context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.IO;
namespace jmespath.net.compliance
{
/// <summary>
/// Provides color support to Console output.
/// The methods of this class are thread-safe to
/// prevent color corruption in case of crash.
/// </summary>
public class ConsoleEx
{
private static readonly object sync_;
private static readonly Writer out_;
private static readonly Writer err_;
static ConsoleEx()
{
sync_ = new Object();
out_ = new Writer(Console.Out, sync_);
err_ = new Writer(Console.Error, sync_);
}
/// <summary>
/// Gets the Console STDOUT writer.
/// </summary>
public static Writer Out => out_;
/// <summary>
/// Gets the Console STDERR writer.
/// </summary>
public static Writer Error => err_;
public sealed class Writer
{
private readonly TextWriter writer_;
private readonly Object synLock_;
/// <summary>
/// Initialize a new instance of the <see cref="Writer"/> class.
/// </summary>
/// <param name="writer"></param>
/// <param name="synLock"></param>
public Writer(TextWriter writer, object synLock)
{
writer_ = writer;
synLock_ = synLock;
DefaultColor = ConsoleColor.Gray;
}
/// <summary>
/// Gets or sets the default Console color.
/// </summary>
public ConsoleColor DefaultColor { get; set; }
/// <summary>
/// Writes a portion of text on the Console with the default color.
/// </summary>
/// <param name="text"></param>
/// <param name="args"></param>
public void Write(string text, params object[] args)
{
Write(DefaultColor, text, args);
}
/// <summary>
/// Writes a line of text on the Console with the default color.
/// </summary>
/// <param name="text"></param>
/// <param name="args"></param>
public void WriteLine(string text, params object[] args)
{
WriteLine(DefaultColor, text, args);
}
/// <summary>
/// Writes a colorized line of text on the Console.
/// </summary>
/// <param name="color"></param>
/// <param name="text"></param>
/// <param name="args"></param>
public void WriteLine(ConsoleColor color, string text, params object[] args)
{
Write(color, text + Environment.NewLine, args);
}
/// <summary>
/// Writes a gray line of text on the Console.
/// </summary>
/// <param name="text"></param>
/// <param name="args"></param>
public void WriteInfo(string text, params object[] args)
{
WriteLine(ConsoleColor.Gray, text, args);
}
/// <summary>
/// Writes a green line of text on the Console.
/// </summary>
/// <param name="text"></param>
/// <param name="args"></param>
public void WriteSuccess(string text, params object[] args)
{
WriteLine(ConsoleColor.Green, text, args);
}
/// <summary>
/// Writes a yellow line of text on the Console.
/// </summary>
/// <param name="text"></param>
/// <param name="args"></param>
public void WriteWarning(string text, params object[] args)
{
WriteLine(ConsoleColor.Yellow, text, args);
}
/// <summary>
/// Writes a red line of text on the Console.
/// </summary>
/// <param name="text"></param>
/// <param name="args"></param>
public void WriteError(string text, params object[] args)
{
WriteLine(ConsoleColor.Red, text, args);
}
public void Write(ConsoleColor color, string text, params object[] args)
{
lock (synLock_)
{
var currentColor = Console.ForegroundColor;
try
{
Console.ForegroundColor = color;
if (args?.Length > 0)
Console.Write(text, args);
else
Console.Write(text);
}
finally
{
Console.ForegroundColor = currentColor;
}
}
}
}
/// <summary>
/// Writes a portion of text on the Console with the default color.
/// </summary>
/// <param name="text"></param>
/// <param name="args"></param>
public static void Write(string text, params object[] args)
{
Out.Write(text, args);
}
/// <summary>
/// Writes a line of text on the Console with the default color.
/// </summary>
/// <param name="text"></param>
/// <param name="args"></param>
public static void WriteLine(string text, params object[] args)
{
Out.WriteLine(text, args);
}
/// <summary>
/// Writes a colorized line of text on the Console.
/// </summary>
/// <param name="color"></param>
/// <param name="text"></param>
/// <param name="args"></param>
public static void WriteLine(ConsoleColor color, string text, params object[] args)
{
Out.WriteLine(color, text, args);
}
/// <summary>
/// Writes a gray line of text on the Console.
/// </summary>
/// <param name="text"></param>
/// <param name="args"></param>
public static void WriteInfo(string text, params object[] args)
{
Out.WriteInfo(text, args);
}
/// <summary>
/// Writes a green line of text on the Console.
/// </summary>
/// <param name="text"></param>
/// <param name="args"></param>
public static void WriteSuccess(string text, params object[] args)
{
Out.WriteSuccess(text, args);
}
/// <summary>
/// Writes a yellow line of text on the Console.
/// </summary>
/// <param name="text"></param>
/// <param name="args"></param>
public static void WriteWarning(string text, params object[] args)
{
Out.WriteWarning(text, args);
}
/// <summary>
/// Writes a red line of text on the Console.
/// </summary>
/// <param name="text"></param>
/// <param name="args"></param>
public static void WriteError(string text, params object[] args)
{
Error.WriteError(text, args);
}
public static void Write(ConsoleColor color, string text, params object[] args)
{
Out.Write(color, text, args);
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ServiceFabric.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.ServiceFabric;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Cluster update request
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class ClusterUpdateParameters
{
/// <summary>
/// Initializes a new instance of the ClusterUpdateParameters class.
/// </summary>
public ClusterUpdateParameters()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ClusterUpdateParameters class.
/// </summary>
/// <param name="reliabilityLevel">This level is used to set the number
/// of replicas of the system services. Possible values include:
/// 'Bronze', 'Silver', 'Gold'</param>
/// <param name="upgradeMode">Cluster upgrade mode indicates if fabric
/// upgrade is initiated automatically by the system or not. Possible
/// values include: 'Automatic', 'Manual'</param>
/// <param name="clusterCodeVersion">The ServiceFabric code version, if
/// set it, please make sure you have set upgradeMode to Manual,
/// otherwise ,it will fail, if you are using PUT new cluster, you can
/// get the version by using ClusterVersions_List, if you are updating
/// existing cluster, you can get the availableClusterVersions from
/// Clusters_Get</param>
/// <param name="certificate">This primay certificate will be used as
/// cluster node to node security, SSL certificate for cluster
/// management endpoint and default admin client, the certificate
/// should exist in the virtual machine scale sets or Azure key vault,
/// before you add it. It will override original value</param>
/// <param name="clientCertificateThumbprints">The client thumbprint
/// details, it is used for client access for cluster operation, it
/// will override existing collection</param>
/// <param name="clientCertificateCommonNames">List of client
/// certificates to whitelist based on common names.</param>
/// <param name="fabricSettings">List of custom fabric settings to
/// configure the cluster, Note, it will overwrite existing
/// collection</param>
/// <param name="reverseProxyCertificate">Certificate for the reverse
/// proxy</param>
/// <param name="nodeTypes">The list of nodetypes that make up the
/// cluster, it will override</param>
/// <param name="upgradeDescription">The policy to use when upgrading
/// the cluster.</param>
/// <param name="tags">Cluster update parameters</param>
public ClusterUpdateParameters(string reliabilityLevel = default(string), string upgradeMode = default(string), string clusterCodeVersion = default(string), CertificateDescription certificate = default(CertificateDescription), IList<ClientCertificateThumbprint> clientCertificateThumbprints = default(IList<ClientCertificateThumbprint>), IList<ClientCertificateCommonName> clientCertificateCommonNames = default(IList<ClientCertificateCommonName>), IList<SettingsSectionDescription> fabricSettings = default(IList<SettingsSectionDescription>), CertificateDescription reverseProxyCertificate = default(CertificateDescription), IList<NodeTypeDescription> nodeTypes = default(IList<NodeTypeDescription>), ClusterUpgradePolicy upgradeDescription = default(ClusterUpgradePolicy), IDictionary<string, string> tags = default(IDictionary<string, string>))
{
ReliabilityLevel = reliabilityLevel;
UpgradeMode = upgradeMode;
ClusterCodeVersion = clusterCodeVersion;
Certificate = certificate;
ClientCertificateThumbprints = clientCertificateThumbprints;
ClientCertificateCommonNames = clientCertificateCommonNames;
FabricSettings = fabricSettings;
ReverseProxyCertificate = reverseProxyCertificate;
NodeTypes = nodeTypes;
UpgradeDescription = upgradeDescription;
Tags = tags;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets this level is used to set the number of replicas of
/// the system services. Possible values include: 'Bronze', 'Silver',
/// 'Gold'
/// </summary>
[JsonProperty(PropertyName = "properties.reliabilityLevel")]
public string ReliabilityLevel { get; set; }
/// <summary>
/// Gets or sets cluster upgrade mode indicates if fabric upgrade is
/// initiated automatically by the system or not. Possible values
/// include: 'Automatic', 'Manual'
/// </summary>
[JsonProperty(PropertyName = "properties.upgradeMode")]
public string UpgradeMode { get; set; }
/// <summary>
/// Gets or sets the ServiceFabric code version, if set it, please make
/// sure you have set upgradeMode to Manual, otherwise ,it will fail,
/// if you are using PUT new cluster, you can get the version by using
/// ClusterVersions_List, if you are updating existing cluster, you can
/// get the availableClusterVersions from Clusters_Get
/// </summary>
[JsonProperty(PropertyName = "properties.clusterCodeVersion")]
public string ClusterCodeVersion { get; set; }
/// <summary>
/// Gets or sets this primay certificate will be used as cluster node
/// to node security, SSL certificate for cluster management endpoint
/// and default admin client, the certificate should exist in the
/// virtual machine scale sets or Azure key vault, before you add it.
/// It will override original value
/// </summary>
[JsonProperty(PropertyName = "properties.certificate")]
public CertificateDescription Certificate { get; set; }
/// <summary>
/// Gets or sets the client thumbprint details, it is used for client
/// access for cluster operation, it will override existing collection
/// </summary>
[JsonProperty(PropertyName = "properties.clientCertificateThumbprints")]
public IList<ClientCertificateThumbprint> ClientCertificateThumbprints { get; set; }
/// <summary>
/// Gets or sets list of client certificates to whitelist based on
/// common names.
/// </summary>
[JsonProperty(PropertyName = "properties.clientCertificateCommonNames")]
public IList<ClientCertificateCommonName> ClientCertificateCommonNames { get; set; }
/// <summary>
/// Gets or sets list of custom fabric settings to configure the
/// cluster, Note, it will overwrite existing collection
/// </summary>
[JsonProperty(PropertyName = "properties.fabricSettings")]
public IList<SettingsSectionDescription> FabricSettings { get; set; }
/// <summary>
/// Gets or sets certificate for the reverse proxy
/// </summary>
[JsonProperty(PropertyName = "properties.reverseProxyCertificate")]
public CertificateDescription ReverseProxyCertificate { get; set; }
/// <summary>
/// Gets or sets the list of nodetypes that make up the cluster, it
/// will override
/// </summary>
[JsonProperty(PropertyName = "properties.nodeTypes")]
public IList<NodeTypeDescription> NodeTypes { get; set; }
/// <summary>
/// Gets or sets the policy to use when upgrading the cluster.
/// </summary>
[JsonProperty(PropertyName = "properties.upgradeDescription")]
public ClusterUpgradePolicy UpgradeDescription { get; set; }
/// <summary>
/// Gets or sets cluster update parameters
/// </summary>
[JsonProperty(PropertyName = "tags")]
public IDictionary<string, string> Tags { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Certificate != null)
{
Certificate.Validate();
}
if (ClientCertificateThumbprints != null)
{
foreach (var element in ClientCertificateThumbprints)
{
if (element != null)
{
element.Validate();
}
}
}
if (ClientCertificateCommonNames != null)
{
foreach (var element1 in ClientCertificateCommonNames)
{
if (element1 != null)
{
element1.Validate();
}
}
}
if (FabricSettings != null)
{
foreach (var element2 in FabricSettings)
{
if (element2 != null)
{
element2.Validate();
}
}
}
if (ReverseProxyCertificate != null)
{
ReverseProxyCertificate.Validate();
}
if (NodeTypes != null)
{
foreach (var element3 in NodeTypes)
{
if (element3 != null)
{
element3.Validate();
}
}
}
if (UpgradeDescription != null)
{
UpgradeDescription.Validate();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using Android.Support.V4.View;
using Android.Views;
using Xamarin.Forms.Internals;
using AView = Android.Views.View;
namespace Xamarin.Forms.Platform.Android
{
public abstract class VisualElementRenderer<TElement> : FormsViewGroup, IVisualElementRenderer, AView.IOnTouchListener, AView.IOnClickListener, IEffectControlProvider where TElement : VisualElement
{
readonly List<EventHandler<VisualElementChangedEventArgs>> _elementChangedHandlers = new List<EventHandler<VisualElementChangedEventArgs>>();
readonly Lazy<GestureDetector> _gestureDetector;
readonly PanGestureHandler _panGestureHandler;
readonly PinchGestureHandler _pinchGestureHandler;
readonly TapGestureHandler _tapGestureHandler;
NotifyCollectionChangedEventHandler _collectionChangeHandler;
VisualElementRendererFlags _flags = VisualElementRendererFlags.AutoPackage | VisualElementRendererFlags.AutoTrack;
InnerGestureListener _gestureListener;
VisualElementPackager _packager;
PropertyChangedEventHandler _propertyChangeHandler;
Lazy<ScaleGestureDetector> _scaleDetector;
protected VisualElementRenderer() : base(Forms.Context)
{
_tapGestureHandler = new TapGestureHandler(() => View);
_panGestureHandler = new PanGestureHandler(() => View, Context.FromPixels);
_pinchGestureHandler = new PinchGestureHandler(() => View);
_gestureDetector =
new Lazy<GestureDetector>(
() =>
new GestureDetector(
_gestureListener =
new InnerGestureListener(_tapGestureHandler.OnTap, _tapGestureHandler.TapGestureRecognizers, _panGestureHandler.OnPan, _panGestureHandler.OnPanStarted, _panGestureHandler.OnPanComplete)));
_scaleDetector = new Lazy<ScaleGestureDetector>(
() => new ScaleGestureDetector(Context, new InnerScaleListener(_pinchGestureHandler.OnPinch, _pinchGestureHandler.OnPinchStarted, _pinchGestureHandler.OnPinchEnded))
);
}
public TElement Element { get; private set; }
protected bool AutoPackage
{
get { return (_flags & VisualElementRendererFlags.AutoPackage) != 0; }
set
{
if (value)
_flags |= VisualElementRendererFlags.AutoPackage;
else
_flags &= ~VisualElementRendererFlags.AutoPackage;
}
}
protected bool AutoTrack
{
get { return (_flags & VisualElementRendererFlags.AutoTrack) != 0; }
set
{
if (value)
_flags |= VisualElementRendererFlags.AutoTrack;
else
_flags &= ~VisualElementRendererFlags.AutoTrack;
}
}
View View => Element as View;
void IEffectControlProvider.RegisterEffect(Effect effect)
{
var platformEffect = effect as PlatformEffect;
if (platformEffect != null)
OnRegisterEffect(platformEffect);
}
void IOnClickListener.OnClick(AView v)
{
_tapGestureHandler.OnSingleClick();
}
public override bool OnInterceptTouchEvent(MotionEvent ev)
{
if (Element != null && Element.InputTransparent && Element.IsEnabled)
return false;
return base.OnInterceptTouchEvent(ev);
}
bool IOnTouchListener.OnTouch(AView v, MotionEvent e)
{
if (Element == null || !Element.IsEnabled)
return true;
if (Element.InputTransparent)
return false;
var handled = false;
if (_pinchGestureHandler.IsPinchSupported)
{
if (!_scaleDetector.IsValueCreated)
ScaleGestureDetectorCompat.SetQuickScaleEnabled(_scaleDetector.Value, true);
handled = _scaleDetector.Value.OnTouchEvent(e);
}
_gestureListener?.OnTouchEvent(e);
return _gestureDetector.Value.OnTouchEvent(e) || handled;
}
VisualElement IVisualElementRenderer.Element => Element;
event EventHandler<VisualElementChangedEventArgs> IVisualElementRenderer.ElementChanged
{
add { _elementChangedHandlers.Add(value); }
remove { _elementChangedHandlers.Remove(value); }
}
public virtual SizeRequest GetDesiredSize(int widthConstraint, int heightConstraint)
{
//HACK: Seeing some places the renderer is disposed and this happens
if (Handle == IntPtr.Zero)
return new SizeRequest();
Measure(widthConstraint, heightConstraint);
return new SizeRequest(new Size(MeasuredWidth, MeasuredHeight), MinimumSize());
}
void IVisualElementRenderer.SetElement(VisualElement element)
{
if (!(element is TElement))
throw new ArgumentException("element is not of type " + typeof(TElement), nameof(element));
SetElement((TElement)element);
}
public VisualElementTracker Tracker { get; private set; }
public void UpdateLayout()
{
Performance.Start();
Tracker?.UpdateLayout();
Performance.Stop();
}
public ViewGroup ViewGroup => this;
public event EventHandler<ElementChangedEventArgs<TElement>> ElementChanged;
public void SetElement(TElement element)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
TElement oldElement = Element;
Element = element;
Performance.Start();
if (oldElement != null)
{
oldElement.PropertyChanged -= _propertyChangeHandler;
UnsubscribeGestureRecognizers(oldElement);
}
// element may be allowed to be passed as null in the future
if (element != null)
{
Color currentColor = oldElement != null ? oldElement.BackgroundColor : Color.Default;
if (element.BackgroundColor != currentColor)
UpdateBackgroundColor();
}
if (_propertyChangeHandler == null)
{
//HACK: we are seeing situations where INPC fires and the renderer is disposed, this fix seems to work globally
_propertyChangeHandler = (sender, e) =>
{
if (Handle == IntPtr.Zero)
return;
OnElementPropertyChanged(sender, e);
};
}
element.PropertyChanged += _propertyChangeHandler;
SubscribeGestureRecognizers(element);
if (oldElement == null)
{
SetOnClickListener(this);
SetOnTouchListener(this);
SoundEffectsEnabled = false;
}
InputTransparent = Element.InputTransparent;
// must be updated AFTER SetOnClickListener is called
// SetOnClickListener implicitly calls Clickable = true
UpdateGestureRecognizers(true);
OnElementChanged(new ElementChangedEventArgs<TElement>(oldElement, element));
if (AutoPackage && _packager == null)
SetPackager(new VisualElementPackager(this));
if (AutoTrack && Tracker == null)
SetTracker(new VisualElementTracker(this));
if (element != null)
SendVisualElementInitialized(element, this);
EffectUtilities.RegisterEffectControlProvider(this, oldElement, element);
if (element != null && !string.IsNullOrEmpty(element.AutomationId))
SetAutomationId(element.AutomationId);
Performance.Stop();
}
/// <summary>
/// Determines whether the native control is disposed of when this renderer is disposed
/// Can be overridden in deriving classes
/// </summary>
protected virtual bool ManageNativeControlLifetime => true;
protected override void Dispose(bool disposing)
{
if ((_flags & VisualElementRendererFlags.Disposed) != 0)
return;
_flags |= VisualElementRendererFlags.Disposed;
if (disposing)
{
SetOnClickListener(null);
SetOnTouchListener(null);
if (Tracker != null)
{
Tracker.Dispose();
Tracker = null;
}
if (_packager != null)
{
_packager.Dispose();
_packager = null;
}
if (_scaleDetector != null && _scaleDetector.IsValueCreated)
{
_scaleDetector.Value.Dispose();
_scaleDetector = null;
}
if (_gestureListener != null)
{
_gestureListener.Dispose();
_gestureListener = null;
}
if (ManageNativeControlLifetime)
{
int count = ChildCount;
for (var i = 0; i < count; i++)
{
AView child = GetChildAt(i);
child.Dispose();
}
}
RemoveAllViews();
if (Element != null)
{
Element.PropertyChanged -= _propertyChangeHandler;
UnsubscribeGestureRecognizers(Element);
if (Platform.GetRenderer(Element) == this)
Platform.SetRenderer(Element, null);
Element = null;
}
}
base.Dispose(disposing);
}
protected virtual Size MinimumSize()
{
return new Size();
}
protected virtual void OnElementChanged(ElementChangedEventArgs<TElement> e)
{
var args = new VisualElementChangedEventArgs(e.OldElement, e.NewElement);
foreach (EventHandler<VisualElementChangedEventArgs> handler in _elementChangedHandlers)
handler(this, args);
ElementChanged?.Invoke(this, e);
}
protected virtual void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName)
UpdateBackgroundColor();
else if (e.PropertyName == VisualElement.InputTransparentProperty.PropertyName)
InputTransparent = Element.InputTransparent;
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
if (Element == null)
return;
ReadOnlyCollection<Element> children = ((IElementController)Element).LogicalChildren;
foreach (Element element in children)
{
var visualElement = element as VisualElement;
if (visualElement == null)
continue;
IVisualElementRenderer renderer = Platform.GetRenderer(visualElement);
renderer?.UpdateLayout();
}
}
protected virtual void OnRegisterEffect(PlatformEffect effect)
{
effect.Container = this;
}
protected virtual void SetAutomationId(string id)
{
ContentDescription = id;
}
protected void SetPackager(VisualElementPackager packager)
{
_packager = packager;
packager.Load();
}
protected void SetTracker(VisualElementTracker tracker)
{
Tracker = tracker;
}
protected virtual void UpdateBackgroundColor()
{
SetBackgroundColor(Element.BackgroundColor.ToAndroid());
}
internal virtual void SendVisualElementInitialized(VisualElement element, AView nativeView)
{
element.SendViewInitialized(nativeView);
}
void HandleGestureRecognizerCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
{
UpdateGestureRecognizers();
}
void SubscribeGestureRecognizers(VisualElement element)
{
var view = element as View;
if (view == null)
return;
if (_collectionChangeHandler == null)
_collectionChangeHandler = HandleGestureRecognizerCollectionChanged;
var observableCollection = (ObservableCollection<IGestureRecognizer>)view.GestureRecognizers;
observableCollection.CollectionChanged += _collectionChangeHandler;
}
void UnsubscribeGestureRecognizers(VisualElement element)
{
var view = element as View;
if (view == null || _collectionChangeHandler == null)
return;
var observableCollection = (ObservableCollection<IGestureRecognizer>)view.GestureRecognizers;
observableCollection.CollectionChanged -= _collectionChangeHandler;
}
void UpdateClickable(bool force = false)
{
var view = Element as View;
if (view == null)
return;
bool newValue = view.ShouldBeMadeClickable();
if (force || newValue)
Clickable = newValue;
}
void UpdateGestureRecognizers(bool forceClick = false)
{
if (View == null)
return;
UpdateClickable(forceClick);
}
}
}
| |
// 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.Data.Common;
using System.Diagnostics;
namespace System.Data.SqlClient
{
internal sealed class SqlStatistics
{
internal static SqlStatistics StartTimer(SqlStatistics statistics)
{
if ((null != statistics) && !statistics.RequestExecutionTimer())
{
// we're re-entrant -- don't bother.
statistics = null;
}
return statistics;
}
internal static void StopTimer(SqlStatistics statistics)
{
if (null != statistics)
{
statistics.ReleaseAndUpdateExecutionTimer();
}
}
// internal values that are not exposed through properties
internal long _closeTimestamp;
internal long _openTimestamp;
internal long _startExecutionTimestamp;
internal long _startFetchTimestamp;
internal long _startNetworkServerTimestamp;
// internal values that are exposed through properties
internal long _buffersReceived;
internal long _buffersSent;
internal long _bytesReceived;
internal long _bytesSent;
internal long _connectionTime;
internal long _cursorOpens;
internal long _executionTime;
internal long _iduCount;
internal long _iduRows;
internal long _networkServerTime;
internal long _preparedExecs;
internal long _prepares;
internal long _selectCount;
internal long _selectRows;
internal long _serverRoundtrips;
internal long _sumResultSets;
internal long _transactions;
internal long _unpreparedExecs;
// these flags are required if statistics is turned on/off in the middle of command execution
private bool _waitForDoneAfterRow;
private bool _waitForReply;
internal bool WaitForDoneAfterRow
{
get
{
return _waitForDoneAfterRow;
}
set
{
_waitForDoneAfterRow = value;
}
}
internal bool WaitForReply
{
get
{
return _waitForReply;
}
}
internal SqlStatistics()
{
}
internal void ContinueOnNewConnection()
{
_startExecutionTimestamp = 0;
_startFetchTimestamp = 0;
_waitForDoneAfterRow = false;
_waitForReply = false;
}
internal IDictionary GetDictionary()
{
const int Count = 18;
var dictionary = new StatisticsDictionary(Count)
{
{ "BuffersReceived", _buffersReceived },
{ "BuffersSent", _buffersSent },
{ "BytesReceived", _bytesReceived },
{ "BytesSent", _bytesSent },
{ "CursorOpens", _cursorOpens },
{ "IduCount", _iduCount },
{ "IduRows", _iduRows },
{ "PreparedExecs", _preparedExecs },
{ "Prepares", _prepares },
{ "SelectCount", _selectCount },
{ "SelectRows", _selectRows },
{ "ServerRoundtrips", _serverRoundtrips },
{ "SumResultSets", _sumResultSets },
{ "Transactions", _transactions },
{ "UnpreparedExecs", _unpreparedExecs },
{ "ConnectionTime", ADP.TimerToMilliseconds(_connectionTime) },
{ "ExecutionTime", ADP.TimerToMilliseconds(_executionTime) },
{ "NetworkServerTime", ADP.TimerToMilliseconds(_networkServerTime) }
};
Debug.Assert(dictionary.Count == Count);
return dictionary;
}
internal bool RequestExecutionTimer()
{
if (_startExecutionTimestamp == 0)
{
ADP.TimerCurrent(out _startExecutionTimestamp);
return true;
}
return false;
}
internal void RequestNetworkServerTimer()
{
Debug.Assert(_startExecutionTimestamp != 0, "No network time expected outside execution period");
if (_startNetworkServerTimestamp == 0)
{
ADP.TimerCurrent(out _startNetworkServerTimestamp);
}
_waitForReply = true;
}
internal void ReleaseAndUpdateExecutionTimer()
{
if (_startExecutionTimestamp > 0)
{
_executionTime += (ADP.TimerCurrent() - _startExecutionTimestamp);
_startExecutionTimestamp = 0;
}
}
internal void ReleaseAndUpdateNetworkServerTimer()
{
if (_waitForReply && _startNetworkServerTimestamp > 0)
{
_networkServerTime += (ADP.TimerCurrent() - _startNetworkServerTimestamp);
_startNetworkServerTimestamp = 0;
}
_waitForReply = false;
}
internal void Reset()
{
_buffersReceived = 0;
_buffersSent = 0;
_bytesReceived = 0;
_bytesSent = 0;
_connectionTime = 0;
_cursorOpens = 0;
_executionTime = 0;
_iduCount = 0;
_iduRows = 0;
_networkServerTime = 0;
_preparedExecs = 0;
_prepares = 0;
_selectCount = 0;
_selectRows = 0;
_serverRoundtrips = 0;
_sumResultSets = 0;
_transactions = 0;
_unpreparedExecs = 0;
_waitForDoneAfterRow = false;
_waitForReply = false;
_startExecutionTimestamp = 0;
_startNetworkServerTimestamp = 0;
}
internal void SafeAdd(ref long value, long summand)
{
if (long.MaxValue - value > summand)
{
value += summand;
}
else
{
value = long.MaxValue;
}
}
internal long SafeIncrement(ref long value)
{
if (value < long.MaxValue) value++;
return value;
}
internal void UpdateStatistics()
{
// update connection time
if (_closeTimestamp >= _openTimestamp)
{
SafeAdd(ref _connectionTime, _closeTimestamp - _openTimestamp);
}
else
{
_connectionTime = long.MaxValue;
}
}
// We subclass Dictionary to provide our own implementation of GetEnumerator, CopyTo, Keys.CopyTo,
// and Values.CopyTo to match the behavior of Hashtable, which is used in the full framework:
//
// - Hashtable's IEnumerator.GetEnumerator enumerator yields DictionaryEntry entries whereas
// Dictionary's yields KeyValuePair entries.
//
// - When arrayIndex > array.Length, Hashtable throws ArgumentException whereas Dictionary
// throws ArgumentOutOfRangeException.
//
// - Hashtable specifies the ArgumentOutOfRangeException paramName as "arrayIndex" whereas
// Dictionary uses "index".
//
// - When the array is of a mismatched type, Hashtable throws InvalidCastException whereas
// Dictionary throws ArrayTypeMismatchException.
//
// - Hashtable allows copying values to a long[] array via Values.CopyTo, whereas Dictionary
// throws ArgumentException due to the "Target array type is not compatible with type of
// items in the collection" (when Dictionary<object, object> is used).
//
// Ideally this would derive from Dictionary<string, long>, but that would break compatibility
// with the full framework, which allows adding keys/values of any type.
private sealed class StatisticsDictionary : Dictionary<object, object>, IDictionary, IEnumerable
{
private Collection _keys;
private Collection _values;
public StatisticsDictionary(int capacity) : base(capacity) { }
ICollection IDictionary.Keys => _keys ?? (_keys = new Collection(this, Keys));
ICollection IDictionary.Values => _values ?? (_values = new Collection(this, Values));
// Return a DictionaryEntry enumerator instead of a KeyValuePair enumerator.
IEnumerator IEnumerable.GetEnumerator() => ((IDictionary)this).GetEnumerator();
void ICollection.CopyTo(Array array, int arrayIndex)
{
ValidateCopyToArguments(array, arrayIndex);
foreach (KeyValuePair<object, object> pair in this)
{
var entry = new DictionaryEntry(pair.Key, pair.Value);
array.SetValue(entry, arrayIndex++);
}
}
private void CopyKeys(Array array, int arrayIndex)
{
ValidateCopyToArguments(array, arrayIndex);
foreach (KeyValuePair<object, object> pair in this)
{
array.SetValue(pair.Key, arrayIndex++);
}
}
private void CopyValues(Array array, int arrayIndex)
{
ValidateCopyToArguments(array, arrayIndex);
foreach (KeyValuePair<object, object> pair in this)
{
array.SetValue(pair.Value, arrayIndex++);
}
}
private void ValidateCopyToArguments(Array array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - arrayIndex < Count)
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
private sealed class Collection : ICollection
{
private readonly StatisticsDictionary _dictionary;
private readonly ICollection _collection;
public Collection(StatisticsDictionary dictionary, ICollection collection)
{
Debug.Assert(dictionary != null);
Debug.Assert(collection != null);
Debug.Assert((collection is KeyCollection) || (collection is ValueCollection));
_dictionary = dictionary;
_collection = collection;
}
int ICollection.Count => _collection.Count;
bool ICollection.IsSynchronized => _collection.IsSynchronized;
object ICollection.SyncRoot => _collection.SyncRoot;
void ICollection.CopyTo(Array array, int arrayIndex)
{
if (_collection is KeyCollection)
{
_dictionary.CopyKeys(array, arrayIndex);
}
else
{
_dictionary.CopyValues(array, arrayIndex);
}
}
IEnumerator IEnumerable.GetEnumerator() => _collection.GetEnumerator();
}
}
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org.
// ****************************************************************
using System;
using System.IO;
using NUnit.Framework;
namespace NUnit.Util.Tests
{
[TestFixture]
public class PathUtilTests : PathUtils
{
[Test]
public void CheckDefaults()
{
Assert.AreEqual( Path.DirectorySeparatorChar, PathUtils.DirectorySeparatorChar );
Assert.AreEqual( Path.AltDirectorySeparatorChar, PathUtils.AltDirectorySeparatorChar );
}
}
// Local Assert extension
internal class Assert : NUnit.Framework.Assert
{
public static void SamePath( string path1, string path2 )
{
string msg = "\r\n\texpected: Same path as <{0}>\r\n\t but was: <{1}>";
Assert.IsTrue( PathUtils.SamePath( path1, path2 ), msg, path1, path2 );
}
public static void NotSamePath( string path1, string path2 )
{
string msg = "\r\n\texpected: Not same path as <{0}>\r\n\t but was: <{1}>";
Assert.IsFalse( PathUtils.SamePath( path1, path2 ), msg, path1, path2 );
}
public static void SamePathOrUnder( string path1, string path2 )
{
string msg = "\r\n\texpected: Same path or under <{0}>\r\n\t but was: <{1}>";
Assert.IsTrue( PathUtils.SamePathOrUnder( path1, path2 ), msg, path1, path2 );
}
public static void NotSamePathOrUnder( string path1, string path2 )
{
string msg = "\r\n\texpected: Not same path or under <{0}>\r\n\t but was: <{1}>";
Assert.IsFalse( PathUtils.SamePathOrUnder( path1, path2 ), msg, path1, path2 );
}
}
[TestFixture]
public class PathUtilTests_Windows : PathUtils
{
[TestFixtureSetUp]
public static void SetUpUnixSeparators()
{
PathUtils.DirectorySeparatorChar = '\\';
PathUtils.AltDirectorySeparatorChar = '/';
}
[TestFixtureTearDown]
public static void RestoreDefaultSeparators()
{
PathUtils.DirectorySeparatorChar = System.IO.Path.DirectorySeparatorChar;
PathUtils.AltDirectorySeparatorChar = System.IO.Path.AltDirectorySeparatorChar;
}
[Test]
public void IsAssemblyFileType()
{
Assert.IsTrue( PathUtils.IsAssemblyFileType( @"c:\bin\test.dll" ) );
Assert.IsTrue( PathUtils.IsAssemblyFileType( @"test.exe" ) );
Assert.IsFalse( PathUtils.IsAssemblyFileType( @"c:\bin\test.nunit" ) );
}
[Test]
public void Canonicalize()
{
Assert.AreEqual( @"C:\folder1\file.tmp",
PathUtils.Canonicalize( @"C:\folder1\.\folder2\..\file.tmp" ) );
Assert.AreEqual( @"folder1\file.tmp",
PathUtils.Canonicalize( @"folder1\.\folder2\..\file.tmp" ) );
Assert.AreEqual( @"folder1\file.tmp",
PathUtils.Canonicalize( @"folder1\folder2\.\..\file.tmp" ) );
Assert.AreEqual( @"file.tmp",
PathUtils.Canonicalize( @"folder1\folder2\..\.\..\file.tmp" ) );
Assert.AreEqual( @"file.tmp",
PathUtils.Canonicalize( @"folder1\folder2\..\..\..\file.tmp" ) );
}
[Test]
[Platform(Exclude="Linux")]
public void RelativePath()
{
Assert.AreEqual( @"folder2\folder3", PathUtils.RelativePath(
@"c:\folder1", @"c:\folder1\folder2\folder3" ) );
Assert.AreEqual( @"..\folder2\folder3", PathUtils.RelativePath(
@"c:\folder1", @"c:\folder2\folder3" ) );
Assert.AreEqual( @"bin\debug", PathUtils.RelativePath(
@"c:\folder1", @"bin\debug" ) );
Assert.IsNull( PathUtils.RelativePath( @"C:\folder", @"D:\folder" ),
"Unrelated paths should return null" );
Assert.IsNull(PathUtils.RelativePath(@"C:\", @"D:\"),
"Unrelated roots should return null");
Assert.IsNull(PathUtils.RelativePath(@"C:", @"D:"),
"Unrelated roots (no trailing separators) should return null");
Assert.AreEqual(string.Empty,
PathUtils.RelativePath(@"C:\folder1", @"C:\folder1"));
Assert.AreEqual(string.Empty,
PathUtils.RelativePath(@"C:\", @"C:\"));
// First path consisting just of a root:
Assert.AreEqual(@"folder1\folder2", PathUtils.RelativePath(
@"C:\", @"C:\folder1\folder2"));
// Trailing directory separator in first path shall be ignored:
Assert.AreEqual(@"folder2\folder3", PathUtils.RelativePath(
@"c:\folder1\", @"c:\folder1\folder2\folder3"));
// Case-insensitive behaviour, preserving 2nd path directories in result:
Assert.AreEqual(@"Folder2\Folder3", PathUtils.RelativePath(
@"C:\folder1", @"c:\folder1\Folder2\Folder3"));
Assert.AreEqual(@"..\Folder2\folder3", PathUtils.RelativePath(
@"c:\folder1", @"C:\Folder2\folder3"));
}
[Test]
public void SamePath()
{
Assert.SamePath( @"C:\folder1\file.tmp", @"c:\folder1\File.TMP" );
Assert.SamePath( @"C:\folder1\file.tmp", @"C:\folder1\.\folder2\..\file.tmp" );
Assert.NotSamePath( @"C:\folder1\file.tmp", @"C:\folder1\.\folder2\..\file.temp" );
Assert.SamePath( "D:/folder1/folder2", @"d:\Folder1\Folder2" );
}
[Test]
public void SamePathOrUnder()
{
Assert.SamePathOrUnder( @"C:\folder1\folder2\folder3", @"c:\folder1\.\folder2\junk\..\folder3" );
Assert.SamePathOrUnder( @"C:\folder1\folder2\", @"c:\folder1\.\folder2\junk\..\folder3" );
Assert.SamePathOrUnder( @"C:\folder1\folder2", @"c:\folder1\.\folder2\junk\..\folder3" );
Assert.SamePathOrUnder( @"C:\folder1\folder2", @"c:\folder1\.\Folder2\junk\..\folder3" );
Assert.NotSamePathOrUnder( @"C:\folder1\folder2", @"c:\folder1\.\folder22\junk\..\folder3" );
Assert.NotSamePathOrUnder( @"C:\folder1\folder2ile.tmp", @"D:\folder1\.\folder2\folder3\file.tmp" );
Assert.NotSamePathOrUnder( @"C:\", @"D:\" );
Assert.SamePathOrUnder( @"C:\", @"c:\" );
Assert.SamePathOrUnder( @"C:\", @"c:\bin\debug" );
}
[Test]
public void PathFromUri()
{
Assert.AreEqual( @"C:\a\b\c\my.dll", PathUtils.GetAssemblyPathFromFileUri( @"file:///C:\a\b\c\my.dll" ) );
Assert.AreEqual( @"C:\a\b\c\my.dll", PathUtils.GetAssemblyPathFromFileUri( @"file://C:\a\b\c\my.dll" ) );
}
}
[TestFixture]
public class PathUtilTests_Unix : PathUtils
{
[TestFixtureSetUp]
public static void SetUpUnixSeparators()
{
PathUtils.DirectorySeparatorChar = '/';
PathUtils.AltDirectorySeparatorChar = '\\';
}
[TestFixtureTearDown]
public static void RestoreDefaultSeparators()
{
PathUtils.DirectorySeparatorChar = System.IO.Path.DirectorySeparatorChar;
PathUtils.AltDirectorySeparatorChar = System.IO.Path.AltDirectorySeparatorChar;
}
[Test]
public void IsAssemblyFileType()
{
Assert.IsTrue( PathUtils.IsAssemblyFileType( "/bin/test.dll" ) );
Assert.IsTrue( PathUtils.IsAssemblyFileType( "test.exe" ) );
Assert.IsFalse( PathUtils.IsAssemblyFileType( "/bin/test.nunit" ) );
}
[Test]
public void Canonicalize()
{
Assert.AreEqual( "/folder1/file.tmp",
PathUtils.Canonicalize( "/folder1/./folder2/../file.tmp" ) );
Assert.AreEqual( "folder1/file.tmp",
PathUtils.Canonicalize( "folder1/./folder2/../file.tmp" ) );
Assert.AreEqual( "folder1/file.tmp",
PathUtils.Canonicalize( "folder1/folder2/./../file.tmp" ) );
Assert.AreEqual( "file.tmp",
PathUtils.Canonicalize( "folder1/folder2/.././../file.tmp" ) );
Assert.AreEqual( "file.tmp",
PathUtils.Canonicalize( "folder1/folder2/../../../file.tmp" ) );
}
[Test]
public void RelativePath()
{
Assert.AreEqual( "folder2/folder3",
PathUtils.RelativePath( "/folder1", "/folder1/folder2/folder3" ) );
Assert.AreEqual( "../folder2/folder3",
PathUtils.RelativePath( "/folder1", "/folder2/folder3" ) );
Assert.AreEqual( "bin/debug",
PathUtils.RelativePath( "/folder1", "bin/debug" ) );
Assert.AreEqual( "../other/folder",
PathUtils.RelativePath( "/folder", "/other/folder" ) );
Assert.AreEqual( "../../d",
PathUtils.RelativePath( "/a/b/c", "/a/d" ) );
Assert.AreEqual(string.Empty,
PathUtils.RelativePath("/a/b", "/a/b"));
Assert.AreEqual(string.Empty,
PathUtils.RelativePath("/", "/"));
// First path consisting just of a root:
Assert.AreEqual("folder1/folder2", PathUtils.RelativePath(
"/", "/folder1/folder2"));
// Trailing directory separator in first path shall be ignored:
Assert.AreEqual("folder2/folder3", PathUtils.RelativePath(
"/folder1/", "/folder1/folder2/folder3"));
// Case-sensitive behaviour:
Assert.AreEqual("../Folder1/Folder2/folder3",
PathUtils.RelativePath("/folder1", "/Folder1/Folder2/folder3"),
"folders differing in case");
}
[Test]
public void SamePath()
{
Assert.SamePath( "/folder1/file.tmp", "/folder1/./folder2/../file.tmp" );
Assert.NotSamePath( "/folder1/file.tmp", "/folder1/File.TMP" );
Assert.NotSamePath( "/folder1/file.tmp", "/folder1/./folder2/../file.temp" );
Assert.SamePath( "/folder1/folder2", @"\folder1\folder2" );
}
[Test]
public void SamePathOrUnder()
{
Assert.SamePathOrUnder( "/folder1/folder2/folder3", "/folder1/./folder2/junk/../folder3" );
Assert.SamePathOrUnder( "/folder1/folder2/", "/folder1/./folder2/junk/../folder3" );
Assert.SamePathOrUnder( "/folder1/folder2", "/folder1/./folder2/junk/../folder3" );
Assert.NotSamePathOrUnder( "/folder1/folder2", "/folder1/./Folder2/junk/../folder3" );
Assert.NotSamePathOrUnder( "/folder1/folder2", "/folder1/./folder22/junk/../folder3" );
Assert.SamePathOrUnder( "/", "/" );
Assert.SamePathOrUnder( "/", "/bin/debug" );
}
[Test]
public void PathFromUri()
{
Assert.AreEqual( @"/a/b/c/my.dll", PathUtils.GetAssemblyPathFromFileUri( @"file:///a/b/c/my.dll" ) );
Assert.AreEqual( @"/a/b/c/my.dll", PathUtils.GetAssemblyPathFromFileUri( @"file://a/b/c/my.dll" ) );
}
}
}
| |
using Android.OS;
using Android.Views;
using System;
using System.Reactive;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Accord;
using Android.Runtime;
using Android.Support.Constraints;
using AndroidX.Fragment.App;
using AndroidX.ViewPager.Widget;
using Toggl.Core;
using Toggl.Core.UI.ViewModels.Calendar;
using Toggl.Droid.Activities;
using Toggl.Droid.Extensions;
using Toggl.Droid.Extensions.Reactive;
using Toggl.Droid.Fragments.Calendar;
using Toggl.Droid.Helper;
using Toggl.Droid.Presentation;
using Toggl.Droid.ViewHolders;
using Toggl.Droid.Views.Calendar;
using Toggl.Shared.Extensions;
using Toggl.Shared.Extensions.Reactive;
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Support.V4.Content;
using Android.Text;
using Toggl.Core.Analytics;
using Toggl.Core.Extensions;
using Toggl.Core.Models.Interfaces;
using Toggl.Core.UI.Helper;
using static Toggl.Core.Helper.Constants;
namespace Toggl.Droid.Fragments
{
public partial class CalendarFragment : ReactiveTabFragment<CalendarViewModel>, IScrollableToStart, IBackPressHandler
{
public static int NumberOfDaysInTheWeek = 7;
private const int pastCalendarPagesCount = CalendarMaxPastDays;
private const int futureCalendarPagesCount = CalendarMaxFutureDays;
private const int calendarPagesCount = pastCalendarPagesCount + futureCalendarPagesCount;
private readonly Subject<bool> scrollToStartSignaler = new Subject<bool>();
private CalendarDayFragmentAdapter calendarDayAdapter;
private CalendarWeekStripeAdapter calendarWeekStripeAdapter;
private ITimeService timeService;
private int defaultToolbarElevationInDPs;
private bool hasResumedOnce = false;
private bool isChangingPageFromUserInteraction = true;
private Drawable addDrawable;
private Drawable playDrawable;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.CalendarFragment, container, false);
InitializeViews(view);
SetupToolbar(view);
timeService = AndroidDependencyContainer.Instance.TimeService;
defaultToolbarElevationInDPs = 4.DpToPixels(Context);
return view;
}
public override void OnViewCreated(View view, Bundle savedInstanceState)
{
base.OnViewCreated(view, savedInstanceState);
calendarDayAdapter = new CalendarDayFragmentAdapter(Context, ViewModel, scrollToStartSignaler, ChildFragmentManager);
var startingCalendarDayViewPage = calculateDayViewPage(ViewModel.CurrentlyShownDate.Value);
calendarDayAdapter.CurrentPageRelay.Accept(startingCalendarDayViewPage);
calendarViewPager.Adapter = calendarDayAdapter;
calendarViewPager.SetCurrentItem(startingCalendarDayViewPage, false);
calendarViewPager.AddOnPageChangeListener(calendarDayAdapter);
calendarViewPager.SetPageTransformer(false, new VerticalOffsetPageTransformer(calendarDayAdapter.HourHeightRelay, calendarDayAdapter.OffsetRelay));
calendarDayAdapter.CurrentPageRelay
.Select(getDateAtAdapterPosition)
.Subscribe(configureHeaderDate)
.DisposedBy(DisposeBag);
calendarDayAdapter.OffsetRelay
.Select(offset => offset == 0)
.DistinctUntilChanged()
.Subscribe(updateAppbarElevation)
.DisposedBy(DisposeBag);
calendarDayAdapter.MenuVisibilityRelay
.Subscribe(swipeIsLocked =>
{
calendarViewPager.IsLocked = swipeIsLocked;
calendarWeekStripePager.IsLocked = swipeIsLocked;
})
.DisposedBy(DisposeBag);
void clickOnTopWeekDatePicker(CalendarWeeklyViewDayViewModel day)
{
if (calendarDayAdapter.MenuVisibilityRelay.Value)
return;
isChangingPageFromUserInteraction = false;
ViewModel.SelectDayFromWeekView.Inputs.OnNext(day);
}
void swipeOnTopWeekDatePicker()
{
isChangingPageFromUserInteraction = false;
}
calendarWeekStripeAdapter = new CalendarWeekStripeAdapter(clickOnTopWeekDatePicker, swipeOnTopWeekDatePicker, ViewModel.CurrentlyShownDate);
calendarWeekStripePager.AddOnPageChangeListener(calendarWeekStripeAdapter);
calendarWeekStripePager.Adapter = calendarWeekStripeAdapter;
ViewModel.WeekViewHeaders
.Subscribe(updateWeekViewHeaders)
.DisposedBy(DisposeBag);
ViewModel.WeekViewDays
.Subscribe(weekDays =>
{
calendarWeekStripeAdapter.UpdateWeekDays(weekDays);
var updatedCurrentPage = calendarWeekStripeAdapter.GetPageFor(ViewModel.CurrentlyShownDate.Value);
calendarWeekStripePager.SetCurrentItem(updatedCurrentPage, false);
})
.DisposedBy(DisposeBag);
ViewModel.CurrentlyShownDate
.Subscribe(calendarWeekStripeAdapter.UpdateSelectedDay)
.DisposedBy(DisposeBag);
calendarDayAdapter.MenuVisibilityRelay
.Select(CommonFunctions.Invert)
.Subscribe(hideBottomBar)
.DisposedBy(DisposeBag);
calendarViewPager.SetCurrentItem(pastCalendarPagesCount - 1, false);
ViewModel.CurrentlyShownDate
.Select(calculateDayViewPage)
.Subscribe(page => calendarViewPager.SetCurrentItem(page, true))
.DisposedBy(DisposeBag);
var startingPageForCalendarWeekPager = calendarWeekStripeAdapter.GetPageFor(ViewModel.CurrentlyShownDate.Value);
calendarWeekStripePager.SetCurrentItem(startingPageForCalendarWeekPager, false);
ViewModel.CurrentlyShownDate
.Select(calendarWeekStripeAdapter.GetPageFor)
.Subscribe(page => calendarWeekStripePager.SetCurrentItem(page, true))
.DisposedBy(DisposeBag);
calendarDayAdapter.CurrentPageRelay
.DistinctUntilChanged()
.Select(calculateDayForCalendarDayPage)
.Subscribe(ViewModel.CurrentlyShownDate.Accept)
.DisposedBy(DisposeBag);
calendarDayAdapter.TimeTrackedOnDay
.DistinctUntilChanged()
.Subscribe(headerTimeEntriesDurationTextView.Rx().TextObserver())
.DisposedBy(DisposeBag);
calendarWeekStripeLabelsContainer.Rx().TouchEvents()
.Select(eventArgs => eventArgs.Event)
.Subscribe(touch => calendarWeekStripePager.OnTouchEvent(touch))
.DisposedBy(DisposeBag);
calendarDayAdapter.PageChanged
.Subscribe(recordPageSwipeEvent)
.DisposedBy(DisposeBag);
playButton.Rx()
.BindAction(ViewModel.StartTimeEntry, _ => true)
.DisposedBy(DisposeBag);
playButton.Rx()
.BindAction(ViewModel.StartTimeEntry, _ => false, ButtonEventType.LongPress)
.DisposedBy(DisposeBag);
stopButton.Rx()
.BindAction(ViewModel.StopTimeEntry)
.DisposedBy(DisposeBag);
playButton.Rx().TouchEvents()
.Subscribe(handlePlayFabEvent)
.DisposedBy(DisposeBag);
playButton.Rx().LongPress()
.Subscribe(_ => playButton.StopAnimation())
.DisposedBy(DisposeBag);
runningEntryCardFrame.Rx().Tap()
.WithLatestFrom(ViewModel.CurrentRunningTimeEntry,
(_, te) => new EditTimeEntryInfo(EditTimeEntryOrigin.RunningTimeEntryCard, te.Id))
.Subscribe(ViewModel.SelectTimeEntry.Inputs)
.DisposedBy(DisposeBag);
ViewModel.ElapsedTime
.Subscribe(timeEntryCardTimerLabel.Rx().TextObserver())
.DisposedBy(DisposeBag);
ViewModel.CurrentRunningTimeEntry
.Select(te => te?.Description ?? "")
.Subscribe(timeEntryCardDescriptionLabel.Rx().TextObserver())
.DisposedBy(DisposeBag);
ViewModel.CurrentRunningTimeEntry
.Select(te => string.IsNullOrWhiteSpace(te?.Description))
.Subscribe(timeEntryCardAddDescriptionLabel.Rx().IsVisible())
.DisposedBy(DisposeBag);
ViewModel.CurrentRunningTimeEntry
.Select(te => string.IsNullOrWhiteSpace(te?.Description))
.Invert()
.Subscribe(timeEntryCardDescriptionLabel.Rx().IsVisible())
.DisposedBy(DisposeBag);
ViewModel.CurrentRunningTimeEntry
.Select(CreateProjectClientTaskLabel)
.Subscribe(timeEntryCardProjectClientTaskLabel.Rx().TextFormattedObserver())
.DisposedBy(DisposeBag);
var projectVisibilityObservable = ViewModel.CurrentRunningTimeEntry
.Select(te => te?.Project != null);
projectVisibilityObservable
.Subscribe(timeEntryCardProjectClientTaskLabel.Rx().IsVisible())
.DisposedBy(DisposeBag);
projectVisibilityObservable
.Subscribe(timeEntryCardDotContainer.Rx().IsVisible())
.DisposedBy(DisposeBag);
var projectColorObservable = ViewModel.CurrentRunningTimeEntry
.Select(te => te?.Project?.Color ?? "#000000")
.Select(Color.ParseColor);
projectColorObservable
.Subscribe(timeEntryCardDotView.Rx().DrawableColor())
.DisposedBy(DisposeBag);
addDrawable = ContextCompat.GetDrawable(Context, Resource.Drawable.ic_add);
playDrawable = ContextCompat.GetDrawable(Context, Resource.Drawable.ic_play_big);
ViewModel.IsInManualMode
.Select(isManualMode => isManualMode ? addDrawable : playDrawable)
.Subscribe(playButton.SetDrawableImageSafe)
.DisposedBy(DisposeBag);
ViewModel.IsTimeEntryRunning
.Subscribe(visible => playButton.SetExpanded(visible))
.DisposedBy(DisposeBag);
calendarDayAdapter.MenuVisibilityRelay
.WithLatestFrom(ViewModel.IsTimeEntryRunning, Tuple.Create)
.Subscribe(tuple => setRunningTimeEntryCardAndStartButtonVisibility(tuple.Item1, tuple.Item2))
.DisposedBy(DisposeBag);
}
private void recordPageSwipeEvent(PageChangedEvent pageChangedEvent)
{
if (!isChangingPageFromUserInteraction)
{
isChangingPageFromUserInteraction = true;
return;
}
var previousPageIndex = pageChangedEvent.OldPage;
var newPageIndex = pageChangedEvent.NewPage;
var swipeDirection = previousPageIndex > newPageIndex
? CalendarSwipeDirection.Left
: CalendarSwipeDirection.Rignt;
var daysSinceToday = newPageIndex - pastCalendarPagesCount + 1;
var dayOfWeek = ViewModel.IndexToDate(daysSinceToday).DayOfWeek.ToString();
AndroidDependencyContainer.Instance.AnalyticsService.CalendarSingleSwipe.Track(swipeDirection, daysSinceToday, dayOfWeek);
}
private DateTime calculateDayForCalendarDayPage(int currentPage)
{
var today = AndroidDependencyContainer.Instance.TimeService.CurrentDateTime.ToLocalTime().Date;
return today.AddDays(-(pastCalendarPagesCount - currentPage - 1));
}
private int calculateDayViewPage(DateTime newDate)
{
var today = AndroidDependencyContainer.Instance.TimeService.CurrentDateTime.ToLocalTime().Date;
var distanceFromToday = (today - newDate).Days;
return pastCalendarPagesCount - distanceFromToday - 1;
}
private void updateWeekViewHeaders(IImmutableList<DayOfWeek> days)
{
if (days.Count != NumberOfDaysInTheWeek)
throw new ArgumentOutOfRangeException($"Week headers should contain exactly {NumberOfDaysInTheWeek} items");
calendarWeekStripeHeaders.Indexed()
.ForEach((textView, day) => textView.Text = days[day].Initial());
}
public bool HandledBackPress()
{
if (calendarDayAdapter?.MenuVisibilityRelay.Value == true)
{
calendarDayAdapter?.OnBackPressed();
return true;
}
return false;
}
public ISpannable CreateProjectClientTaskLabel(IThreadSafeTimeEntry te)
{
if (te == null)
return new SpannableString(string.Empty);
var hasProject = te.ProjectId != null;
var projectIsPlaceholder = te.Project?.IsPlaceholder() ?? false;
var taskIsPlaceholder = te.Task?.IsPlaceholder() ?? false;
return Extensions.TimeEntryExtensions.ToProjectTaskClient(
Context,
hasProject,
te.Project?.Name,
te.Project?.Color,
te.Task?.Name,
te.Project?.Client?.Name,
projectIsPlaceholder,
taskIsPlaceholder,
displayPlaceholders: true);
}
private void handlePlayFabEvent(View.TouchEventArgs eventArgs)
{
if (eventArgs == null)
{
return;
}
eventArgs.Handled = false;
if (eventArgs.Event.Action == MotionEventActions.Up)
{
playButton.StopAnimation();
}
else
{
playButton.TryStartAnimation();
}
}
private void hideBottomBar(bool bottomBarShouldBeHidden)
{
(Activity as MainTabBarActivity)?.ChangeBottomBarVisibility(bottomBarShouldBeHidden);
calendarViewPager.PostInvalidateOnAnimation();
calendarDayAdapter?.InvalidateCurrentPage();
}
private void setRunningTimeEntryCardAndStartButtonVisibility(bool contextualMenuVisible, bool timeEntryRunning)
{
if (contextualMenuVisible)
{
playButton.Visibility = ViewStates.Invisible;
stopButton.Visibility = ViewStates.Invisible;
runningEntryCardFrame.Visibility = ViewStates.Invisible;
}
else
{
playButton.Visibility = timeEntryRunning ? ViewStates.Invisible : ViewStates.Visible;
stopButton.Visibility = runningEntryCardFrame.Visibility =
timeEntryRunning ? ViewStates.Visible : ViewStates.Invisible;
}
playButton.Enabled = !contextualMenuVisible;
stopButton.Enabled = !contextualMenuVisible;
runningEntryCardFrame.Enabled = !contextualMenuVisible;
}
public void ScrollToStart()
{
if (calendarDayAdapter == null || calendarViewPager == null)
return;
if (calendarDayAdapter?.MenuVisibilityRelay.Value == true)
return;
scrollToStartSignaler.OnNext(true);
calendarViewPager.SetCurrentItem(pastCalendarPagesCount - 1, true);
}
public override void OnResume()
{
base.OnResume();
if (hasResumedOnce)
return;
hasResumedOnce = true;
if (calendarDayAdapter?.MenuVisibilityRelay.Value == true)
return;
scrollToStartSignaler.OnNext(false);
}
private void configureHeaderDate(DateTimeOffset offset)
{
var dayText = offset.ToString(Shared.Resources.CalendarToolbarDateFormat);
headerDateTextView.Text = dayText;
}
private DateTimeOffset getDateAtAdapterPosition(int position)
{
var currentDate = timeService.CurrentDateTime.ToLocalTime().Date;
return currentDate.AddDays(-(calendarDayAdapter.Count - pastCalendarPagesCount - 1 - position));
}
private void updateAppbarElevation(bool isAtTop)
{
if (MarshmallowApis.AreNotAvailable)
return;
var targetElevation = isAtTop ? 0f : defaultToolbarElevationInDPs;
appBarLayout.Elevation = targetElevation;
}
private class VerticalOffsetPageTransformer : Java.Lang.Object, ViewPager.IPageTransformer
{
private BehaviorRelay<int> verticalOffsetProvider { get; }
private BehaviorRelay<int> hourHeightProvider { get; }
public VerticalOffsetPageTransformer(
BehaviorRelay<int> hourHeightProvider,
BehaviorRelay<int> verticalOffsetProvider)
{
this.hourHeightProvider = hourHeightProvider;
this.verticalOffsetProvider = verticalOffsetProvider;
}
public void TransformPage(View page, float position)
{
var calendarDayView = page.FindViewById<CalendarDayView>(Resource.Id.CalendarDayView);
calendarDayView?.SetOffset(verticalOffsetProvider.Value);
calendarDayView?.SetHourHeight(hourHeightProvider.Value);
}
}
private struct PageChangedEvent
{
public int OldPage { get; }
public int NewPage { get; }
public PageChangedEvent(int oldPage, int newPage)
{
OldPage = oldPage;
NewPage = newPage;
}
}
private class CalendarDayFragmentAdapter : FragmentStatePagerAdapter, ViewPager.IOnPageChangeListener
{
private readonly CalendarViewModel calendarViewModel;
private readonly IObservable<bool> scrollToTopSign;
private readonly ISubject<Unit> pageNeedsToBeInvalidated = new Subject<Unit>();
private readonly ISubject<Unit> backPressSubject = new Subject<Unit>();
private readonly ISubject<PageChangedEvent> pageChanged = new Subject<PageChangedEvent>();
private readonly ISubject<int> ScrollingPage = new Subject<int>();
public BehaviorRelay<int> OffsetRelay { get; } = new BehaviorRelay<int>(0);
public BehaviorRelay<int> HourHeightRelay { get; }
public BehaviorRelay<int> CurrentPageRelay { get; } = new BehaviorRelay<int>(-1);
public BehaviorRelay<bool> MenuVisibilityRelay { get; } = new BehaviorRelay<bool>(false);
public BehaviorRelay<string> TimeTrackedOnDay { get; } = new BehaviorRelay<string>(string.Empty);
public IObservable<PageChangedEvent> PageChanged => pageChanged.AsObservable();
public CalendarDayFragmentAdapter(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public CalendarDayFragmentAdapter(
Context context,
CalendarViewModel calendarViewModel,
IObservable<bool> scrollToTopSign,
FragmentManager fm)
: base(fm)
{
this.calendarViewModel = calendarViewModel;
this.scrollToTopSign = scrollToTopSign;
HourHeightRelay = new BehaviorRelay<int>(56.DpToPixels(context));
}
public override int Count { get; } = calendarPagesCount;
public override Fragment GetItem(int position)
=> new CalendarDayViewPageFragment
{
ViewModel = calendarViewModel.DayViewModelAt(-(pastCalendarPagesCount - 1 - position)),
ScrollOffsetRelay = OffsetRelay,
HourHeightRelay = HourHeightRelay,
CurrentPageRelay = CurrentPageRelay,
MenuVisibilityRelay = MenuVisibilityRelay,
PageNumber = position,
ScrollToStartSign = scrollToTopSign,
InvalidationListener = pageNeedsToBeInvalidated.AsObservable(),
BackPressListener = backPressSubject.AsObservable(),
TimeTrackedOnDay = TimeTrackedOnDay,
ScrollingPage = ScrollingPage.AsObservable()
};
public void InvalidateCurrentPage()
{
pageNeedsToBeInvalidated.OnNext(Unit.Default);
}
public void OnBackPressed()
{
backPressSubject.OnNext(Unit.Default);
}
public void OnPageSelected(int position)
{
pageChanged.OnNext(new PageChangedEvent(CurrentPageRelay.Value, position));
CurrentPageRelay.Accept(position);
}
public void OnPageScrollStateChanged(int state)
{
}
public void OnPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
if (!(positionOffset > 0.01f)) return;
ScrollingPage.OnNext(position);
}
}
private class CalendarWeekStripeAdapter : PagerAdapter, ViewPager.IOnPageChangeListener
{
private readonly Action<CalendarWeeklyViewDayViewModel> dayInputAction;
private readonly Action onPageChanged;
private readonly BehaviorRelay<DateTime> currentlyShownDateRelay;
private readonly Dictionary<int, CalendarWeekSectionViewHolder> pages = new Dictionary<int, CalendarWeekSectionViewHolder>();
private ImmutableList<ImmutableList<CalendarWeeklyViewDayViewModel>> weekSections = ImmutableList<ImmutableList<CalendarWeeklyViewDayViewModel>>.Empty;
private DateTime currentlySelectedDate = DateTime.Today;
public CalendarWeekStripeAdapter(Action<CalendarWeeklyViewDayViewModel> dayInputAction, Action onPageChanged, BehaviorRelay<DateTime> currentlyShownDateRelay)
{
this.dayInputAction = dayInputAction;
this.currentlyShownDateRelay = currentlyShownDateRelay;
this.onPageChanged = onPageChanged;
}
public override Java.Lang.Object InstantiateItem(ViewGroup container, int position)
{
var weekStripe = (ConstraintLayout)LayoutInflater.From(container.Context).Inflate(Resource.Layout.CalendarWeekStripeDaysView, container, false);
var weekSectionViewHolder = new CalendarWeekSectionViewHolder(weekStripe, dayInputAction);
var weekSection = weekSections[position];
weekSectionViewHolder.InitDaysAndSelectedDate(weekSection, currentlySelectedDate);
pages[position] = weekSectionViewHolder;
weekStripe.Tag = position;
container.AddView(weekStripe);
return weekStripe;
}
public override void DestroyItem(ViewGroup container, int position, Java.Lang.Object @object)
{
pages.TryGetValue(position, out var page);
page?.Destroy();
var view = (View)@object;
view.Tag = null;
container.RemoveView(view);
}
public override int GetItemPosition(Java.Lang.Object @object)
{
var tag = ((View) @object).Tag;
if (tag == null)
return PositionNone;
var positionFromTag = (int)tag;
return positionFromTag == Count
? PositionNone
: positionFromTag;
}
public override bool IsViewFromObject(View view, Java.Lang.Object @object)
=> view == @object;
public override int Count => weekSections.Count;
public void OnPageScrollStateChanged(int state)
{
}
public void OnPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
public void OnPageSelected(int position)
{
var newDateOnSwipe = selectAppropriateNewDateOnSwipe(position);
if (currentlySelectedDate == newDateOnSwipe)
return;
onPageChanged();
currentlyShownDateRelay.Accept(newDateOnSwipe);
}
private DateTime selectAppropriateNewDateOnSwipe(int position)
{
var currentSections = weekSections;
var daysOnPage = currentSections[position];
var newDateOnSwipe = currentlySelectedDate;
if (currentlySelectedDate > daysOnPage.Last().Date)
{
newDateOnSwipe = currentlySelectedDate.AddDays(-NumberOfDaysInTheWeek);
newDateOnSwipe = daysOnPage.First(date => date.Enabled && date.Date >= newDateOnSwipe).Date;
}
else if (currentlySelectedDate < daysOnPage.First().Date)
{
newDateOnSwipe = currentlySelectedDate.AddDays(NumberOfDaysInTheWeek);
newDateOnSwipe = daysOnPage.Last(date => date.Enabled && date.Date <= newDateOnSwipe).Date;
}
return newDateOnSwipe;
}
public void UpdateWeekDays(ImmutableList<CalendarWeeklyViewDayViewModel> newWeekDays)
{
weekSections = createWeekSections(newWeekDays);
NotifyDataSetChanged();
applyToAllPages((pageIndex, page) => page.UpdateDays(weekSections[pageIndex]));
}
public void UpdateSelectedDay(DateTime newSelectedDate)
{
currentlySelectedDate = newSelectedDate;
applyToAllPages((pageIndex, page) => page.UpdateCurrentlySelectedDate(newSelectedDate));
}
private void applyToAllPages(Action<int, CalendarWeekSectionViewHolder> apply)
{
for (var pageIndex = 0; pageIndex < weekSections.Count; pageIndex++)
{
pages.TryGetValue(pageIndex, out var page);
if (page != null)
{
apply(pageIndex, page);
}
}
}
public int GetPageFor(DateTime selectedDate)
{
var currentWeekDays = weekSections;
for (var page = 0; page < currentWeekDays.Count; page++)
{
var weekSection = currentWeekDays[page];
if (selectedDate >= weekSection.First().Date && selectedDate <= weekSection.Last().Date)
return page;
}
return 0;
}
private ImmutableList<ImmutableList<CalendarWeeklyViewDayViewModel>> createWeekSections(ImmutableList<CalendarWeeklyViewDayViewModel> newWeekDays)
{
var weeklySections = new List<ImmutableList<CalendarWeeklyViewDayViewModel>>();
for (var i = 0; i < newWeekDays.Count; i += NumberOfDaysInTheWeek)
{
var week = newWeekDays.GetRange(i, NumberOfDaysInTheWeek);
if (week[0].Enabled || week[NumberOfDaysInTheWeek - 1].Enabled)
weeklySections.Add(week);
}
return weeklySections.ToImmutableList();
}
}
}
}
| |
using System;
using System.IO;
using System.Runtime.InteropServices;
using NDesk.Options;
namespace SteamBot
{
public class Program
{
private static OptionSet opts = new OptionSet()
{
{"bot=", "launch a configured bot given that bots index in the configuration array.",
b => botIndex = Convert.ToInt32(b) } ,
{ "help", "shows this help text", p => showHelp = (p != null) }
};
private static bool showHelp;
private static int botIndex = -1;
private static BotManager manager;
private static bool isclosing = false;
[STAThread]
public static void Main(string[] args)
{
opts.Parse(args);
if (showHelp)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("If no options are given SteamBot defaults to Bot Manager mode.");
opts.WriteOptionDescriptions(Console.Out);
Console.Write("Press Enter to exit...");
Console.ReadLine();
return;
}
if (args.Length == 0)
{
BotManagerMode();
}
else if (botIndex > -1)
{
BotMode(botIndex);
}
}
#region SteamBot Operational Modes
// This mode is to run a single Bot until it's terminated.
private static void BotMode(int botIndex)
{
if (!File.Exists("settings.json"))
{
Console.WriteLine("No settings.json file found.");
return;
}
Configuration configObject;
try
{
configObject = Configuration.LoadConfiguration("settings.json");
}
catch (Newtonsoft.Json.JsonReaderException)
{
// handle basic json formatting screwups
Console.WriteLine("settings.json file is corrupt or improperly formatted.");
return;
}
if (botIndex >= configObject.Bots.Length)
{
Console.WriteLine("Invalid bot index.");
return;
}
Bot b = new Bot(configObject.Bots[botIndex], configObject.ApiKey, BotManager.UserHandlerCreator, true, true, true);
Console.Title = "Bot Manager";
b.StartBot();
string AuthSet = "auth";
string ExecCommand = "exec";
string InputCommand = "input";
// this loop is needed to keep the botmode console alive.
// instead of just sleeping, this loop will handle console input
while (true)
{
string inputText = Console.ReadLine();
if (String.IsNullOrEmpty(inputText))
continue;
// Small parse for console input
var c = inputText.Trim();
var cs = c.Split(' ');
if (cs.Length > 1)
{
if (cs[0].Equals(AuthSet, StringComparison.CurrentCultureIgnoreCase))
{
b.AuthCode = cs[1].Trim();
}
else if (cs[0].Equals(ExecCommand, StringComparison.CurrentCultureIgnoreCase))
{
b.HandleBotCommand(c.Remove(0, cs[0].Length + 1));
}
else if (cs[0].Equals(InputCommand, StringComparison.CurrentCultureIgnoreCase))
{
b.HandleInput(c.Remove(0, cs[0].Length + 1));
}
}
}
}
// This mode is to manage child bot processes and take use command line inputs
private static void BotManagerMode()
{
Console.Title = "Bot Manager";
manager = new BotManager();
var loadedOk = manager.LoadConfiguration("settings.json");
if (!loadedOk)
{
Console.WriteLine(
"Configuration file Does not exist or is corrupt. Please rename 'settings-template.json' to 'settings.json' and modify the settings to match your environment");
Console.Write("Press Enter to exit...");
Console.ReadLine();
}
else
{
if (manager.ConfigObject.UseSeparateProcesses)
SetConsoleCtrlHandler(ConsoleCtrlCheck, true);
if (manager.ConfigObject.AutoStartAllBots)
{
var startedOk = manager.StartBots();
if (!startedOk)
{
Console.WriteLine(
"Error starting the bots because either the configuration was bad or because the log file was not opened.");
Console.Write("Press Enter to exit...");
Console.ReadLine();
}
}
else
{
foreach (var botInfo in manager.ConfigObject.Bots)
{
if (botInfo.AutoStart)
{
// auto start this particual bot...
manager.StartBot(botInfo.Username);
}
}
}
Console.WriteLine("Type help for bot manager commands. ");
Console.Write("botmgr > ");
var bmi = new BotManagerInterpreter(manager);
// command interpreter loop.
do
{
Console.Write("botmgr > ");
string inputText = Console.ReadLine();
if (!String.IsNullOrEmpty(inputText))
bmi.CommandInterpreter(inputText);
} while (!isclosing);
}
}
#endregion Bot Modes
private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
{
// Put your own handler here
switch (ctrlType)
{
case CtrlTypes.CTRL_C_EVENT:
case CtrlTypes.CTRL_BREAK_EVENT:
case CtrlTypes.CTRL_CLOSE_EVENT:
case CtrlTypes.CTRL_LOGOFF_EVENT:
case CtrlTypes.CTRL_SHUTDOWN_EVENT:
if (manager != null)
{
manager.StopBots();
}
isclosing = true;
break;
}
return true;
}
#region Console Control Handler Imports
// Declare the SetConsoleCtrlHandler function
// as external and receiving a delegate.
[DllImport("Kernel32")]
public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
// A delegate type to be used as the handler routine
// for SetConsoleCtrlHandler.
public delegate bool HandlerRoutine(CtrlTypes CtrlType);
// An enumerated type for the control messages
// sent to the handler routine.
public enum CtrlTypes
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT,
CTRL_CLOSE_EVENT,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
// Set font cache path if it doesn't already exist.
if($Gui::fontCacheDirectory $= "")
{
$Gui::fontCacheDirectory = expandFilename("./fonts");
}
// ----------------------------------------------------------------------------
// GuiDefaultProfile is a special profile that all other profiles inherit
// defaults from. It must exist.
// ----------------------------------------------------------------------------
if(!isObject(GuiDefaultProfile))
new GuiControlProfile (GuiDefaultProfile)
{
tab = false;
canKeyFocus = false;
hasBitmapArray = false;
mouseOverSelected = false;
// fill color
opaque = false;
fillColor = "242 241 240";
fillColorHL ="228 228 235";
fillColorSEL = "98 100 137";
fillColorNA = "255 255 255 ";
// border color
border = 0;
borderColor = "100 100 100";
borderColorHL = "50 50 50 50";
borderColorNA = "75 75 75";
// font
fontType = "Arial";
fontSize = 14;
fontCharset = ANSI;
fontColor = "0 0 0";
fontColorHL = "0 0 0";
fontColorNA = "0 0 0";
fontColorSEL= "255 255 255";
// bitmap information
bitmap = "";
bitmapBase = "";
textOffset = "0 0";
// used by guiTextControl
modal = true;
justify = "left";
autoSizeWidth = false;
autoSizeHeight = false;
returnTab = false;
numbersOnly = false;
cursorColor = "0 0 0 255";
};
if(!isObject(GuiToolTipProfile))
new GuiControlProfile (GuiToolTipProfile)
{
// fill color
fillColor = "239 237 222";
// border color
borderColor = "138 134 122";
// font
fontType = "Arial";
fontSize = 14;
fontColor = "0 0 0";
category = "Core";
};
if(!isObject(GuiWindowProfile))
new GuiControlProfile (GuiWindowProfile)
{
opaque = false;
border = 2;
fillColor = "242 241 240";
fillColorHL = "221 221 221";
fillColorNA = "200 200 200";
fontColor = "50 50 50";
fontColorHL = "0 0 0";
bevelColorHL = "255 255 255";
bevelColorLL = "0 0 0";
text = "untitled";
bitmap = "core/gui/images/window";
textOffset = "8 4";
hasBitmapArray = true;
justify = "left";
category = "Core";
};
if(!isObject(GuiTextEditProfile))
new GuiControlProfile(GuiTextEditProfile)
{
opaque = true;
bitmap = "core/gui/images/textEdit";
hasBitmapArray = true;
border = -2;
fillColor = "242 241 240 0";
fillColorHL = "255 255 255";
fontColor = "0 0 0";
fontColorHL = "255 255 255";
fontColorSEL = "98 100 137";
fontColorNA = "200 200 200";
textOffset = "4 2";
autoSizeWidth = false;
autoSizeHeight = true;
justify = "left";
tab = true;
canKeyFocus = true;
category = "Core";
};
if(!isObject(GuiScrollProfile))
new GuiControlProfile(GuiScrollProfile)
{
opaque = true;
fillcolor = "255 255 255";
fontColor = "0 0 0";
fontColorHL = "150 150 150";
border = true;
bitmap = "core/gui/images/scrollBar";
hasBitmapArray = true;
category = "Core";
};
if(!isObject(GuiOverlayProfile))
new GuiControlProfile(GuiOverlayProfile)
{
opaque = true;
fontColor = "0 0 0";
fontColorHL = "255 255 255";
fillColor = "0 0 0 100";
category = "Core";
};
if(!isObject(GuiCheckBoxProfile))
new GuiControlProfile(GuiCheckBoxProfile)
{
opaque = false;
fillColor = "232 232 232";
border = false;
borderColor = "100 100 100";
fontSize = 14;
fontColor = "20 20 20";
fontColorHL = "80 80 80";
fontColorNA = "200 200 200";
fixedExtent = true;
justify = "left";
bitmap = "core/gui/images/checkbox";
hasBitmapArray = true;
category = "Tools";
};
if( !isObject( GuiProgressProfile ) )
new GuiControlProfile( GuiProgressProfile )
{
opaque = false;
fillColor = "0 162 255 200";
border = true;
borderColor = "50 50 50 200";
category = "Core";
};
if( !isObject( GuiProgressBitmapProfile ) )
new GuiControlProfile( GuiProgressBitmapProfile )
{
border = false;
hasBitmapArray = true;
bitmap = "core/gui/images/loadingbar";
category = "Core";
};
if( !isObject( GuiProgressTextProfile ) )
new GuiControlProfile( GuiProgressTextProfile )
{
fontSize = "14";
fontType = "Arial";
fontColor = "0 0 0";
justify = "center";
category = "Core";
};
if( !isObject( GuiButtonProfile ) )
new GuiControlProfile( GuiButtonProfile )
{
opaque = true;
border = true;
fontColor = "50 50 50";
fontColorHL = "0 0 0";
fontColorNA = "200 200 200";
//fontColorSEL ="0 0 0";
fixedExtent = false;
justify = "center";
canKeyFocus = false;
bitmap = "core/gui/images/button";
hasBitmapArray = false;
category = "Core";
};
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using HtcSharp.HttpModule.Connections.Abstractions.Exceptions;
using HtcSharp.HttpModule.Core.Internal.Infrastructure;
using HtcSharp.HttpModule.Http;
using HtcSharp.HttpModule.Http.Abstractions;
using HtcSharp.HttpModule.Server.Abstractions.Features;
using Microsoft.Extensions.Logging;
namespace HtcSharp.HttpModule.Core.Internal {
// SourceTools-Start
// Remote-File C:\ASP\src\Servers\Kestrel\Core\src\Internal\AddressBinder.cs
// Start-At-Remote-Line 19
// SourceTools-End
internal class AddressBinder {
public static async Task BindAsync(IServerAddressesFeature addresses,
KestrelServerOptions serverOptions,
ILogger logger,
Func<ListenOptions, Task> createBinding) {
var listenOptions = serverOptions.ListenOptions;
var strategy = CreateStrategy(
listenOptions.ToArray(),
addresses.Addresses.ToArray(),
addresses.PreferHostingUrls);
var context = new AddressBindContext { Addresses = addresses.Addresses, ListenOptions = listenOptions, ServerOptions = serverOptions, Logger = logger, CreateBinding = createBinding };
// reset options. The actual used options and addresses will be populated
// by the address binding feature
listenOptions.Clear();
addresses.Addresses.Clear();
await strategy.BindAsync(context).ConfigureAwait(false);
}
private static IStrategy CreateStrategy(ListenOptions[] listenOptions, string[] addresses, bool preferAddresses) {
var hasListenOptions = listenOptions.Length > 0;
var hasAddresses = addresses.Length > 0;
if (preferAddresses && hasAddresses) {
if (hasListenOptions) {
return new OverrideWithAddressesStrategy(addresses);
}
return new AddressesStrategy(addresses);
} else if (hasListenOptions) {
if (hasAddresses) {
return new OverrideWithEndpointsStrategy(listenOptions, addresses);
}
return new EndpointsStrategy(listenOptions);
} else if (hasAddresses) {
// If no endpoints are configured directly using KestrelServerOptions, use those configured via the IServerAddressesFeature.
return new AddressesStrategy(addresses);
} else {
// "localhost" for both IPv4 and IPv6 can't be represented as an IPEndPoint.
return new DefaultAddressStrategy();
}
}
/// <summary>
/// Returns an <see cref="IPEndPoint"/> for the given host an port.
/// If the host parameter isn't "localhost" or an IP address, use IPAddress.Any.
/// </summary>
protected internal static bool TryCreateIPEndPoint(BindingAddress address, out IPEndPoint endpoint) {
if (!IPAddress.TryParse(address.Host, out var ip)) {
endpoint = null;
return false;
}
endpoint = new IPEndPoint(ip, address.Port);
return true;
}
internal static async Task BindEndpointAsync(ListenOptions endpoint, AddressBindContext context) {
try {
await context.CreateBinding(endpoint).ConfigureAwait(false);
} catch (AddressInUseException ex) {
throw new IOException(CoreStrings.FormatEndpointAlreadyInUse(endpoint), ex);
}
context.ListenOptions.Add(endpoint);
}
internal static ListenOptions ParseAddress(string address, out bool https) {
var parsedAddress = BindingAddress.Parse(address);
https = false;
if (parsedAddress.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) {
https = true;
} else if (!parsedAddress.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase)) {
throw new InvalidOperationException(CoreStrings.FormatUnsupportedAddressScheme(address));
}
if (!string.IsNullOrEmpty(parsedAddress.PathBase)) {
throw new InvalidOperationException(CoreStrings.FormatConfigurePathBaseFromMethodCall($"{nameof(IApplicationBuilder)}.UsePathBase()"));
}
ListenOptions options = null;
if (parsedAddress.IsUnixPipe) {
options = new ListenOptions(parsedAddress.UnixPipePath);
} else if (string.Equals(parsedAddress.Host, "localhost", StringComparison.OrdinalIgnoreCase)) {
// "localhost" for both IPv4 and IPv6 can't be represented as an IPEndPoint.
options = new LocalhostListenOptions(parsedAddress.Port);
} else if (TryCreateIPEndPoint(parsedAddress, out var endpoint)) {
options = new ListenOptions(endpoint);
} else {
// when address is 'http://hostname:port', 'http://*:port', or 'http://+:port'
options = new AnyIPListenOptions(parsedAddress.Port);
}
return options;
}
private interface IStrategy {
Task BindAsync(AddressBindContext context);
}
private class DefaultAddressStrategy : IStrategy {
public async Task BindAsync(AddressBindContext context) {
var httpDefault = ParseAddress(Constants.DefaultServerAddress, out var https);
context.ServerOptions.ApplyEndpointDefaults(httpDefault);
await httpDefault.BindAsync(context).ConfigureAwait(false);
// Conditional https default, only if a cert is available
var httpsDefault = ParseAddress(Constants.DefaultServerHttpsAddress, out https);
context.ServerOptions.ApplyEndpointDefaults(httpsDefault);
if (httpsDefault.IsTls || httpsDefault.TryUseHttps()) {
await httpsDefault.BindAsync(context).ConfigureAwait(false);
context.Logger.LogDebug(CoreStrings.BindingToDefaultAddresses,
Constants.DefaultServerAddress, Constants.DefaultServerHttpsAddress);
} else {
// No default cert is available, do not bind to the https endpoint.
context.Logger.LogDebug(CoreStrings.BindingToDefaultAddress, Constants.DefaultServerAddress);
}
}
}
private class OverrideWithAddressesStrategy : AddressesStrategy {
public OverrideWithAddressesStrategy(IReadOnlyCollection<string> addresses)
: base(addresses) {
}
public override Task BindAsync(AddressBindContext context) {
var joined = string.Join(", ", _addresses);
context.Logger.LogInformation(CoreStrings.OverridingWithPreferHostingUrls, nameof(IServerAddressesFeature.PreferHostingUrls), joined);
return base.BindAsync(context);
}
}
private class OverrideWithEndpointsStrategy : EndpointsStrategy {
private readonly string[] _originalAddresses;
public OverrideWithEndpointsStrategy(IReadOnlyCollection<ListenOptions> endpoints, string[] originalAddresses)
: base(endpoints) {
_originalAddresses = originalAddresses;
}
public override Task BindAsync(AddressBindContext context) {
var joined = string.Join(", ", _originalAddresses);
context.Logger.LogWarning(CoreStrings.OverridingWithKestrelOptions, joined, "UseKestrel()");
return base.BindAsync(context);
}
}
private class EndpointsStrategy : IStrategy {
private readonly IReadOnlyCollection<ListenOptions> _endpoints;
public EndpointsStrategy(IReadOnlyCollection<ListenOptions> endpoints) {
_endpoints = endpoints;
}
public virtual async Task BindAsync(AddressBindContext context) {
foreach (var endpoint in _endpoints) {
await endpoint.BindAsync(context).ConfigureAwait(false);
}
}
}
private class AddressesStrategy : IStrategy {
protected readonly IReadOnlyCollection<string> _addresses;
public AddressesStrategy(IReadOnlyCollection<string> addresses) {
_addresses = addresses;
}
public virtual async Task BindAsync(AddressBindContext context) {
foreach (var address in _addresses) {
var options = ParseAddress(address, out var https);
context.ServerOptions.ApplyEndpointDefaults(options);
if (https && !options.IsTls) {
options.UseHttps();
}
await options.BindAsync(context).ConfigureAwait(false);
}
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="MaterializeFromAtom.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// materialize objects from an xml stream
// </summary>
//---------------------------------------------------------------------
namespace System.Data.Services.Client
{
#region Namespaces.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using System.Linq.Expressions;
#endregion Namespaces.
/// <summary>
/// Use this class to materialize objects from an application/atom+xml stream.
/// </summary>
internal class MaterializeAtom : IDisposable, IEnumerable, IEnumerator
{
/// <summary>MergeOption captured from context so its static for the entire materialization</summary>
internal readonly MergeOption MergeOptionValue;
#region Private fields.
/// <summary>Row count value representing the initial state (-1)</summary>
private const long CountStateInitial = -1;
/// <summary>Row count value representing the failure state (-2)</summary>
private const long CountStateFailure = -2;
/// <summary>Options when deserializing properties to the target type.</summary>
private readonly bool ignoreMissingProperties;
/// <summary>Backreference to the context to allow type resolution.</summary>
private readonly DataServiceContext context;
/// <summary>base type of the object to create from the stream.</summary>
private readonly Type elementType;
/// <summary>when materializing a known type (like string)</summary>
/// <remarks><property> text-value </property></remarks>
private readonly bool expectingSingleValue;
/// <summary>Materializer from which instances are read.</summary>
/// <remarks>
/// The log for the materializer stores all changes for the
/// associated data context.
/// </remarks>
private readonly AtomMaterializer materializer;
/// <summary>Parser used by materializer.</summary>
/// <remarks>Odd thing to have, only here to force a lookahead for inline elements.</remarks>
private readonly AtomParser parser;
/// <summary>source reader (may be running on top of a buffer or be the real reader)</summary>
private XmlReader reader;
/// <summary>untyped current object</summary>
private object current;
/// <summary>has GetEnumerator been called?</summary>
private bool calledGetEnumerator;
/// <summary>The count tag's value, if requested</summary>
private long countValue;
/// <summary>Whether anything has been read.</summary>
private bool moved;
/// <summary>
/// output writer, set using reflection
/// </summary>
#if DEBUG && !ASTORIA_LIGHT
private System.IO.TextWriter writer = new System.IO.StringWriter(System.Globalization.CultureInfo.InvariantCulture);
#else
#pragma warning disable 649
private System.IO.TextWriter writer;
#pragma warning restore 649
#endif
#endregion Private fields.
/// <summary>
/// constructor
/// </summary>
/// <param name="context">originating context</param>
/// <param name="reader">reader</param>
/// <param name="queryComponents">Query components (projection, expected type)</param>
/// <param name="plan">Projection plan (if compiled in an earlier query).</param>
/// <param name="mergeOption">merge option to use for this materialization pass</param>
internal MaterializeAtom(DataServiceContext context, XmlReader reader, QueryComponents queryComponents, ProjectionPlan plan, MergeOption mergeOption)
{
Debug.Assert(queryComponents != null, "queryComponents != null");
this.context = context;
this.elementType = queryComponents.LastSegmentType;
this.MergeOptionValue = mergeOption;
this.ignoreMissingProperties = context.IgnoreMissingProperties;
this.reader = (reader == null) ? null : new System.Data.Services.Client.Xml.XmlAtomErrorReader(reader);
this.countValue = CountStateInitial;
this.expectingSingleValue = ClientConvert.IsKnownNullableType(elementType);
Debug.Assert(reader != null, "Materializer reader is null! Did you mean to use Materializer.ResultsWrapper/EmptyResults?");
// NOTE: dataNamespace is used for reference equality, and while it looks like
// a variable, it appears that it will only get set to XmlConstants.DataWebNamespace
// at runtime. Therefore we remove string dataNamespace as a field here.
// this.dataNamespace = reader != null ? reader.Settings.NameTable.Add(context.DataNamespace) : null;
reader.Settings.NameTable.Add(context.DataNamespace);
string typeScheme = this.context.TypeScheme.OriginalString;
this.parser = new AtomParser(this.reader, AtomParser.XElementBuilderCallback, typeScheme, context.DataNamespace);
AtomMaterializerLog log = new AtomMaterializerLog(this.context, mergeOption);
Type implementationType;
Type materializerType = GetTypeForMaterializer(this.expectingSingleValue, this.elementType, out implementationType);
this.materializer = new AtomMaterializer(parser, context, materializerType, this.ignoreMissingProperties, mergeOption, log, this.MaterializedObjectCallback, queryComponents, plan);
}
private void MaterializedObjectCallback(object tag, object entity)
{
Debug.Assert(tag != null, "tag != null");
Debug.Assert(entity != null, "entity != null");
XElement data = (XElement)tag;
if (this.context.HasReadingEntityHandlers)
{
XmlUtil.RemoveDuplicateNamespaceAttributes(data);
this.context.FireReadingEntityEvent(entity, data);
}
}
/// <summary>
/// Private internal constructor used for creating empty wrapper.
/// </summary>
private MaterializeAtom()
{
}
/// <summary>
/// DO NOT USE - this is a private hook for client unit tests to construct materializers
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
private MaterializeAtom(DataServiceContext context, XmlReader reader, Type type, MergeOption mergeOption)
: this(context, reader, new QueryComponents(null, Util.DataServiceVersionEmpty, type, null, null), null, mergeOption)
{
}
#region Current
/// <summary>Loosely typed current object property.</summary>
/// <remarks>
/// The value should be of the right type, as the materializer takes the
/// expected type into account.
/// </remarks>
public object Current
{
get
{
object currentValue = this.current;
return currentValue;
}
}
#endregion
/// <summary>
/// A materializer for empty results
/// </summary>
internal static MaterializeAtom EmptyResults
{
get
{
return new ResultsWrapper(null, null);
}
}
/// <summary>
/// Returns true, if the materialize atom has empty results, because of
/// IgnoreResourceNotFoundException flag set in context
/// </summary>
internal bool IsEmptyResults
{
get { return this.reader == null; }
}
/// <summary>
/// The context object this materializer belongs to
/// </summary>
internal DataServiceContext Context
{
get { return this.context; }
}
#region IDisposable
/// <summary>
/// dispose
/// </summary>
public void Dispose()
{
this.current = null;
if (null != this.reader)
{
((IDisposable)this.reader).Dispose();
}
if (null != this.writer)
{
this.writer.Dispose();
}
GC.SuppressFinalize(this);
}
#endregion
#region IEnumerable
/// <summary>
/// as IEnumerable
/// </summary>
/// <returns>this</returns>
public virtual IEnumerator GetEnumerator()
{
this.CheckGetEnumerator();
return this;
}
#endregion
private static Type GetTypeForMaterializer(bool expectingSingleValue, Type elementType, out Type implementationType)
{
if (!expectingSingleValue && typeof(IEnumerable).IsAssignableFrom(elementType))
{
implementationType = ClientType.GetImplementationType(elementType, typeof(ICollection<>));
if (implementationType != null)
{
Type expectedType = implementationType.GetGenericArguments()[0]; // already know its IList<>
return expectedType;
}
}
implementationType = null;
return elementType;
}
/// <summary>
/// Creates the next object from the stream.
/// </summary>
/// <returns>false if stream is finished</returns>
public bool MoveNext()
{
bool applying = this.context.ApplyingChanges;
try
{
this.context.ApplyingChanges = true;
return this.MoveNextInternal();
}
finally
{
this.context.ApplyingChanges = applying;
}
}
/// <summary>
/// Creates the next object from the stream.
/// </summary>
/// <returns>false if stream is finished</returns>
private bool MoveNextInternal()
{
// For empty results, just return false.
if (this.reader == null)
{
Debug.Assert(this.current == null, "this.current == null -- otherwise this.reader should have some value.");
return false;
}
this.current = null;
this.materializer.Log.Clear();
bool result = false;
Type implementationType;
GetTypeForMaterializer(this.expectingSingleValue, this.elementType, out implementationType);
if (implementationType != null)
{
if (this.moved)
{
return false;
}
Type expectedType = implementationType.GetGenericArguments()[0]; // already know its IList<>
implementationType = this.elementType;
if (implementationType.IsInterface)
{
implementationType = typeof(System.Collections.ObjectModel.Collection<>).MakeGenericType(expectedType);
}
IList list = (IList)Activator.CreateInstance(implementationType);
while (this.materializer.Read())
{
this.moved = true;
list.Add(this.materializer.CurrentValue);
}
this.current = list;
result = true;
}
if (null == this.current)
{
if (this.expectingSingleValue && this.moved)
{
result = false;
}
else
{
result = this.materializer.Read();
if (result)
{
this.current = this.materializer.CurrentValue;
}
this.moved = true;
}
}
this.materializer.Log.ApplyToContext();
return result;
}
/// <summary>
/// Not supported.
/// </summary>
/// <exception cref="NotSupportedException">Always thrown</exception>
void System.Collections.IEnumerator.Reset()
{
throw Error.NotSupported();
}
/// <summary>
/// Creates materializer for results
/// </summary>
/// <param name="results">the results to wrap</param>
/// <returns>a new materializer</returns>
internal static MaterializeAtom CreateWrapper(IEnumerable results)
{
return new ResultsWrapper(results, null);
}
/// <summary>Creates a materializer for partial result sets.</summary>
/// <param name="results">The current page of results</param>
/// <param name="cotinuation">The continuation for the results.</param>
/// <returns>A new materializer.</returns>
internal static MaterializeAtom CreateWrapper(IEnumerable results, DataServiceQueryContinuation continuation)
{
return new ResultsWrapper(results, continuation);
}
/// <summary>set the inserted object expected in the response</summary>
/// <param name="addedObject">object being inserted that the response is looking for</param>
internal void SetInsertingObject(object addedObject)
{
this.materializer.TargetInstance = addedObject;
}
internal static void SkipToEnd(XmlReader reader)
{
Debug.Assert(reader != null, "reader != null");
Debug.Assert(reader.NodeType == XmlNodeType.Element, "reader.NodeType == XmlNodeType.Element");
if (reader.IsEmptyElement)
{
return;
}
int readerDepth = reader.Depth;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == readerDepth)
{
return;
}
}
}
/// <summary>
/// The count tag's value, if requested
/// </summary>
/// <returns>The count value returned from the server</returns>
internal long CountValue()
{
if (this.countValue == CountStateInitial)
{
this.ReadCountValue();
}
else if (this.countValue == CountStateFailure)
{
throw new InvalidOperationException(Strings.MaterializeFromAtom_CountNotPresent);
}
return this.countValue;
}
/// <summary>
/// Returns the next link URI for the collection key
/// </summary>
/// <param name="Key">The collection for which the Uri is returned, or null, if the top level link is to be returned</param>
/// <returns>An Uri pointing to the next page for the collection</returns>
internal virtual DataServiceQueryContinuation GetContinuation(IEnumerable key)
{
Debug.Assert(this.materializer != null, "Materializer is null!");
DataServiceQueryContinuation result;
if (key == null)
{
if ((this.expectingSingleValue && !this.moved) || (!this.expectingSingleValue && !this.materializer.IsEndOfStream))
{
// expectingSingleValue && !moved : haven't started parsing single value (single value should not have next link anyway)
// !expectingSingleValue && !IsEndOfStream : collection type feed did not finish parsing yet
throw new InvalidOperationException(Strings.MaterializeFromAtom_TopLevelLinkNotAvailable);
}
// we have already moved to the end of stream
// are we singleton or just an entry?
if (this.expectingSingleValue || this.materializer.CurrentFeed == null)
{
result = null;
}
else
{
// DEVNOTE([....]): The next link uri should never be edited by the client, and therefore it must be absolute
result = DataServiceQueryContinuation.Create(
this.materializer.CurrentFeed.NextLink,
this.materializer.MaterializeEntryPlan);
}
}
else
{
if (!this.materializer.NextLinkTable.TryGetValue(key, out result))
{
// someone has asked for a collection that's "out of scope" or doesn't exist
throw new ArgumentException(Strings.MaterializeFromAtom_CollectionKeyNotPresentInLinkTable);
}
}
return result;
}
/// <summary>verify the GetEnumerator can only be called once</summary>
private void CheckGetEnumerator()
{
if (this.calledGetEnumerator)
{
throw Error.NotSupported(Strings.Deserialize_GetEnumerator);
}
this.calledGetEnumerator = true;
}
/// <summary>
/// read the m2:count tag in the feed
/// </summary>
private void ReadCountValue()
{
Debug.Assert(this.countValue == CountStateInitial, "Count value is not in the initial state");
if (this.materializer.CurrentFeed != null &&
this.materializer.CurrentFeed.Count.HasValue)
{
this.countValue = this.materializer.CurrentFeed.Count.Value;
return;
}
// find the first element tag
while (this.reader.NodeType != XmlNodeType.Element && this.reader.Read())
{
}
if (this.reader.EOF)
{
throw new InvalidOperationException(Strings.MaterializeFromAtom_CountNotPresent);
}
// the tag Should only be <feed> or <links> tag:
Debug.Assert(
(Util.AreSame(XmlConstants.AtomNamespace, this.reader.NamespaceURI) &&
Util.AreSame(XmlConstants.AtomFeedElementName, this.reader.LocalName)) ||
(Util.AreSame(XmlConstants.DataWebNamespace, this.reader.NamespaceURI) &&
Util.AreSame(XmlConstants.LinkCollectionElementName, this.reader.LocalName)),
"<feed> or <links> tag expected");
// Create the XElement for look-ahead
// DEVNOTE([....]):
// This is not streaming friendly!
XElement element = XElement.Load(this.reader);
this.reader.Close();
// Read the count value from the xelement
XElement countNode = element.Descendants(XNamespace.Get(XmlConstants.DataWebMetadataNamespace) + XmlConstants.RowCountElement).FirstOrDefault();
if (countNode == null)
{
throw new InvalidOperationException(Strings.MaterializeFromAtom_CountNotPresent);
}
else
{
if (!long.TryParse(countNode.Value, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out this.countValue))
{
throw new FormatException(Strings.MaterializeFromAtom_CountFormatError);
}
if (this.countValue < 0)
{
throw new FormatException(Strings.MaterializeFromAtom_CountFormatError);
}
}
this.reader = new System.Data.Services.Client.Xml.XmlAtomErrorReader(element.CreateReader());
this.parser.ReplaceReader(this.reader);
}
/// <summary>
/// Gets the <see cref="ClientType"/> for the (potentially
/// user-callback-resolved) type name.
/// </summary>
/// <param name="typeName">String with type name to check.</param>
/// <param name="context">Context in which type is being resolved.</param>
/// <param name="expectedType">Expected type for the name.</param>
/// <param name="checkAssignable">
/// Whether to check that a user-overriden type is assignable to a
/// variable of type <paramref name="expectedType"/>.
/// </param>
/// <returns>The <see cref="ClientType"/> for the given type name.</returns>
internal static ClientType GetEntryClientType(string typeName, DataServiceContext context, Type expectedType, bool checkAssignable)
{
Debug.Assert(context != null, "context != null");
Type resolvedType = context.ResolveTypeFromName(typeName, expectedType, checkAssignable);
ClientType result = ClientType.Create(resolvedType);
Debug.Assert(result != null, "result != null -- otherwise ClientType.Create returned null");
return result;
}
internal static string ReadElementString(XmlReader reader, bool checkNullAttribute)
{
Debug.Assert(reader != null, "reader != null");
Debug.Assert(
reader.NodeType == XmlNodeType.Element,
"reader.NodeType == XmlNodeType.Element -- otherwise caller is confused as to where the reader is");
string result = null;
bool empty = checkNullAttribute && !Util.DoesNullAttributeSayTrue(reader);
if (reader.IsEmptyElement)
{
return (empty ? String.Empty : null);
}
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.EndElement:
return result ?? (empty ? String.Empty : null);
case XmlNodeType.CDATA:
case XmlNodeType.Text:
case XmlNodeType.SignificantWhitespace:
if (null != result)
{
throw Error.InvalidOperation(Strings.Deserialize_MixedTextWithComment);
}
result = reader.Value;
break;
case XmlNodeType.Comment:
case XmlNodeType.Whitespace:
break;
#region XmlNodeType error
case XmlNodeType.Element:
goto default;
default:
throw Error.InvalidOperation(Strings.Deserialize_ExpectingSimpleValue);
#endregion
}
}
// xml ended before EndElement?
throw Error.InvalidOperation(Strings.Deserialize_ExpectingSimpleValue);
}
/// <summary>
/// Private type to wrap partial (paged) results and make it look like standard materialized results.
/// </summary>
private class ResultsWrapper : MaterializeAtom
{
#region Private fields.
/// <summary> The results to wrap </summary>
private readonly IEnumerable results;
/// <summary>A continuation to the next page of results.</summary>
private readonly DataServiceQueryContinuation continuation;
#endregion Private fields.
/// <summary>
/// Creates a wrapper for raw results
/// </summary>
/// <param name="results">the results to wrap</param>
/// <param name="continuation">The continuation for this query.</param>
internal ResultsWrapper(IEnumerable results, DataServiceQueryContinuation continuation)
{
this.results = results ?? new object[0];
this.continuation = continuation;
}
/// <summary>
/// Get the next link to the result set
/// </summary>
/// <param name="key">When equals to null, returns the next link associated with this collection. Otherwise throws InvalidOperationException.</param>
/// <returns>The continuation for this query.</returns>
internal override DataServiceQueryContinuation GetContinuation(IEnumerable key)
{
if (key == null)
{
return this.continuation;
}
else
{
throw new InvalidOperationException(Strings.MaterializeFromAtom_GetNestLinkForFlatCollection);
}
}
/// <summary>
/// Gets Enumerator for wrapped results.
/// </summary>
/// <returns>IEnumerator for results</returns>
public override IEnumerator GetEnumerator()
{
return this.results.GetEnumerator();
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier<
Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier<
Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.NetFramework.Analyzers.UnitTests
{
public partial class DoNotUseInsecureDtdProcessingAnalyzerTests
{
private DiagnosticResult CA3075ReadXmlSchemaGetCSharpResultAt(int line, int column)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("ReadXmlSchema");
#pragma warning restore RS0030 // Do not used banned APIs
private DiagnosticResult CA3075ReadXmlSchemaGetBasicResultAt(int line, int column)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("ReadXmlSchema");
#pragma warning restore RS0030 // Do not used banned APIs
[Fact]
public async Task UseDataSetReadXmlSchemaShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Data;
namespace TestNamespace
{
public class UseXmlReaderForDataSetReadXmlSchema
{
public void TestMethod(string path)
{
DataSet ds = new DataSet();
ds.ReadXmlSchema(path);
}
}
}
",
CA3075ReadXmlSchemaGetCSharpResultAt(11, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Data
Namespace TestNamespace
Public Class UseXmlReaderForDataSetReadXmlSchema
Public Sub TestMethod(path As String)
Dim ds As New DataSet()
ds.ReadXmlSchema(path)
End Sub
End Class
End Namespace",
CA3075ReadXmlSchemaGetBasicResultAt(8, 13)
);
}
[Fact]
public async Task UseDataSetReadXmlSchemaInGetShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Data;
class TestClass
{
public DataSet Test
{
get {
var src = """";
DataSet ds = new DataSet();
ds.ReadXmlSchema(src);
return ds;
}
}
}",
CA3075ReadXmlSchemaGetCSharpResultAt(11, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Data
Class TestClass
Public ReadOnly Property Test() As DataSet
Get
Dim src = """"
Dim ds As New DataSet()
ds.ReadXmlSchema(src)
Return ds
End Get
End Property
End Class",
CA3075ReadXmlSchemaGetBasicResultAt(9, 13)
);
}
[Fact]
public async Task UseDataSetReadXmlSchemaInSetShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Data;
class TestClass
{
DataSet privateDoc;
public DataSet GetDoc
{
set
{
if (value == null)
{
var src = """";
DataSet ds = new DataSet();
ds.ReadXmlSchema(src);
privateDoc = ds;
}
else
privateDoc = value;
}
}
}",
CA3075ReadXmlSchemaGetCSharpResultAt(15, 21)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Data
Class TestClass
Private privateDoc As DataSet
Public WriteOnly Property GetDoc() As DataSet
Set
If value Is Nothing Then
Dim src = """"
Dim ds As New DataSet()
ds.ReadXmlSchema(src)
privateDoc = ds
Else
privateDoc = value
End If
End Set
End Property
End Class",
CA3075ReadXmlSchemaGetBasicResultAt(11, 17)
);
}
[Fact]
public async Task UseDataSetReadXmlSchemaInTryBlockShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Data;
class TestClass
{
private void TestMethod()
{
try
{
var src = """";
DataSet ds = new DataSet();
ds.ReadXmlSchema(src);
}
catch (Exception) { throw; }
finally { }
}
}",
CA3075ReadXmlSchemaGetCSharpResultAt(13, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Data
Class TestClass
Private Sub TestMethod()
Try
Dim src = """"
Dim ds As New DataSet()
ds.ReadXmlSchema(src)
Catch generatedExceptionName As Exception
Throw
Finally
End Try
End Sub
End Class",
CA3075ReadXmlSchemaGetBasicResultAt(10, 13)
);
}
[Fact]
public async Task UseDataSetReadXmlSchemaInCatchBlockShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Data;
class TestClass
{
private void TestMethod()
{
try { }
catch (Exception)
{
var src = """";
DataSet ds = new DataSet();
ds.ReadXmlSchema(src);
}
finally { }
}
}",
CA3075ReadXmlSchemaGetCSharpResultAt(14, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Data
Class TestClass
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Dim src = """"
Dim ds As New DataSet()
ds.ReadXmlSchema(src)
Finally
End Try
End Sub
End Class",
CA3075ReadXmlSchemaGetBasicResultAt(11, 13)
);
}
[Fact]
public async Task UseDataSetReadXmlSchemaInFinallyBlockShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Data;
class TestClass
{
private void TestMethod()
{
try { }
catch (Exception) { throw; }
finally
{
var src = """";
DataSet ds = new DataSet();
ds.ReadXmlSchema(src);
}
}
}",
CA3075ReadXmlSchemaGetCSharpResultAt(15, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Data
Class TestClass
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Throw
Finally
Dim src = """"
Dim ds As New DataSet()
ds.ReadXmlSchema(src)
End Try
End Sub
End Class",
CA3075ReadXmlSchemaGetBasicResultAt(13, 13)
);
}
[Fact]
public async Task UseDataSetReadXmlSchemaInAsyncAwaitShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Threading.Tasks;
using System.Data;
class TestClass
{
private async Task TestMethod()
{
await Task.Run(() => {
var src = """";
DataSet ds = new DataSet();
ds.ReadXmlSchema(src);
});
}
private async void TestMethod2()
{
await TestMethod();
}
}",
CA3075ReadXmlSchemaGetCSharpResultAt(12, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Threading.Tasks
Imports System.Data
Class TestClass
Private Async Function TestMethod() As Task
Await Task.Run(Function()
Dim src = """"
Dim ds As New DataSet()
ds.ReadXmlSchema(src)
End Function)
End Function
Private Async Sub TestMethod2()
Await TestMethod()
End Sub
End Class",
CA3075ReadXmlSchemaGetBasicResultAt(10, 9)
);
}
[Fact]
public async Task UseDataSetReadXmlSchemaInDelegateShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Data;
class TestClass
{
delegate void Del();
Del d = delegate () {
var src = """";
DataSet ds = new DataSet();
ds.ReadXmlSchema(src);
};
}",
CA3075ReadXmlSchemaGetCSharpResultAt(11, 9)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Data
Class TestClass
Private Delegate Sub Del()
Private d As Del = Sub()
Dim src = """"
Dim ds As New DataSet()
ds.ReadXmlSchema(src)
End Sub
End Class",
CA3075ReadXmlSchemaGetBasicResultAt(10, 5)
);
}
[Fact]
public async Task UseDataSetReadXmlSchemaWithXmlReaderShouldNotGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Xml;
using System.Data;
namespace TestNamespace
{
public class UseXmlReaderForDataSetReadXmlSchema
{
public void TestMethod(XmlReader reader)
{
DataSet ds = new DataSet();
ds.ReadXmlSchema(reader);
}
}
}
"
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Xml
Imports System.Data
Namespace TestNamespace
Public Class UseXmlReaderForDataSetReadXmlSchema
Public Sub TestMethod(reader As XmlReader)
Dim ds As New DataSet()
ds.ReadXmlSchema(reader)
End Sub
End Class
End Namespace");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Xunit;
namespace System.Linq.Tests
{
public class ConcatTests : EnumerableTests
{
[Theory]
[InlineData(new int[] { 2, 3, 2, 4, 5 }, new int[] { 1, 9, 4 })]
public void SameResultsWithQueryAndRepeatCalls(IEnumerable<int> first, IEnumerable<int> second)
{
// workaround: xUnit type inference doesn't work if the input type is not T (like IEnumerable<T>)
SameResultsWithQueryAndRepeatCallsWorker(first, second);
}
[Theory]
[InlineData(new[] { "AAA", "", "q", "C", "#", "!@#$%^", "0987654321", "Calling Twice" }, new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS" })]
public void SameResultsWithQueryAndRepeatCalls(IEnumerable<string> first, IEnumerable<string> second)
{
// workaround: xUnit type inference doesn't work if the input type is not T (like IEnumerable<T>)
SameResultsWithQueryAndRepeatCallsWorker(first, second);
}
private static void SameResultsWithQueryAndRepeatCallsWorker<T>(IEnumerable<T> first, IEnumerable<T> second)
{
first = from item in first select item;
second = from item in second select item;
VerifyEqualsWorker(first.Concat(second), first.Concat(second));
VerifyEqualsWorker(second.Concat(first), second.Concat(first));
}
[Theory]
[InlineData(new int[] { }, new int[] { }, new int[] { })] // Both inputs are empty
[InlineData(new int[] { }, new int[] { 2, 6, 4, 6, 2 }, new int[] { 2, 6, 4, 6, 2 })] // One is empty
[InlineData(new int[] { 2, 3, 5, 9 }, new int[] { 8, 10 }, new int[] { 2, 3, 5, 9, 8, 10 })] // Neither side is empty
public void PossiblyEmptyInputs(IEnumerable<int> first, IEnumerable<int> second, IEnumerable<int> expected)
{
VerifyEqualsWorker(expected, first.Concat(second));
VerifyEqualsWorker(expected.Skip(first.Count()).Concat(expected.Take(first.Count())), second.Concat(first)); // Swap the inputs around
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerate()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Concat(Enumerable.Range(0, 3));
// Don't insist on this behaviour, but check it's correct if it happens
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void FirstNull()
{
AssertExtensions.Throws<ArgumentNullException>("first", () => ((IEnumerable<int>)null).Concat(Enumerable.Range(0, 0)));
AssertExtensions.Throws<ArgumentNullException>("first", () => ((IEnumerable<int>)null).Concat(null)); // If both inputs are null, throw for "first" first
}
[Fact]
public void SecondNull()
{
AssertExtensions.Throws<ArgumentNullException>("second", () => Enumerable.Range(0, 0).Concat(null));
}
[Theory]
[MemberData(nameof(ArraySourcesData))]
[MemberData(nameof(SelectArraySourcesData))]
[MemberData(nameof(EnumerableSourcesData))]
[MemberData(nameof(NonCollectionSourcesData))]
[MemberData(nameof(ListSourcesData))]
[MemberData(nameof(ConcatOfConcatsData))]
[MemberData(nameof(ConcatWithSelfData))]
[MemberData(nameof(ChainedCollectionConcatData))]
[MemberData(nameof(AppendedPrependedConcatAlternationsData))]
public void VerifyEquals(IEnumerable<int> expected, IEnumerable<int> actual)
{
// workaround: xUnit type inference doesn't work if the input type is not T (like IEnumerable<T>)
VerifyEqualsWorker(expected, actual);
}
private static void VerifyEqualsWorker<T>(IEnumerable<T> expected, IEnumerable<T> actual)
{
// Returns a list of functions that, when applied to enumerable, should return
// another one that has equivalent contents.
var identityTransforms = IdentityTransforms<T>();
// We run the transforms N^2 times, by testing all transforms
// of expected against all transforms of actual.
foreach (var outTransform in identityTransforms)
{
foreach (var inTransform in identityTransforms)
{
Assert.Equal(outTransform(expected), inTransform(actual));
}
}
}
public static IEnumerable<object[]> ArraySourcesData() => GenerateSourcesData(outerTransform: e => e.ToArray());
public static IEnumerable<object[]> SelectArraySourcesData() => GenerateSourcesData(outerTransform: e => e.Select(i => i).ToArray());
public static IEnumerable<object[]> EnumerableSourcesData() => GenerateSourcesData();
public static IEnumerable<object[]> NonCollectionSourcesData() => GenerateSourcesData(outerTransform: e => ForceNotCollection(e));
public static IEnumerable<object[]> ListSourcesData() => GenerateSourcesData(outerTransform: e => e.ToList());
public static IEnumerable<object[]> ConcatOfConcatsData()
{
yield return new object[]
{
Enumerable.Range(0, 20),
Enumerable.Concat(
Enumerable.Concat(
Enumerable.Range(0, 4),
Enumerable.Range(4, 6)),
Enumerable.Concat(
Enumerable.Range(10, 3),
Enumerable.Range(13, 7)))
};
}
public static IEnumerable<object[]> ConcatWithSelfData()
{
IEnumerable<int> source = Enumerable.Repeat(1, 4).Concat(Enumerable.Repeat(1, 5));
source = source.Concat(source);
yield return new object[] { Enumerable.Repeat(1, 18), source };
}
public static IEnumerable<object[]> ChainedCollectionConcatData() => GenerateSourcesData(innerTransform: e => e.ToList());
public static IEnumerable<object[]> AppendedPrependedConcatAlternationsData()
{
const int EnumerableCount = 4; // How many enumerables to concat together per test case.
var foundation = Array.Empty<int>();
var expected = new List<int>();
IEnumerable<int> actual = foundation;
// each bit in the last EnumerableCount bits of i represent whether we want to prepend/append a sequence for this iteration.
// if it's set, we'll prepend. otherwise, we'll append.
for (int i = 0; i < (1 << EnumerableCount); i++)
{
// each bit in last EnumerableCount bits of j is set if we want to ensure the nth enumerable
// concat'd is an ICollection.
// Note: It is important we run over the all-bits-set case, since currently
// Concat is specialized for when all inputs are ICollection.
for (int j = 0; j < (1 << EnumerableCount); j++)
{
for (int k = 0; k < EnumerableCount; k++) // k is how much bits we shift by, and also the item that gets appended/prepended.
{
var nextRange = Enumerable.Range(k, 1);
bool prepend = ((i >> k) & 1) != 0;
bool forceCollection = ((j >> k) & 1) != 0;
if (forceCollection)
{
nextRange = nextRange.ToList();
}
actual = prepend ? nextRange.Concat(actual) : actual.Concat(nextRange);
if (prepend)
{
expected.Insert(0, k);
}
else
{
expected.Add(k);
}
}
yield return new object[] { expected.ToArray(), actual.ToArray() };
actual = foundation;
expected.Clear();
}
}
}
private static IEnumerable<object[]> GenerateSourcesData(
Func<IEnumerable<int>, IEnumerable<int>> outerTransform = null,
Func<IEnumerable<int>, IEnumerable<int>> innerTransform = null)
{
outerTransform = outerTransform ?? (e => e);
innerTransform = innerTransform ?? (e => e);
for (int i = 0; i <= 6; i++)
{
var expected = Enumerable.Range(0, i * 3);
var actual = Enumerable.Empty<int>();
for (int j = 0; j < i; j++)
{
actual = outerTransform(actual.Concat(innerTransform(Enumerable.Range(j * 3, 3))));
}
yield return new object[] { expected, actual };
}
}
[Theory]
[MemberData(nameof(ManyConcatsData))]
public void ManyConcats(IEnumerable<IEnumerable<int>> sources)
{
foreach (var transform in IdentityTransforms<int>())
{
IEnumerable<int> concatee = Enumerable.Empty<int>();
foreach (var source in sources)
{
concatee = concatee.Concat(transform(source));
}
Assert.Equal(sources.Sum(s => s.Count()), concatee.Count());
VerifyEqualsWorker(sources.SelectMany(s => s), concatee);
}
}
[Theory]
[MemberData(nameof(ManyConcatsData))]
public void ManyConcatsRunOnce(IEnumerable<IEnumerable<int>> sources)
{
foreach (var transform in IdentityTransforms<int>())
{
IEnumerable<int> concatee = Enumerable.Empty<int>();
foreach (var source in sources)
{
concatee = concatee.RunOnce().Concat(transform(source));
}
Assert.Equal(sources.Sum(s => s.Count()), concatee.Count());
}
}
public static IEnumerable<object[]> ManyConcatsData()
{
yield return new object[] { Enumerable.Repeat(Enumerable.Empty<int>(), 256) };
yield return new object[] { Enumerable.Repeat(Enumerable.Repeat(6, 1), 256) };
// Make sure Concat doesn't accidentally swap around the sources, e.g. [3, 4], [1, 2] should not become [1..4]
yield return new object[] { Enumerable.Range(0, 500).Select(i => Enumerable.Repeat(i, 1)).Reverse() };
}
[Fact]
public void CountOfConcatIteratorShouldThrowExceptionOnIntegerOverflow()
{
var supposedlyLargeCollection = new DelegateBasedCollection<int> { CountWorker = () => int.MaxValue };
var tinyCollection = new DelegateBasedCollection<int> { CountWorker = () => 1 };
// We need to use checked arithmetic summing up the collections' counts.
Assert.Throws<OverflowException>(() => supposedlyLargeCollection.Concat(tinyCollection).Count());
Assert.Throws<OverflowException>(() => tinyCollection.Concat(tinyCollection).Concat(supposedlyLargeCollection).Count());
Assert.Throws<OverflowException>(() => tinyCollection.Concat(tinyCollection).Concat(tinyCollection).Concat(supposedlyLargeCollection).Count());
// This applies to ToArray() and ToList() as well, which try to preallocate the exact size
// needed if all inputs are ICollections.
Assert.Throws<OverflowException>(() => supposedlyLargeCollection.Concat(tinyCollection).ToArray());
Assert.Throws<OverflowException>(() => tinyCollection.Concat(tinyCollection).Concat(supposedlyLargeCollection).ToArray());
Assert.Throws<OverflowException>(() => tinyCollection.Concat(tinyCollection).Concat(tinyCollection).Concat(supposedlyLargeCollection).ToArray());
Assert.Throws<OverflowException>(() => supposedlyLargeCollection.Concat(tinyCollection).ToList());
Assert.Throws<OverflowException>(() => tinyCollection.Concat(tinyCollection).Concat(supposedlyLargeCollection).ToList());
Assert.Throws<OverflowException>(() => tinyCollection.Concat(tinyCollection).Concat(tinyCollection).Concat(supposedlyLargeCollection).ToList());
}
[Fact]
[OuterLoop("This test tries to catch stack overflows and can take a long time.")]
public void CountOfConcatCollectionChainShouldBeResilientToStackOverflow()
{
// Currently, .Concat chains of 3+ ICollections are represented as a
// singly-linked list of iterators, each holding 1 collection. When
// we call Count() on the last iterator, it needs to sum up the count
// of its collection, plus the count of all the previous collections.
// It is tempting to use recursion to solve this problem, by simply
// returning [this collection].Count + [previous iterator].Count(),
// since it is so much simpler than the iterative solution.
// However, this can lead to a stack overflow for long chains of
// .Concats. This is a test to guard against that.
// Something big enough to cause a SO when this many method calls
// are made, but not too large.
const int NumberOfConcats = 30000;
// For perf reasons (this test can take a long time to run)
// we use a for-loop manually rather than .Repeat and .Aggregate
IEnumerable<int> concatChain = Array.Empty<int>(); // note: all items in this chain must implement ICollection<T>
for (int i = 0; i < NumberOfConcats; i++)
{
concatChain = concatChain.Concat(Array.Empty<int>());
}
Assert.Equal(0, concatChain.Count()); // should not throw a StackOverflowException
// ToArray needs the count as well, and the process of copying all of the collections
// to the array should also not be recursive.
Assert.Equal(new int[] { }, concatChain.ToArray());
Assert.Equal(new List<int> { }, concatChain.ToList()); // ToList also gets the count beforehand
}
[Fact]
[OuterLoop("This test tries to catch stack overflows and can take a long time.")]
public void CountOfConcatEnumerableChainShouldBeResilientToStackOverflow()
{
// Concat chains where one or more of the inputs is not an ICollection
// (so we cannot figure out the total count w/o iterating through some
// of the enumerables) are represented much the same, as singly-linked lists.
// However, the underlying iterator type/implementation of Count()
// will be different (it treats all of the concatenated enumerables as lazy),
// so we have to make sure that implementation isn't recursive either.
const int NumberOfConcats = 30000;
// Start with a non-ICollection seed, which means all subsequent
// Concats will be treated as lazy enumerables.
IEnumerable<int> concatChain = ForceNotCollection(Array.Empty<int>());
// Then, concatenate a bunch of ICollections to it.
// Since Count() is optimized for when its input is an ICollection,
// this will reduce the time it takes to run the test, which otherwise
// would take quite long.
for (int i = 0; i < NumberOfConcats; i++)
{
concatChain = concatChain.Concat(Array.Empty<int>());
}
Assert.Equal(0, concatChain.Count());
// ToArray/ToList do not attempt to preallocate a result of the correct
// size- if there's just 1 lazy enumerable in the chain, it's impossible
// to get the count to preallocate without iterating through that, and then
// when the data is being copied you'd need to iterate through it again
// (not ideal). So we do not need to worry about those methods having a
// stack overflow through getting the Count() of the iterator.
}
[Fact]
[OuterLoop("This test tries to catch stack overflows and can take a long time.")]
public void GettingFirstEnumerableShouldBeResilientToStackOverflow()
{
// When MoveNext() is first called on a chain of 3+ Concats, we have to
// walk all the way to the tail of the linked list to reach the first
// concatee. Likewise as before, make sure this isn't accomplished with
// a recursive implementation.
const int NumberOfConcats = 30000;
// Start with a lazy seed.
// The seed holds 1 item, so during the first MoveNext we won't have to
// backtrack through the linked list 30000 times. This is for test perf.
IEnumerable<int> concatChain = ForceNotCollection(new int[] { 0xf00 });
for (int i = 0; i < NumberOfConcats; i++)
{
concatChain = concatChain.Concat(Array.Empty<int>());
}
using (IEnumerator<int> en = concatChain.GetEnumerator())
{
Assert.True(en.MoveNext()); // should not SO
Assert.Equal(0xf00, en.Current);
}
}
[Fact]
[OuterLoop("This test tries to catch stack overflows and can take a long time.")]
public void GetEnumerableOfConcatCollectionChainFollowedByEnumerableNodeShouldBeResilientToStackOverflow()
{
// Since concatenating even 1 lazy enumerable ruins the ability for ToArray/ToList
// optimizations, if one is Concat'd to a collection-based iterator then we will
// fall back to treating all subsequent concatenations as lazy.
// Since it is possible for an enumerable iterator to be preceded by a collection
// iterator, but not the other way around, an assumption is made. If an enumerable
// iterator encounters a collection iterator during GetEnumerable(), it calls into
// the collection iterator's GetEnumerable() under the assumption that the callee
// will never call into another enumerable iterator's GetEnumerable(). This is
// because collection iterators can only be preceded by other collection iterators.
// Violation of this assumption means that the GetEnumerable() implementations could
// become mutually recursive, which may lead to stack overflow for enumerable iterators
// preceded by a long chain of collection iterators.
const int NumberOfConcats = 30000;
// This time, start with an ICollection seed. We want the subsequent Concats in
// the loop to produce collection iterators.
IEnumerable<int> concatChain = new int[] { 0xf00 };
for (int i = 0; i < NumberOfConcats - 1; i++)
{
concatChain = concatChain.Concat(Array.Empty<int>());
}
// Finally, link an enumerable iterator at the head of the list.
concatChain = concatChain.Concat(ForceNotCollection(Array.Empty<int>()));
using (IEnumerator<int> en = concatChain.GetEnumerator())
{
Assert.True(en.MoveNext());
Assert.Equal(0xf00, en.Current);
}
}
[Theory]
[MemberData(nameof(GetToArrayDataSources))]
public void CollectionInterleavedWithLazyEnumerables_ToArray(IEnumerable<int>[] arrays)
{
// See https://github.com/dotnet/corefx/issues/23680
IEnumerable<int> concats = arrays[0];
for (int i = 1; i < arrays.Length; i++)
{
concats = concats.Concat(arrays[i]);
}
int[] results = concats.ToArray();
for (int i = 0; i < results.Length; i++)
{
Assert.Equal(i, results[i]);
}
}
public static IEnumerable<object[]> GetToArrayDataSources()
{
// Marker at the end
yield return new object[]
{
new IEnumerable<int>[]
{
new TestEnumerable<int>(new int[] { 0 }),
new TestEnumerable<int>(new int[] { 1 }),
new TestEnumerable<int>(new int[] { 2 }),
new int[] { 3 },
}
};
// Marker at beginning
yield return new object[]
{
new IEnumerable<int>[]
{
new int[] { 0 },
new TestEnumerable<int>(new int[] { 1 }),
new TestEnumerable<int>(new int[] { 2 }),
new TestEnumerable<int>(new int[] { 3 }),
}
};
// Marker in middle
yield return new object[]
{
new IEnumerable<int>[]
{
new TestEnumerable<int>(new int[] { 0 }),
new int[] { 1 },
new TestEnumerable<int>(new int[] { 2 }),
}
};
// Non-marker in middle
yield return new object[]
{
new IEnumerable<int>[]
{
new int[] { 0 },
new TestEnumerable<int>(new int[] { 1 }),
new int[] { 2 },
}
};
// Big arrays (marker in middle)
yield return new object[]
{
new IEnumerable<int>[]
{
new TestEnumerable<int>(Enumerable.Range(0, 100).ToArray()),
Enumerable.Range(100, 100).ToArray(),
new TestEnumerable<int>(Enumerable.Range(200, 100).ToArray()),
}
};
// Big arrays (non-marker in middle)
yield return new object[]
{
new IEnumerable<int>[]
{
Enumerable.Range(0, 100).ToArray(),
new TestEnumerable<int>(Enumerable.Range(100, 100).ToArray()),
Enumerable.Range(200, 100).ToArray(),
}
};
// Interleaved (first marker)
yield return new object[]
{
new IEnumerable<int>[]
{
new int[] { 0 },
new TestEnumerable<int>(new int[] { 1 }),
new int[] { 2 },
new TestEnumerable<int>(new int[] { 3 }),
new int[] { 4 },
}
};
// Interleaved (first non-marker)
yield return new object[]
{
new IEnumerable<int>[]
{
new TestEnumerable<int>(new int[] { 0 }),
new int[] { 1 },
new TestEnumerable<int>(new int[] { 2 }),
new int[] { 3 },
new TestEnumerable<int>(new int[] { 4 }),
}
};
}
}
}
| |
using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Runtime.InteropServices;
namespace MovablePython
{
/// <summary>
/// TODO: maybe use http://blogs.msdn.com/b/toub/archive/2006/05/03/589423.aspx
/// </summary>
public class Hotkey : IMessageFilter
{
#region Interop
[DllImport("user32.dll", SetLastError = true)]
private static extern int RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, Keys vk);
[DllImport("user32.dll", SetLastError=true)]
private static extern int UnregisterHotKey(IntPtr hWnd, int id);
private const uint WM_HOTKEY = 0x312;
private const uint MOD_ALT = 0x1;
private const uint MOD_CONTROL = 0x2;
private const uint MOD_SHIFT = 0x4;
private const uint MOD_WIN = 0x8;
private const uint ERROR_HOTKEY_ALREADY_REGISTERED = 1409;
#endregion
private static int currentID;
private const int maximumID = 0xBFFF;
private Keys keyCode;
private bool shift;
private bool control;
private bool alt;
private bool windows;
[XmlIgnore]
private int id;
[XmlIgnore]
private bool registered;
[XmlIgnore]
private Control windowControl;
public event HandledEventHandler Pressed;
public Hotkey() : this(Keys.None, false, false, false, false)
{
// No work done here!
}
public Hotkey(Keys keyCode, bool shift, bool control, bool alt, bool windows)
{
// Assign properties
this.KeyCode = keyCode;
this.Shift = shift;
this.Control = control;
this.Alt = alt;
this.Windows = windows;
// Register us as a message filter
Application.AddMessageFilter(this);
}
~Hotkey()
{
// Unregister the hotkey if necessary
if (this.Registered)
{ this.Unregister(); }
}
public Hotkey Clone()
{
// Clone the whole object
return new Hotkey(this.keyCode, this.shift, this.control, this.alt, this.windows);
}
public bool GetCanRegister(Control windowControl)
{
// Handle any exceptions: they mean "no, you can't register" :)
try
{
// Attempt to register
if (!this.Register(windowControl))
{ return false; }
// Unregister and say we managed it
this.Unregister();
return true;
}
catch (Win32Exception)
{ return false; }
catch (NotSupportedException)
{ return false; }
}
public bool Register(Control windowControl)
{
// Check that we have not registered
if (this.registered)
{ throw new NotSupportedException("You cannot register a hotkey that is already registered"); }
// We can't register an empty hotkey
if (this.Empty)
{ throw new NotSupportedException("You cannot register an empty hotkey"); }
// Get an ID for the hotkey and increase current ID
this.id = Hotkey.currentID;
Hotkey.currentID = Hotkey.currentID + 1 % Hotkey.maximumID;
// Translate modifier keys into unmanaged version
uint modifiers = (this.Alt ? Hotkey.MOD_ALT : 0) | (this.Control ? Hotkey.MOD_CONTROL : 0) |
(this.Shift ? Hotkey.MOD_SHIFT : 0) | (this.Windows ? Hotkey.MOD_WIN : 0);
// Register the hotkey
if (Hotkey.RegisterHotKey(windowControl.Handle, this.id, modifiers, keyCode) == 0)
{
// Is the error that the hotkey is registered?
if (Marshal.GetLastWin32Error() == ERROR_HOTKEY_ALREADY_REGISTERED)
{ return false; }
else
{ throw new Win32Exception(); }
}
// Save the control reference and register state
this.registered = true;
this.windowControl = windowControl;
// We successfully registered
return true;
}
public void Unregister()
{
// Check that we have registered
if (!this.registered)
{ throw new NotSupportedException("You cannot unregister a hotkey that is not registered"); }
// It's possible that the control itself has died: in that case, no need to unregister!
if (!this.windowControl.IsDisposed)
{
// Clean up after ourselves
if (Hotkey.UnregisterHotKey(this.windowControl.Handle, this.id) == 0)
{ throw new Win32Exception(); }
}
// Clear the control reference and register state
this.registered = false;
this.windowControl = null;
}
private void Reregister()
{
// Only do something if the key is already registered
if (!this.registered)
{ return; }
// Save control reference
Control windowControl = this.windowControl;
// Unregister and then reregister again
this.Unregister();
this.Register(windowControl);
}
public bool PreFilterMessage(ref Message message)
{
// Only process WM_HOTKEY messages
if (message.Msg != Hotkey.WM_HOTKEY)
{ return false; }
// Check that the ID is our key and we are registerd
if (this.registered && (message.WParam.ToInt32() == this.id))
{
// Fire the event and pass on the event if our handlers didn't handle it
return this.OnPressed();
}
else
{ return false; }
}
private bool OnPressed()
{
// Fire the event if we can
HandledEventArgs handledEventArgs = new HandledEventArgs(false);
if (this.Pressed != null)
{ this.Pressed(this, handledEventArgs); }
// Return whether we handled the event or not
return handledEventArgs.Handled;
}
public override string ToString()
{
// We can be empty
if (this.Empty)
{ return "(none)"; }
// Build key name
string keyName = Enum.GetName(typeof(Keys), this.keyCode);;
switch (this.keyCode)
{
case Keys.D0:
case Keys.D1:
case Keys.D2:
case Keys.D3:
case Keys.D4:
case Keys.D5:
case Keys.D6:
case Keys.D7:
case Keys.D8:
case Keys.D9:
// Strip the first character
keyName = keyName.Substring(1);
break;
default:
// Leave everything alone
break;
}
// Build modifiers
string modifiers = "";
if (this.shift)
{ modifiers += "Shift+"; }
if (this.control)
{ modifiers += "Control+"; }
if (this.alt)
{ modifiers += "Alt+"; }
if (this.windows)
{ modifiers += "Windows+"; }
// Return result
return modifiers + keyName;
}
public bool Empty
{
get { return this.keyCode == Keys.None; }
}
public bool Registered
{
get { return this.registered; }
}
public Keys KeyCode
{
get { return this.keyCode; }
set
{
// Save and reregister
this.keyCode = value;
this.Reregister();
}
}
public bool Shift
{
get { return this.shift; }
set
{
// Save and reregister
this.shift = value;
this.Reregister();
}
}
public bool Control
{
get { return this.control; }
set
{
// Save and reregister
this.control = value;
this.Reregister();
}
}
public bool Alt
{
get { return this.alt; }
set
{
// Save and reregister
this.alt = value;
this.Reregister();
}
}
public bool Windows
{
get { return this.windows; }
set
{
// Save and reregister
this.windows = value;
this.Reregister();
}
}
}
}
| |
// 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 System.Linq;
namespace System.IO.Tests
{
public partial class File_Move : FileSystemTest
{
#region Utilities
public virtual void Move(string sourceFile, string destFile)
{
File.Move(sourceFile, destFile);
}
#endregion
#region UniversalTests
[Fact]
public void NullPath()
{
Assert.Throws<ArgumentNullException>(() => Move(null, "."));
Assert.Throws<ArgumentNullException>(() => Move(".", null));
}
[Fact]
public void EmptyPath()
{
Assert.Throws<ArgumentException>(() => Move(string.Empty, "."));
Assert.Throws<ArgumentException>(() => Move(".", string.Empty));
}
[Fact]
public virtual void NonExistentPath()
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.Throws<FileNotFoundException>(() => Move(GetTestFilePath(), testFile.FullName));
Assert.Throws<DirectoryNotFoundException>(() => Move(testFile.FullName, Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName())));
Assert.Throws<FileNotFoundException>(() => Move(Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName()), testFile.FullName));
}
[Theory, MemberData(nameof(PathsWithInvalidCharacters))]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void PathWithIllegalCharacters_Desktop(string invalidPath)
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.Throws<ArgumentException>(() => Move(testFile.FullName, invalidPath));
}
[Theory, MemberData(nameof(PathsWithInvalidCharacters))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void PathWithIllegalCharacters_Core(string invalidPath)
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
if (invalidPath.Contains('\0'.ToString()))
{
Assert.Throws<ArgumentException>(() => Move(testFile.FullName, invalidPath));
}
else
{
if (PlatformDetection.IsInAppContainer)
{
AssertExtensions.ThrowsAny<IOException, UnauthorizedAccessException>(() => Move(testFile.FullName, invalidPath));
}
else
{
Assert.ThrowsAny<IOException>(() => Move(testFile.FullName, invalidPath));
}
}
}
[Fact]
public void BasicMove()
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
testFileSource.Create().Dispose();
string testFileDest = GetTestFilePath();
Move(testFileSource.FullName, testFileDest);
Assert.True(File.Exists(testFileDest));
Assert.False(File.Exists(testFileSource.FullName));
}
[Fact]
public void MoveNonEmptyFile()
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
using (var stream = testFileSource.Create())
{
var writer = new StreamWriter(stream);
writer.Write("testing\nwrite\n");
writer.Flush();
}
string testFileDest = GetTestFilePath();
Move(testFileSource.FullName, testFileDest);
Assert.True(File.Exists(testFileDest));
Assert.False(File.Exists(testFileSource.FullName));
Assert.Equal("testing\nwrite\n", File.ReadAllText(testFileDest));
}
[Fact]
public void MoveOntoDirectory()
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.Throws<IOException>(() => Move(testFile.FullName, TestDirectory));
}
[Fact]
public void MoveOntoExistingFile()
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
testFileSource.Create().Dispose();
FileInfo testFileDest = new FileInfo(GetTestFilePath());
testFileDest.Create().Dispose();
Assert.Throws<IOException>(() => Move(testFileSource.FullName, testFileDest.FullName));
Assert.True(File.Exists(testFileSource.FullName));
Assert.True(File.Exists(testFileDest.FullName));
}
[Fact]
public void MoveIntoParentDirectory()
{
string testDir = GetTestFilePath();
Directory.CreateDirectory(testDir);
FileInfo testFileSource = new FileInfo(Path.Combine(testDir, GetTestFileName()));
testFileSource.Create().Dispose();
FileInfo testFileDest = new FileInfo(Path.Combine(testDir, "..", GetTestFileName()));
Move(testFileSource.FullName, testFileDest.FullName);
Assert.True(File.Exists(testFileDest.FullName));
}
[Fact]
public void MoveToSameName()
{
string testDir = GetTestFilePath();
Directory.CreateDirectory(testDir);
FileInfo testFileSource = new FileInfo(Path.Combine(testDir, GetTestFileName()));
testFileSource.Create().Dispose();
Move(testFileSource.FullName, testFileSource.FullName);
Assert.True(File.Exists(testFileSource.FullName));
}
[Fact]
public void MoveToSameNameDifferentCasing()
{
string testDir = GetTestFilePath();
Directory.CreateDirectory(testDir);
FileInfo testFileSource = new FileInfo(Path.Combine(testDir, Path.GetRandomFileName().ToLowerInvariant()));
testFileSource.Create().Dispose();
FileInfo testFileDest = new FileInfo(Path.Combine(testFileSource.DirectoryName, testFileSource.Name.ToUpperInvariant()));
Move(testFileSource.FullName, testFileDest.FullName);
Assert.True(File.Exists(testFileDest.FullName));
}
[Fact]
public void MultipleMoves()
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
testFileSource.Create().Dispose();
string testFileDest1 = GetTestFilePath();
string testFileDest2 = GetTestFilePath();
Move(testFileSource.FullName, testFileDest1);
Move(testFileDest1, testFileDest2);
Assert.True(File.Exists(testFileDest2));
Assert.False(File.Exists(testFileDest1));
Assert.False(File.Exists(testFileSource.FullName));
}
[Fact]
public void FileNameWithSignificantWhitespace()
{
string testFileSource = Path.Combine(TestDirectory, GetTestFileName());
string testFileDest = Path.Combine(TestDirectory, " e n d");
File.Create(testFileSource).Dispose();
Move(testFileSource, testFileDest);
Assert.True(File.Exists(testFileDest));
Assert.False(File.Exists(testFileSource));
}
[ConditionalFact(nameof(AreAllLongPathsAvailable))]
[ActiveIssue(32167, TargetFrameworkMonikers.NetFramework)]
[PlatformSpecific(TestPlatforms.Windows)] // Path longer than max path limit
public void OverMaxPathWorks_Windows()
{
// Create a destination path longer than the traditional Windows limit of 256 characters,
// but under the long path limitation (32K).
string testFileSource = Path.Combine(TestDirectory, GetTestFileName());
File.Create(testFileSource).Dispose();
Assert.True(File.Exists(testFileSource), "test file should exist");
Assert.All(IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath()), (path) =>
{
string baseDestinationPath = Path.GetDirectoryName(path);
if (!Directory.Exists(baseDestinationPath))
{
Directory.CreateDirectory(baseDestinationPath);
}
Assert.True(Directory.Exists(baseDestinationPath), "base destination path should exist");
Move(testFileSource, path);
Assert.True(File.Exists(path), "moved test file should exist");
File.Delete(testFileSource);
Assert.False(File.Exists(testFileSource), "source test file should not exist");
Move(path, testFileSource);
Assert.True(File.Exists(testFileSource), "restored test file should exist");
});
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void LongPath()
{
string testFileSource = Path.Combine(TestDirectory, GetTestFileName());
File.Create(testFileSource).Dispose();
Assert.All(IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath()), (path) =>
{
AssertExtensions.ThrowsAny<PathTooLongException, FileNotFoundException, DirectoryNotFoundException>(() => Move(testFileSource, path));
File.Delete(testFileSource);
AssertExtensions.ThrowsAny<PathTooLongException, FileNotFoundException, DirectoryNotFoundException>(() => Move(path, testFileSource));
});
}
#endregion
#region PlatformSpecific
[Theory, MemberData(nameof(PathsWithInvalidColons))]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void WindowsPathWithIllegalColons_Desktop(string invalidPath)
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
if (PathFeatures.IsUsingLegacyPathNormalization())
{
Assert.Throws<ArgumentException>(() => Move(testFile.FullName, invalidPath));
}
else
{
if (invalidPath.Contains('|'))
Assert.Throws<ArgumentException>(() => Move(testFile.FullName, invalidPath));
else
Assert.Throws<NotSupportedException>(() => Move(testFile.FullName, invalidPath));
}
}
[Theory, MemberData(nameof(PathsWithInvalidColons))]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void WindowsPathWithIllegalColons_Core(string invalidPath)
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.ThrowsAny<IOException>(() => Move(testFile.FullName, testFile.DirectoryName + Path.DirectorySeparatorChar + invalidPath));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void WindowsWildCharacterPath_Desktop()
{
Assert.Throws<ArgumentException>(() => Move("*", GetTestFilePath()));
Assert.Throws<ArgumentException>(() => Move(GetTestFilePath(), "*"));
Assert.Throws<ArgumentException>(() => Move(GetTestFilePath(), "Test*t"));
Assert.Throws<ArgumentException>(() => Move(GetTestFilePath(), "*Test"));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void WindowsWildCharacterPath_Core()
{
Assert.Throws<FileNotFoundException>(() => Move(Path.Combine(TestDirectory, "*"), GetTestFilePath()));
Assert.Throws<FileNotFoundException>(() => Move(GetTestFilePath(), Path.Combine(TestDirectory, "*")));
Assert.Throws<FileNotFoundException>(() => Move(GetTestFilePath(), Path.Combine(TestDirectory, "Test*t")));
Assert.Throws<FileNotFoundException>(() => Move(GetTestFilePath(), Path.Combine(TestDirectory, "*Test")));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Wild characters in path are allowed
public void UnixWildCharacterPath()
{
string testDir = GetTestFilePath();
string testFileSource = Path.Combine(testDir, "*");
string testFileShouldntMove = Path.Combine(testDir, "*t");
string testFileDest = Path.Combine(testDir, "*" + GetTestFileName());
Directory.CreateDirectory(testDir);
File.Create(testFileSource).Dispose();
File.Create(testFileShouldntMove).Dispose();
Move(testFileSource, testFileDest);
Assert.True(File.Exists(testFileDest));
Assert.False(File.Exists(testFileSource));
Assert.True(File.Exists(testFileShouldntMove));
Move(testFileDest, testFileSource);
Assert.False(File.Exists(testFileDest));
Assert.True(File.Exists(testFileSource));
Assert.True(File.Exists(testFileShouldntMove));
}
[Theory,
MemberData(nameof(ControlWhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void WindowsControlPath_Desktop(string whitespace)
{
FileInfo testFile = new FileInfo(GetTestFilePath());
Assert.Throws<ArgumentException>(() => Move(testFile.FullName, whitespace));
}
[Theory,
MemberData(nameof(ControlWhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void WindowsControlPath_Core(string whitespace)
{
FileInfo testFile = new FileInfo(GetTestFilePath());
Assert.ThrowsAny<IOException>(() => Move(testFile.FullName, Path.Combine(TestDirectory, whitespace)));
}
[Theory,
MemberData(nameof(SimpleWhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)]
public void WindowsSimpleWhitespacePath(string whitespace)
{
FileInfo testFile = new FileInfo(GetTestFilePath());
Assert.Throws<ArgumentException>(() => Move(testFile.FullName, whitespace));
}
[Theory,
MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Whitespace in path allowed
public void UnixWhitespacePath(string whitespace)
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
testFileSource.Create().Dispose();
Move(testFileSource.FullName, Path.Combine(TestDirectory, whitespace));
Move(Path.Combine(TestDirectory, whitespace), testFileSource.FullName);
}
[Theory,
InlineData("", ":bar"),
InlineData("", ":bar:$DATA"),
InlineData("::$DATA", ":bar"),
InlineData("::$DATA", ":bar:$DATA")]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void WindowsAlternateDataStreamMove(string defaultStream, string alternateStream)
{
DirectoryInfo testDirectory = Directory.CreateDirectory(GetTestFilePath());
string testFile = Path.Combine(testDirectory.FullName, GetTestFileName());
string testFileDefaultStream = testFile + defaultStream;
string testFileAlternateStream = testFile + alternateStream;
// Cannot move into an alternate stream
File.WriteAllText(testFileDefaultStream, "Foo");
Assert.Throws<IOException>(() => Move(testFileDefaultStream, testFileAlternateStream));
// Cannot move out of an alternate stream
File.WriteAllText(testFileAlternateStream, "Bar");
string testFile2 = Path.Combine(testDirectory.FullName, GetTestFileName());
Assert.Throws<IOException>(() => Move(testFileAlternateStream, testFile2));
}
#endregion
}
}
| |
//
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.DataFactories.Core;
using Microsoft.Azure.Management.DataFactories.Models;
namespace Microsoft.Azure.Management.DataFactories.Core
{
public static partial class ActivityWindowOperationsExtensions
{
/// <summary>
/// Gets the first page of activity window instances for a data factory
/// with the link to the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IActivityWindowOperations.
/// </param>
/// <param name='parameters'>
/// Required. Filter parameters for activity windows list.
/// </param>
/// <returns>
/// The List activity windows operation response.
/// </returns>
public static ActivityWindowListResponse ListByDataFactory(this IActivityWindowOperations operations, ActivityWindowsByDataFactoryListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IActivityWindowOperations)s).ListByDataFactoryAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the first page of activity window instances for a data factory
/// with the link to the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IActivityWindowOperations.
/// </param>
/// <param name='parameters'>
/// Required. Filter parameters for activity windows list.
/// </param>
/// <returns>
/// The List activity windows operation response.
/// </returns>
public static Task<ActivityWindowListResponse> ListByDataFactoryAsync(this IActivityWindowOperations operations, ActivityWindowsByDataFactoryListParameters parameters)
{
return operations.ListByDataFactoryAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Gets the first page of activity window instances for a dataset with
/// the link to the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IActivityWindowOperations.
/// </param>
/// <param name='parameters'>
/// Required. Filter parameters for activity windows list.
/// </param>
/// <returns>
/// The List activity windows operation response.
/// </returns>
public static ActivityWindowListResponse ListByDataset(this IActivityWindowOperations operations, ActivityWindowsByDatasetListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IActivityWindowOperations)s).ListByDatasetAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the first page of activity window instances for a dataset with
/// the link to the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IActivityWindowOperations.
/// </param>
/// <param name='parameters'>
/// Required. Filter parameters for activity windows list.
/// </param>
/// <returns>
/// The List activity windows operation response.
/// </returns>
public static Task<ActivityWindowListResponse> ListByDatasetAsync(this IActivityWindowOperations operations, ActivityWindowsByDatasetListParameters parameters)
{
return operations.ListByDatasetAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Gets the first page of activity window instances for a pipeline
/// with the link to the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IActivityWindowOperations.
/// </param>
/// <param name='parameters'>
/// Required. Filter parameters for activity windows list.
/// </param>
/// <returns>
/// The List activity windows operation response.
/// </returns>
public static ActivityWindowListResponse ListByPipeline(this IActivityWindowOperations operations, ActivityWindowsByPipelineListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IActivityWindowOperations)s).ListByPipelineAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the first page of activity window instances for a pipeline
/// with the link to the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IActivityWindowOperations.
/// </param>
/// <param name='parameters'>
/// Required. Filter parameters for activity windows list.
/// </param>
/// <returns>
/// The List activity windows operation response.
/// </returns>
public static Task<ActivityWindowListResponse> ListByPipelineAsync(this IActivityWindowOperations operations, ActivityWindowsByPipelineListParameters parameters)
{
return operations.ListByPipelineAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Gets the first page of activity window instances for a pipeline
/// activity with the link to the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IActivityWindowOperations.
/// </param>
/// <param name='parameters'>
/// Required. Filter parameters for activity windows list.
/// </param>
/// <returns>
/// The List activity windows operation response.
/// </returns>
public static ActivityWindowListResponse ListByPipelineActivity(this IActivityWindowOperations operations, ActivityWindowsByActivityListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IActivityWindowOperations)s).ListByPipelineActivityAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the first page of activity window instances for a pipeline
/// activity with the link to the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IActivityWindowOperations.
/// </param>
/// <param name='parameters'>
/// Required. Filter parameters for activity windows list.
/// </param>
/// <returns>
/// The List activity windows operation response.
/// </returns>
public static Task<ActivityWindowListResponse> ListByPipelineActivityAsync(this IActivityWindowOperations operations, ActivityWindowsByActivityListParameters parameters)
{
return operations.ListByPipelineActivityAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Gets the next page of activity window instances with the link to
/// the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IActivityWindowOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The URL to the next page of activity windows.
/// </param>
/// <param name='parameters'>
/// Required. Filter parameters for activity windows list.
/// </param>
/// <returns>
/// The List activity windows operation response.
/// </returns>
public static ActivityWindowListResponse ListNextByDataFactory(this IActivityWindowOperations operations, string nextLink, ActivityWindowsByDataFactoryListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IActivityWindowOperations)s).ListNextByDataFactoryAsync(nextLink, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the next page of activity window instances with the link to
/// the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IActivityWindowOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The URL to the next page of activity windows.
/// </param>
/// <param name='parameters'>
/// Required. Filter parameters for activity windows list.
/// </param>
/// <returns>
/// The List activity windows operation response.
/// </returns>
public static Task<ActivityWindowListResponse> ListNextByDataFactoryAsync(this IActivityWindowOperations operations, string nextLink, ActivityWindowsByDataFactoryListParameters parameters)
{
return operations.ListNextByDataFactoryAsync(nextLink, parameters, CancellationToken.None);
}
/// <summary>
/// Gets the next page of activity window instances with the link to
/// the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IActivityWindowOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The URL to the next page of activity windows.
/// </param>
/// <param name='parameters'>
/// Required. Filter parameters for activity windows list.
/// </param>
/// <returns>
/// The List activity windows operation response.
/// </returns>
public static ActivityWindowListResponse ListNextByDataset(this IActivityWindowOperations operations, string nextLink, ActivityWindowsByDatasetListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IActivityWindowOperations)s).ListNextByDatasetAsync(nextLink, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the next page of activity window instances with the link to
/// the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IActivityWindowOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The URL to the next page of activity windows.
/// </param>
/// <param name='parameters'>
/// Required. Filter parameters for activity windows list.
/// </param>
/// <returns>
/// The List activity windows operation response.
/// </returns>
public static Task<ActivityWindowListResponse> ListNextByDatasetAsync(this IActivityWindowOperations operations, string nextLink, ActivityWindowsByDatasetListParameters parameters)
{
return operations.ListNextByDatasetAsync(nextLink, parameters, CancellationToken.None);
}
/// <summary>
/// Gets the next page of activity window instances with the link to
/// the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IActivityWindowOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The URL to the next page of activity windows.
/// </param>
/// <param name='parameters'>
/// Required. Filter parameters for activity windows list.
/// </param>
/// <returns>
/// The List activity windows operation response.
/// </returns>
public static ActivityWindowListResponse ListNextByPipeline(this IActivityWindowOperations operations, string nextLink, ActivityWindowsByPipelineListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IActivityWindowOperations)s).ListNextByPipelineAsync(nextLink, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the next page of activity window instances with the link to
/// the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IActivityWindowOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The URL to the next page of activity windows.
/// </param>
/// <param name='parameters'>
/// Required. Filter parameters for activity windows list.
/// </param>
/// <returns>
/// The List activity windows operation response.
/// </returns>
public static Task<ActivityWindowListResponse> ListNextByPipelineAsync(this IActivityWindowOperations operations, string nextLink, ActivityWindowsByPipelineListParameters parameters)
{
return operations.ListNextByPipelineAsync(nextLink, parameters, CancellationToken.None);
}
/// <summary>
/// Gets the next page of activity window instances with the link to
/// the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IActivityWindowOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The URL to the next page of activity windows.
/// </param>
/// <param name='parameters'>
/// Required. Filter parameters for activity windows list.
/// </param>
/// <returns>
/// The List activity windows operation response.
/// </returns>
public static ActivityWindowListResponse ListNextByPipelineActivity(this IActivityWindowOperations operations, string nextLink, ActivityWindowsByActivityListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IActivityWindowOperations)s).ListNextByPipelineActivityAsync(nextLink, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the next page of activity window instances with the link to
/// the next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IActivityWindowOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The URL to the next page of activity windows.
/// </param>
/// <param name='parameters'>
/// Required. Filter parameters for activity windows list.
/// </param>
/// <returns>
/// The List activity windows operation response.
/// </returns>
public static Task<ActivityWindowListResponse> ListNextByPipelineActivityAsync(this IActivityWindowOperations operations, string nextLink, ActivityWindowsByActivityListParameters parameters)
{
return operations.ListNextByPipelineActivityAsync(nextLink, parameters, CancellationToken.None);
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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.Reflection;
using System.Text;
using Gallio.Common.Collections;
using Gallio.Common;
using Gallio.Common.Reflection;
namespace Gallio.Runtime.Extensibility
{
/// <summary>
/// A handle for a lazily instantiated component and its traits.
/// </summary>
/// <seealso cref="ComponentHandle{TService, TTraits}"/>
public abstract class ComponentHandle
{
private readonly IComponentDescriptor componentDescriptor;
internal ComponentHandle(IComponentDescriptor componentDescriptor)
{
this.componentDescriptor = componentDescriptor;
}
/// <summary>
/// Creates an instance of a typed component handle for the specified descriptor.
/// </summary>
/// <param name="componentDescriptor">The component descriptor.</param>
/// <returns>The appropriately typed component handle.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="componentDescriptor"/> is null.</exception>
/// <exception cref="RuntimeException">Thrown if the described component's service type or traits type cannot be resolved.</exception>
public static ComponentHandle CreateInstance(IComponentDescriptor componentDescriptor)
{
if (componentDescriptor == null)
throw new ArgumentNullException("componentDescriptor");
Type serviceType = componentDescriptor.Service.ResolveServiceType();
Type traitsType = componentDescriptor.Service.ResolveTraitsType();
Type handleType = typeof(ComponentHandle<,>).MakeGenericType(serviceType, traitsType);
ConstructorInfo constructor = handleType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance,
null, new[] { typeof(IComponentDescriptor) }, null);
return (ComponentHandle) constructor.Invoke(new[] { componentDescriptor });
}
/// <summary>
/// Creates an instance of a typed component handle for the specified descriptor.
/// </summary>
/// <param name="componentDescriptor">The component descriptor.</param>
/// <returns>The appropriately typed component handle.</returns>
/// <typeparam name="TService">The service type.</typeparam>
/// <typeparam name="TTraits">The traits type.</typeparam>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="componentDescriptor"/> is null.</exception>
/// <exception cref="ArgumentException">Thrown if the described component's service or traits are not compatible with a handle of this type.</exception>
/// <exception cref="RuntimeException">Thrown if the described component's service type or traits type cannot be resolved.</exception>
public static ComponentHandle<TService, TTraits> CreateInstance<TService, TTraits>(IComponentDescriptor componentDescriptor)
where TTraits : Traits
{
if (componentDescriptor == null)
throw new ArgumentNullException("componentDescriptor");
Type serviceType = componentDescriptor.Service.ResolveServiceType();
Type traitsType = componentDescriptor.Service.ResolveTraitsType();
if (serviceType != typeof(TService) || traitsType != typeof(TTraits))
{
throw new ArgumentException(
"The component descriptor is not compatible with the requested component handle type because it has a different service type or traits type.",
"componentDescriptor");
}
return new ComponentHandle<TService, TTraits>(componentDescriptor);
}
/// <summary>
/// Creates an instance of a typed component handle for the specified component and traits instance.
/// The component handle will have a stub component descriptor for testing purposes.
/// </summary>
/// <param name="componentId">The component id.</param>
/// <param name="component">The component instance.</param>
/// <param name="traits">The component traits.</param>
/// <typeparam name="TService">The service type.</typeparam>
/// <typeparam name="TTraits">The traits type.</typeparam>
/// <returns>The appropriately typed component handle.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="componentId"/>, <paramref name="component"/>
/// or <paramref name="traits"/> is null.</exception>
/// <exception cref="ArgumentException">Thrown if the described component's service or traits are not compatible with a handle of this type.</exception>
/// <exception cref="RuntimeException">Thrown if the described component's service type or traits type cannot be resolved.</exception>
public static ComponentHandle<TService, TTraits> CreateStub<TService, TTraits>(string componentId, TService component, TTraits traits)
where TTraits : Traits
{
if (componentId == null)
throw new ArgumentNullException("componentId");
if (component == null)
throw new ArgumentNullException("component");
if (traits == null)
throw new ArgumentNullException("traits");
IComponentDescriptor componentDescriptor = new ComponentDescriptorStub(componentId, component, traits);
return new ComponentHandle<TService, TTraits>(componentDescriptor);
}
/// <summary>
/// Returns true if the specified type is a component handle type.
/// </summary>
/// <param name="type">The type to examine.</param>
/// <returns>True if the type is a component handle type.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="type"/> is null.</exception>
public static bool IsComponentHandleType(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
return type == typeof(ComponentHandle)
|| type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ComponentHandle<,>);
}
/// <summary>
/// Gets the component descriptor.
/// </summary>
public IComponentDescriptor Descriptor
{
get { return componentDescriptor; }
}
/// <summary>
/// Gets the component id.
/// </summary>
public string Id
{
get { return componentDescriptor.ComponentId; }
}
/// <summary>
/// Gets the service type.
/// </summary>
/// <returns>The service type.</returns>
public abstract Type ServiceType { get; }
/// <summary>
/// Gets the traits type.
/// </summary>
/// <returns>The traits type.</returns>
public abstract Type TraitsType { get; }
/// <summary>
/// Gets the component instance.
/// </summary>
/// <returns>The component instance.</returns>
/// <exception cref="RuntimeException">Thrown if the component cannot be resolved.</exception>
public object GetComponent()
{
return GetComponentImpl();
}
/// <summary>
/// Gets the component traits.
/// </summary>
/// <returns>The component traits.</returns>
/// <exception cref="RuntimeException">Thrown if the traits cannot be resolved.</exception>
public Traits GetTraits()
{
return GetTraitsImpl();
}
/// <summary>
/// Returns the component's id.
/// </summary>
/// <returns>The component id.</returns>
public override string ToString()
{
return Id;
}
internal abstract object GetComponentImpl();
internal abstract Traits GetTraitsImpl();
private sealed class ComponentDescriptorStub : IComponentDescriptor
{
private readonly string componentId;
private readonly object component;
private readonly Traits traits;
public ComponentDescriptorStub(string componentId, object component, Traits traits)
{
this.componentId = componentId;
this.component = component;
this.traits = traits;
}
public IPluginDescriptor Plugin
{
get { throw new NotSupportedException(); }
}
public IServiceDescriptor Service
{
get { throw new NotSupportedException(); }
}
public string ComponentId
{
get { return componentId; }
}
public TypeName ComponentTypeName
{
get { return new TypeName(component.GetType()); }
}
public IHandlerFactory ComponentHandlerFactory
{
get { throw new NotSupportedException(); }
}
public PropertySet ComponentProperties
{
get { throw new NotSupportedException(); }
}
public PropertySet TraitsProperties
{
get { throw new NotSupportedException(); }
}
public bool IsDisabled
{
get { return false; }
}
public string DisabledReason
{
get { throw new InvalidOperationException("The component has not been disabled."); }
}
public Type ResolveComponentType()
{
return component.GetType();
}
public IHandler ResolveComponentHandler()
{
throw new NotSupportedException();
}
public object ResolveComponent()
{
return component;
}
public IHandler ResolveTraitsHandler()
{
throw new NotSupportedException();
}
public Traits ResolveTraits()
{
return traits;
}
}
}
/// <summary>
/// A typed handle for a lazily instantiated component and its traits.
/// </summary>
/// <typeparam name="TService">The type of service implemented by the component.</typeparam>
/// <typeparam name="TTraits">The type of traits provided by the component.</typeparam>
public sealed class ComponentHandle<TService, TTraits> : ComponentHandle
where TTraits : Traits
{
private Memoizer<TService> instanceMemoizer = new Memoizer<TService>();
private Memoizer<TTraits> traitsMemoizer = new Memoizer<TTraits>();
internal ComponentHandle(IComponentDescriptor componentDescriptor)
: base(componentDescriptor)
{
}
/// <inheritdoc />
public override Type ServiceType
{
get { return typeof(TService); }
}
/// <inheritdoc />
public override Type TraitsType
{
get { return typeof(TTraits); }
}
/// <summary>
/// Gets the component instance.
/// </summary>
/// <returns>The component instance.</returns>
/// <exception cref="RuntimeException">Thrown if the component cannot be resolved.</exception>
new public TService GetComponent()
{
return instanceMemoizer.Memoize(() => (TService)Descriptor.ResolveComponent());
}
/// <summary>
/// Gets the component traits.
/// </summary>
/// <returns>The component traits.</returns>
/// <exception cref="RuntimeException">Thrown if the traits cannot be resolved.</exception>
new public TTraits GetTraits()
{
return traitsMemoizer.Memoize(() => (TTraits)Descriptor.ResolveTraits());
}
internal override object GetComponentImpl()
{
return GetComponent();
}
internal override Traits GetTraitsImpl()
{
return GetTraits();
}
}
}
| |
// 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.Linq;
using System.Threading;
using Xunit;
namespace Test
{
public class AggregateTests
{
private const int ResultFuncModifier = 17;
public static IEnumerable<object[]> AggregateExceptionData(object[] counts)
{
foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>()))
{
Labeled<ParallelQuery<int>> query = (Labeled<ParallelQuery<int>>)results[0];
if (query.ToString().StartsWith("Partitioner"))
{
yield return new object[] { Labeled.Label(query.ToString(), Partitioner.Create(UnorderedSources.GetRangeArray(0, (int)results[1]), false).AsParallel()), results[1] };
}
else if (query.ToString().StartsWith("Enumerable.Range"))
{
yield return new object[] { Labeled.Label(query.ToString(), new StrictPartitioner<int>(Partitioner.Create(Enumerable.Range(0, (int)results[1]), EnumerablePartitionerOptions.None), (int)results[1]).AsParallel()), results[1] };
}
else
{
yield return results;
}
}
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
if (count == 0)
{
Assert.Throws<InvalidOperationException>(() => query.Aggregate((x, y) => x + y));
}
else
{
// The operation will overflow for long-running sizes, but that's okay:
// The helper is overflowing too!
Assert.Equal(Functions.SumRange(0, count), query.Aggregate((x, y) => x + y));
}
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Aggregate_Sum(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum_Seed(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.SumRange(0, count), query.Aggregate(0, (x, y) => x + y));
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum_Seed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Aggregate_Sum_Seed(labeled, count);
}
[Theory]
[MemberData("Ranges", 1, new int[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))]
public static void Aggregate_Product_Seed(Labeled<ParallelQuery<int>> labeled, int count, int start)
{
ParallelQuery<int> query = labeled.Item;
// The operation will overflow for long-running sizes, but that's okay:
// The helper is overflowing too!
Assert.Equal(Functions.ProductRange(start, count), query.Aggregate(1L, (x, y) => x * y));
}
[Theory]
[OuterLoop]
[MemberData("Ranges", 1, new int[] { 1024 * 1024, 1024 * 1024 * 4 }, MemberType = typeof(UnorderedSources))]
public static void Aggregate_Product_Seed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int start)
{
Aggregate_Product_Seed(labeled, count, start);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Collection_Seed(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Enumerable.Range(0, count), query.Aggregate((IList<int>)new List<int>(), (l, x) => l.AddToCopy(x)).OrderBy(x => x));
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 512, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Collection_Seed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Aggregate_Collection_Seed(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum_Result(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.SumRange(0, count) + ResultFuncModifier, query.Aggregate(0, (x, y) => x + y, result => result + ResultFuncModifier));
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum_Result_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Aggregate_Sum_Result(labeled, count);
}
[Theory]
[MemberData("Ranges", 1, new int[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))]
public static void Aggregate_Product_Result(Labeled<ParallelQuery<int>> labeled, int count, int start)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.ProductRange(start, count) + ResultFuncModifier, query.Aggregate(1L, (x, y) => x * y, result => result + ResultFuncModifier));
}
[Theory]
[OuterLoop]
[MemberData("Ranges", 1, new int[] { 1024 * 1024, 1024 * 1024 * 4 }, MemberType = typeof(UnorderedSources))]
public static void Aggregate_Product_Results_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int start)
{
Aggregate_Product_Result(labeled, count, start);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Collection_Results(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Enumerable.Range(0, count), query.Aggregate((IList<int>)new List<int>(), (l, x) => l.AddToCopy(x), l => l.OrderBy(x => x)));
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 512, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Collection_Results_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Aggregate_Collection_Results(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum_Accumulator(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int actual = query.Aggregate(
0,
(accumulator, x) => accumulator + x,
(left, right) => left + right,
result => result + ResultFuncModifier);
Assert.Equal(Functions.SumRange(0, count) + ResultFuncModifier, actual);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum_Accumulator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Aggregate_Sum_Accumulator(labeled, count);
}
[Theory]
[MemberData("Ranges", 1, new int[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))]
public static void Aggregate_Product_Accumulator(Labeled<ParallelQuery<int>> labeled, int count, int start)
{
ParallelQuery<int> query = labeled.Item;
long actual = query.Aggregate(
1L,
(accumulator, x) => accumulator * x,
(left, right) => left * right,
result => result + ResultFuncModifier);
Assert.Equal(Functions.ProductRange(start, count) + ResultFuncModifier, actual);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", 1, new int[] { 1024 * 1024, 1024 * 1024 * 4 }, MemberType = typeof(UnorderedSources))]
public static void Aggregate_Product_Accumulator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int start)
{
Aggregate_Product_Accumulator(labeled, count, start);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Collection_Accumulator(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IList<int> actual = query.Aggregate(
(IList<int>)new List<int>(),
(accumulator, x) => accumulator.AddToCopy(x),
(left, right) => left.ConcatCopy(right),
result => result.OrderBy(x => x).ToList());
Assert.Equal(Enumerable.Range(0, count), actual);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 512, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Collection_Accumulator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Aggregate_Collection_Accumulator(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum_SeedFunction(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int actual = query.Aggregate(
() => 0,
(accumulator, x) => accumulator + x,
(left, right) => left + right,
result => result + ResultFuncModifier);
Assert.Equal(Functions.SumRange(0, count) + ResultFuncModifier, actual);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Sum_SeedFunction_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Aggregate_Sum_SeedFunction(labeled, count);
}
[Theory]
[MemberData("Ranges", 1, new int[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))]
public static void Aggregate_Product_SeedFunction(Labeled<ParallelQuery<int>> labeled, int count, int start)
{
ParallelQuery<int> query = labeled.Item;
long actual = query.Aggregate(
() => 1L,
(accumulator, x) => accumulator * x,
(left, right) => left * right,
result => result + ResultFuncModifier);
Assert.Equal(Functions.ProductRange(start, count) + ResultFuncModifier, actual);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", 1, new int[] { 1024 * 1024, 1024 * 1024 * 4 }, MemberType = typeof(UnorderedSources))]
public static void Aggregate_Product_SeedFunction_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int start)
{
Aggregate_Product_SeedFunction(labeled, count, start);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Collection_SeedFunction(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IList<int> actual = query.Aggregate(
() => (IList<int>)new List<int>(),
(accumulator, x) => accumulator.AddToCopy(x),
(left, right) => left.ConcatCopy(right),
result => result.OrderBy(x => x).ToList());
Assert.Equal(Enumerable.Range(0, count), actual);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 512, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_Collection_SeedFunction_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
Aggregate_Collection_SeedFunction(labeled, count);
}
[Fact]
public static void Aggregate_InvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Aggregate((i, j) => i));
// All other invocations return the seed value.
Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(-1, (i, j) => i + j));
Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(-1, (i, j) => i + j, i => i));
Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(-1, (i, j) => i + j, (i, j) => i + j, i => i));
Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(() => -1, (i, j) => i + j, (i, j) => i + j, i => i));
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))]
public static void Aggregate_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Aggregate((i, j) => i));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Aggregate(0, (i, j) => i));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Aggregate(0, (i, j) => i, i => i));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Aggregate(0, (i, j) => i, (i, j) => i, i => i));
}
[Theory]
[MemberData("AggregateExceptionData", (object)(new int[] { 2 }))]
public static void Aggregate_AggregateException(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate((i, j) => { throw new DeliberateTestException(); }));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate(0, (i, j) => { throw new DeliberateTestException(); }));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate(0, (i, j) => { throw new DeliberateTestException(); }, i => i));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate<int, int, int>(0, (i, j) => i, i => { throw new DeliberateTestException(); }));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate(0, (i, j) => { throw new DeliberateTestException(); }, (i, j) => i, i => i));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate<int, int, int>(0, (i, j) => i, (i, j) => i, i => { throw new DeliberateTestException(); }));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate<int, int, int>(() => { throw new DeliberateTestException(); }, (i, j) => i, (i, j) => i, i => i));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate(() => 0, (i, j) => { throw new DeliberateTestException(); }, (i, j) => i, i => i));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate<int, int, int>(() => 0, (i, j) => i, (i, j) => i, i => { throw new DeliberateTestException(); }));
if (Environment.ProcessorCount >= 2)
{
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate(0, (i, j) => i, (i, j) => { throw new DeliberateTestException(); }, i => i));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate(() => 0, (i, j) => i, (i, j) => { throw new DeliberateTestException(); }, i => i));
}
}
[Fact]
public static void Aggregate_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Aggregate((i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Aggregate(0, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(0, null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Aggregate(0, (i, j) => i, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(0, null, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate<int, int, int>(0, (i, j) => i, null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Aggregate(0, (i, j) => i, (i, j) => i, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(0, null, (i, j) => i, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(0, (i, j) => i, null, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate<int, int, int>(0, (i, j) => i, (i, j) => i, null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Aggregate(() => 0, (i, j) => i, (i, j) => i, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate<int, int, int>(null, (i, j) => i, (i, j) => i, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(() => 0, null, (i, j) => i, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(() => 0, (i, j) => i, null, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate<int, int, int>(() => 0, (i, j) => i, (i, j) => i, null));
}
}
internal static class ListHelper
{
// System.Collections.Immutable.ImmutableList wasn't available.
public static IList<int> AddToCopy(this IList<int> collection, int element)
{
collection = new List<int>(collection);
collection.Add(element);
return collection;
}
public static IList<int> ConcatCopy(this IList<int> left, IList<int> right)
{
List<int> results = new List<int>(left);
results.AddRange(right);
return results;
}
}
}
| |
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace Org.Achartengine.Renderer {
// Metadata.xml XPath class reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer']"
[global::Android.Runtime.Register ("org/achartengine/renderer/DialRenderer", DoNotGenerateAcw=true)]
public partial class DialRenderer : global::Org.Achartengine.Renderer.DefaultRenderer {
// Metadata.xml XPath class reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer.Type']"
[global::Android.Runtime.Register ("org/achartengine/renderer/DialRenderer$Type", DoNotGenerateAcw=true)]
public sealed partial class Type : global::Java.Lang.Enum {
static IntPtr ARROW_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer.Type']/field[@name='ARROW']"
[Register ("ARROW")]
public static global::Org.Achartengine.Renderer.DialRenderer.Type Arrow {
get {
if (ARROW_jfieldId == IntPtr.Zero)
ARROW_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "ARROW", "Lorg/achartengine/renderer/DialRenderer$Type;");
IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, ARROW_jfieldId);
return global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer.Type> (__ret, JniHandleOwnership.TransferLocalRef);
}
set {
if (ARROW_jfieldId == IntPtr.Zero)
ARROW_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "ARROW", "Lorg/achartengine/renderer/DialRenderer$Type;");
IntPtr native_value = JNIEnv.ToLocalJniHandle (value);
JNIEnv.SetStaticField (class_ref, ARROW_jfieldId, native_value);
JNIEnv.DeleteLocalRef (native_value);
}
}
static IntPtr NEEDLE_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer.Type']/field[@name='NEEDLE']"
[Register ("NEEDLE")]
public static global::Org.Achartengine.Renderer.DialRenderer.Type Needle {
get {
if (NEEDLE_jfieldId == IntPtr.Zero)
NEEDLE_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "NEEDLE", "Lorg/achartengine/renderer/DialRenderer$Type;");
IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, NEEDLE_jfieldId);
return global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer.Type> (__ret, JniHandleOwnership.TransferLocalRef);
}
set {
if (NEEDLE_jfieldId == IntPtr.Zero)
NEEDLE_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "NEEDLE", "Lorg/achartengine/renderer/DialRenderer$Type;");
IntPtr native_value = JNIEnv.ToLocalJniHandle (value);
JNIEnv.SetStaticField (class_ref, NEEDLE_jfieldId, native_value);
JNIEnv.DeleteLocalRef (native_value);
}
}
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/achartengine/renderer/DialRenderer$Type", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (Type); }
}
internal Type (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_valueOf_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer.Type']/method[@name='valueOf' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register ("valueOf", "(Ljava/lang/String;)Lorg/achartengine/renderer/DialRenderer$Type;", "")]
public static global::Org.Achartengine.Renderer.DialRenderer.Type ValueOf (string p0)
{
if (id_valueOf_Ljava_lang_String_ == IntPtr.Zero)
id_valueOf_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "valueOf", "(Ljava/lang/String;)Lorg/achartengine/renderer/DialRenderer$Type;");
IntPtr native_p0 = JNIEnv.NewString (p0);
global::Org.Achartengine.Renderer.DialRenderer.Type __ret = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer.Type> (JNIEnv.CallStaticObjectMethod (class_ref, id_valueOf_Ljava_lang_String_, new JValue (native_p0)), JniHandleOwnership.TransferLocalRef);
JNIEnv.DeleteLocalRef (native_p0);
return __ret;
}
static IntPtr id_values;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer.Type']/method[@name='values' and count(parameter)=0]"
[Register ("values", "()[Lorg/achartengine/renderer/DialRenderer$Type;", "")]
public static global::Org.Achartengine.Renderer.DialRenderer.Type[] Values ()
{
if (id_values == IntPtr.Zero)
id_values = JNIEnv.GetStaticMethodID (class_ref, "values", "()[Lorg/achartengine/renderer/DialRenderer$Type;");
return (global::Org.Achartengine.Renderer.DialRenderer.Type[]) JNIEnv.GetArray (JNIEnv.CallStaticObjectMethod (class_ref, id_values), JniHandleOwnership.TransferLocalRef, typeof (global::Org.Achartengine.Renderer.DialRenderer.Type));
}
}
internal static new IntPtr java_class_handle;
internal static new IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/achartengine/renderer/DialRenderer", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (DialRenderer); }
}
protected DialRenderer (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer']/constructor[@name='DialRenderer' and count(parameter)=0]"
[Register (".ctor", "()V", "")]
public DialRenderer () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
if (GetType () != typeof (DialRenderer)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "()V"),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "()V");
return;
}
if (id_ctor == IntPtr.Zero)
id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor);
}
static Delegate cb_getAngleMax;
#pragma warning disable 0169
static Delegate GetGetAngleMaxHandler ()
{
if (cb_getAngleMax == null)
cb_getAngleMax = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, double>) n_GetAngleMax);
return cb_getAngleMax;
}
static double n_GetAngleMax (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Renderer.DialRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.AngleMax;
}
#pragma warning restore 0169
static Delegate cb_setAngleMax_D;
#pragma warning disable 0169
static Delegate GetSetAngleMax_DHandler ()
{
if (cb_setAngleMax_D == null)
cb_setAngleMax_D = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, double>) n_SetAngleMax_D);
return cb_setAngleMax_D;
}
static void n_SetAngleMax_D (IntPtr jnienv, IntPtr native__this, double p0)
{
global::Org.Achartengine.Renderer.DialRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.AngleMax = p0;
}
#pragma warning restore 0169
static IntPtr id_getAngleMax;
static IntPtr id_setAngleMax_D;
public virtual double AngleMax {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer']/method[@name='getAngleMax' and count(parameter)=0]"
[Register ("getAngleMax", "()D", "GetGetAngleMaxHandler")]
get {
if (id_getAngleMax == IntPtr.Zero)
id_getAngleMax = JNIEnv.GetMethodID (class_ref, "getAngleMax", "()D");
if (GetType () == ThresholdType)
return JNIEnv.CallDoubleMethod (Handle, id_getAngleMax);
else
return JNIEnv.CallNonvirtualDoubleMethod (Handle, ThresholdClass, id_getAngleMax);
}
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer']/method[@name='setAngleMax' and count(parameter)=1 and parameter[1][@type='double']]"
[Register ("setAngleMax", "(D)V", "GetSetAngleMax_DHandler")]
set {
if (id_setAngleMax_D == IntPtr.Zero)
id_setAngleMax_D = JNIEnv.GetMethodID (class_ref, "setAngleMax", "(D)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_setAngleMax_D, new JValue (value));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_setAngleMax_D, new JValue (value));
}
}
static Delegate cb_getAngleMin;
#pragma warning disable 0169
static Delegate GetGetAngleMinHandler ()
{
if (cb_getAngleMin == null)
cb_getAngleMin = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, double>) n_GetAngleMin);
return cb_getAngleMin;
}
static double n_GetAngleMin (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Renderer.DialRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.AngleMin;
}
#pragma warning restore 0169
static Delegate cb_setAngleMin_D;
#pragma warning disable 0169
static Delegate GetSetAngleMin_DHandler ()
{
if (cb_setAngleMin_D == null)
cb_setAngleMin_D = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, double>) n_SetAngleMin_D);
return cb_setAngleMin_D;
}
static void n_SetAngleMin_D (IntPtr jnienv, IntPtr native__this, double p0)
{
global::Org.Achartengine.Renderer.DialRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.AngleMin = p0;
}
#pragma warning restore 0169
static IntPtr id_getAngleMin;
static IntPtr id_setAngleMin_D;
public virtual double AngleMin {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer']/method[@name='getAngleMin' and count(parameter)=0]"
[Register ("getAngleMin", "()D", "GetGetAngleMinHandler")]
get {
if (id_getAngleMin == IntPtr.Zero)
id_getAngleMin = JNIEnv.GetMethodID (class_ref, "getAngleMin", "()D");
if (GetType () == ThresholdType)
return JNIEnv.CallDoubleMethod (Handle, id_getAngleMin);
else
return JNIEnv.CallNonvirtualDoubleMethod (Handle, ThresholdClass, id_getAngleMin);
}
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer']/method[@name='setAngleMin' and count(parameter)=1 and parameter[1][@type='double']]"
[Register ("setAngleMin", "(D)V", "GetSetAngleMin_DHandler")]
set {
if (id_setAngleMin_D == IntPtr.Zero)
id_setAngleMin_D = JNIEnv.GetMethodID (class_ref, "setAngleMin", "(D)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_setAngleMin_D, new JValue (value));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_setAngleMin_D, new JValue (value));
}
}
static Delegate cb_isMaxValueSet;
#pragma warning disable 0169
static Delegate GetIsMaxValueSetHandler ()
{
if (cb_isMaxValueSet == null)
cb_isMaxValueSet = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_IsMaxValueSet);
return cb_isMaxValueSet;
}
static bool n_IsMaxValueSet (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Renderer.DialRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.IsMaxValueSet;
}
#pragma warning restore 0169
static IntPtr id_isMaxValueSet;
public virtual bool IsMaxValueSet {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer']/method[@name='isMaxValueSet' and count(parameter)=0]"
[Register ("isMaxValueSet", "()Z", "GetIsMaxValueSetHandler")]
get {
if (id_isMaxValueSet == IntPtr.Zero)
id_isMaxValueSet = JNIEnv.GetMethodID (class_ref, "isMaxValueSet", "()Z");
if (GetType () == ThresholdType)
return JNIEnv.CallBooleanMethod (Handle, id_isMaxValueSet);
else
return JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, id_isMaxValueSet);
}
}
static Delegate cb_isMinValueSet;
#pragma warning disable 0169
static Delegate GetIsMinValueSetHandler ()
{
if (cb_isMinValueSet == null)
cb_isMinValueSet = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_IsMinValueSet);
return cb_isMinValueSet;
}
static bool n_IsMinValueSet (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Renderer.DialRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.IsMinValueSet;
}
#pragma warning restore 0169
static IntPtr id_isMinValueSet;
public virtual bool IsMinValueSet {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer']/method[@name='isMinValueSet' and count(parameter)=0]"
[Register ("isMinValueSet", "()Z", "GetIsMinValueSetHandler")]
get {
if (id_isMinValueSet == IntPtr.Zero)
id_isMinValueSet = JNIEnv.GetMethodID (class_ref, "isMinValueSet", "()Z");
if (GetType () == ThresholdType)
return JNIEnv.CallBooleanMethod (Handle, id_isMinValueSet);
else
return JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, id_isMinValueSet);
}
}
static Delegate cb_getMajorTicksSpacing;
#pragma warning disable 0169
static Delegate GetGetMajorTicksSpacingHandler ()
{
if (cb_getMajorTicksSpacing == null)
cb_getMajorTicksSpacing = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, double>) n_GetMajorTicksSpacing);
return cb_getMajorTicksSpacing;
}
static double n_GetMajorTicksSpacing (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Renderer.DialRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.MajorTicksSpacing;
}
#pragma warning restore 0169
static Delegate cb_setMajorTicksSpacing_D;
#pragma warning disable 0169
static Delegate GetSetMajorTicksSpacing_DHandler ()
{
if (cb_setMajorTicksSpacing_D == null)
cb_setMajorTicksSpacing_D = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, double>) n_SetMajorTicksSpacing_D);
return cb_setMajorTicksSpacing_D;
}
static void n_SetMajorTicksSpacing_D (IntPtr jnienv, IntPtr native__this, double p0)
{
global::Org.Achartengine.Renderer.DialRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.MajorTicksSpacing = p0;
}
#pragma warning restore 0169
static IntPtr id_getMajorTicksSpacing;
static IntPtr id_setMajorTicksSpacing_D;
public virtual double MajorTicksSpacing {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer']/method[@name='getMajorTicksSpacing' and count(parameter)=0]"
[Register ("getMajorTicksSpacing", "()D", "GetGetMajorTicksSpacingHandler")]
get {
if (id_getMajorTicksSpacing == IntPtr.Zero)
id_getMajorTicksSpacing = JNIEnv.GetMethodID (class_ref, "getMajorTicksSpacing", "()D");
if (GetType () == ThresholdType)
return JNIEnv.CallDoubleMethod (Handle, id_getMajorTicksSpacing);
else
return JNIEnv.CallNonvirtualDoubleMethod (Handle, ThresholdClass, id_getMajorTicksSpacing);
}
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer']/method[@name='setMajorTicksSpacing' and count(parameter)=1 and parameter[1][@type='double']]"
[Register ("setMajorTicksSpacing", "(D)V", "GetSetMajorTicksSpacing_DHandler")]
set {
if (id_setMajorTicksSpacing_D == IntPtr.Zero)
id_setMajorTicksSpacing_D = JNIEnv.GetMethodID (class_ref, "setMajorTicksSpacing", "(D)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_setMajorTicksSpacing_D, new JValue (value));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_setMajorTicksSpacing_D, new JValue (value));
}
}
static Delegate cb_getMaxValue;
#pragma warning disable 0169
static Delegate GetGetMaxValueHandler ()
{
if (cb_getMaxValue == null)
cb_getMaxValue = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, double>) n_GetMaxValue);
return cb_getMaxValue;
}
static double n_GetMaxValue (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Renderer.DialRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.MaxValue;
}
#pragma warning restore 0169
static Delegate cb_setMaxValue_D;
#pragma warning disable 0169
static Delegate GetSetMaxValue_DHandler ()
{
if (cb_setMaxValue_D == null)
cb_setMaxValue_D = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, double>) n_SetMaxValue_D);
return cb_setMaxValue_D;
}
static void n_SetMaxValue_D (IntPtr jnienv, IntPtr native__this, double p0)
{
global::Org.Achartengine.Renderer.DialRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.MaxValue = p0;
}
#pragma warning restore 0169
static IntPtr id_getMaxValue;
static IntPtr id_setMaxValue_D;
public virtual double MaxValue {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer']/method[@name='getMaxValue' and count(parameter)=0]"
[Register ("getMaxValue", "()D", "GetGetMaxValueHandler")]
get {
if (id_getMaxValue == IntPtr.Zero)
id_getMaxValue = JNIEnv.GetMethodID (class_ref, "getMaxValue", "()D");
if (GetType () == ThresholdType)
return JNIEnv.CallDoubleMethod (Handle, id_getMaxValue);
else
return JNIEnv.CallNonvirtualDoubleMethod (Handle, ThresholdClass, id_getMaxValue);
}
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer']/method[@name='setMaxValue' and count(parameter)=1 and parameter[1][@type='double']]"
[Register ("setMaxValue", "(D)V", "GetSetMaxValue_DHandler")]
set {
if (id_setMaxValue_D == IntPtr.Zero)
id_setMaxValue_D = JNIEnv.GetMethodID (class_ref, "setMaxValue", "(D)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_setMaxValue_D, new JValue (value));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_setMaxValue_D, new JValue (value));
}
}
static Delegate cb_getMinValue;
#pragma warning disable 0169
static Delegate GetGetMinValueHandler ()
{
if (cb_getMinValue == null)
cb_getMinValue = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, double>) n_GetMinValue);
return cb_getMinValue;
}
static double n_GetMinValue (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Renderer.DialRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.MinValue;
}
#pragma warning restore 0169
static Delegate cb_setMinValue_D;
#pragma warning disable 0169
static Delegate GetSetMinValue_DHandler ()
{
if (cb_setMinValue_D == null)
cb_setMinValue_D = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, double>) n_SetMinValue_D);
return cb_setMinValue_D;
}
static void n_SetMinValue_D (IntPtr jnienv, IntPtr native__this, double p0)
{
global::Org.Achartengine.Renderer.DialRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.MinValue = p0;
}
#pragma warning restore 0169
static IntPtr id_getMinValue;
static IntPtr id_setMinValue_D;
public virtual double MinValue {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer']/method[@name='getMinValue' and count(parameter)=0]"
[Register ("getMinValue", "()D", "GetGetMinValueHandler")]
get {
if (id_getMinValue == IntPtr.Zero)
id_getMinValue = JNIEnv.GetMethodID (class_ref, "getMinValue", "()D");
if (GetType () == ThresholdType)
return JNIEnv.CallDoubleMethod (Handle, id_getMinValue);
else
return JNIEnv.CallNonvirtualDoubleMethod (Handle, ThresholdClass, id_getMinValue);
}
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer']/method[@name='setMinValue' and count(parameter)=1 and parameter[1][@type='double']]"
[Register ("setMinValue", "(D)V", "GetSetMinValue_DHandler")]
set {
if (id_setMinValue_D == IntPtr.Zero)
id_setMinValue_D = JNIEnv.GetMethodID (class_ref, "setMinValue", "(D)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_setMinValue_D, new JValue (value));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_setMinValue_D, new JValue (value));
}
}
static Delegate cb_getMinorTicksSpacing;
#pragma warning disable 0169
static Delegate GetGetMinorTicksSpacingHandler ()
{
if (cb_getMinorTicksSpacing == null)
cb_getMinorTicksSpacing = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, double>) n_GetMinorTicksSpacing);
return cb_getMinorTicksSpacing;
}
static double n_GetMinorTicksSpacing (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Renderer.DialRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.MinorTicksSpacing;
}
#pragma warning restore 0169
static Delegate cb_setMinorTicksSpacing_D;
#pragma warning disable 0169
static Delegate GetSetMinorTicksSpacing_DHandler ()
{
if (cb_setMinorTicksSpacing_D == null)
cb_setMinorTicksSpacing_D = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, double>) n_SetMinorTicksSpacing_D);
return cb_setMinorTicksSpacing_D;
}
static void n_SetMinorTicksSpacing_D (IntPtr jnienv, IntPtr native__this, double p0)
{
global::Org.Achartengine.Renderer.DialRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.MinorTicksSpacing = p0;
}
#pragma warning restore 0169
static IntPtr id_getMinorTicksSpacing;
static IntPtr id_setMinorTicksSpacing_D;
public virtual double MinorTicksSpacing {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer']/method[@name='getMinorTicksSpacing' and count(parameter)=0]"
[Register ("getMinorTicksSpacing", "()D", "GetGetMinorTicksSpacingHandler")]
get {
if (id_getMinorTicksSpacing == IntPtr.Zero)
id_getMinorTicksSpacing = JNIEnv.GetMethodID (class_ref, "getMinorTicksSpacing", "()D");
if (GetType () == ThresholdType)
return JNIEnv.CallDoubleMethod (Handle, id_getMinorTicksSpacing);
else
return JNIEnv.CallNonvirtualDoubleMethod (Handle, ThresholdClass, id_getMinorTicksSpacing);
}
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer']/method[@name='setMinorTicksSpacing' and count(parameter)=1 and parameter[1][@type='double']]"
[Register ("setMinorTicksSpacing", "(D)V", "GetSetMinorTicksSpacing_DHandler")]
set {
if (id_setMinorTicksSpacing_D == IntPtr.Zero)
id_setMinorTicksSpacing_D = JNIEnv.GetMethodID (class_ref, "setMinorTicksSpacing", "(D)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_setMinorTicksSpacing_D, new JValue (value));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_setMinorTicksSpacing_D, new JValue (value));
}
}
static Delegate cb_getVisualTypeForIndex_I;
#pragma warning disable 0169
static Delegate GetGetVisualTypeForIndex_IHandler ()
{
if (cb_getVisualTypeForIndex_I == null)
cb_getVisualTypeForIndex_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, IntPtr>) n_GetVisualTypeForIndex_I);
return cb_getVisualTypeForIndex_I;
}
static IntPtr n_GetVisualTypeForIndex_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Achartengine.Renderer.DialRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle (__this.GetVisualTypeForIndex (p0));
}
#pragma warning restore 0169
static IntPtr id_getVisualTypeForIndex_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer']/method[@name='getVisualTypeForIndex' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("getVisualTypeForIndex", "(I)Lorg/achartengine/renderer/DialRenderer$Type;", "GetGetVisualTypeForIndex_IHandler")]
public virtual global::Org.Achartengine.Renderer.DialRenderer.Type GetVisualTypeForIndex (int p0)
{
if (id_getVisualTypeForIndex_I == IntPtr.Zero)
id_getVisualTypeForIndex_I = JNIEnv.GetMethodID (class_ref, "getVisualTypeForIndex", "(I)Lorg/achartengine/renderer/DialRenderer$Type;");
if (GetType () == ThresholdType)
return global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer.Type> (JNIEnv.CallObjectMethod (Handle, id_getVisualTypeForIndex_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef);
else
return global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer.Type> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, id_getVisualTypeForIndex_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef);
}
static Delegate cb_setVisualTypes_arrayLorg_achartengine_renderer_DialRenderer_Type_;
#pragma warning disable 0169
static Delegate GetSetVisualTypes_arrayLorg_achartengine_renderer_DialRenderer_Type_Handler ()
{
if (cb_setVisualTypes_arrayLorg_achartengine_renderer_DialRenderer_Type_ == null)
cb_setVisualTypes_arrayLorg_achartengine_renderer_DialRenderer_Type_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetVisualTypes_arrayLorg_achartengine_renderer_DialRenderer_Type_);
return cb_setVisualTypes_arrayLorg_achartengine_renderer_DialRenderer_Type_;
}
static void n_SetVisualTypes_arrayLorg_achartengine_renderer_DialRenderer_Type_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Achartengine.Renderer.DialRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.DialRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Org.Achartengine.Renderer.DialRenderer.Type[] p0 = (global::Org.Achartengine.Renderer.DialRenderer.Type[]) JNIEnv.GetArray (native_p0, JniHandleOwnership.DoNotTransfer, typeof (global::Org.Achartengine.Renderer.DialRenderer.Type));
__this.SetVisualTypes (p0);
if (p0 != null)
JNIEnv.CopyArray (p0, native_p0);
}
#pragma warning restore 0169
static IntPtr id_setVisualTypes_arrayLorg_achartengine_renderer_DialRenderer_Type_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='DialRenderer']/method[@name='setVisualTypes' and count(parameter)=1 and parameter[1][@type='org.achartengine.renderer.DialRenderer.Type[]']]"
[Register ("setVisualTypes", "([Lorg/achartengine/renderer/DialRenderer$Type;)V", "GetSetVisualTypes_arrayLorg_achartengine_renderer_DialRenderer_Type_Handler")]
public virtual void SetVisualTypes (global::Org.Achartengine.Renderer.DialRenderer.Type[] p0)
{
if (id_setVisualTypes_arrayLorg_achartengine_renderer_DialRenderer_Type_ == IntPtr.Zero)
id_setVisualTypes_arrayLorg_achartengine_renderer_DialRenderer_Type_ = JNIEnv.GetMethodID (class_ref, "setVisualTypes", "([Lorg/achartengine/renderer/DialRenderer$Type;)V");
IntPtr native_p0 = JNIEnv.NewArray (p0);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_setVisualTypes_arrayLorg_achartengine_renderer_DialRenderer_Type_, new JValue (native_p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_setVisualTypes_arrayLorg_achartengine_renderer_DialRenderer_Type_, new JValue (native_p0));
if (p0 != null) {
JNIEnv.CopyArray (native_p0, p0);
JNIEnv.DeleteLocalRef (native_p0);
}
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Linq;
using NLog.Conditions;
using NLog.Config;
using NLog.Internal;
using NLog.LayoutRenderers;
using NLog.Layouts;
using NLog.Targets.Wrappers;
using NLog.UnitTests.Targets.Wrappers;
namespace NLog.UnitTests.Targets
{
using System;
using System.Collections.Generic;
using System.Threading;
using NLog.Common;
using NLog.Targets;
using Xunit;
public class TargetTests : NLogTestBase
{
/// <summary>
/// Test the following things:
/// - Target has default ctor
/// - Target has ctor with name (string) arg.
/// - Both ctors are creating the same instances
/// </summary>
[Fact]
public void TargetContructorWithNameTest()
{
var targetTypes = typeof(Target).Assembly.GetTypes().Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(Target))).ToList();
int neededCheckCount = targetTypes.Count;
int checkCount = 0;
Target fileTarget = new FileTarget();
Target memoryTarget = new MemoryTarget();
foreach (Type targetType in targetTypes)
{
string lastPropertyName = null;
try
{
// Check if the Target can be created using a default constructor
var name = targetType + "_name";
var isWrapped = targetType.IsSubclassOf(typeof(WrapperTargetBase));
var isCompound = targetType.IsSubclassOf(typeof(CompoundTargetBase));
if (isWrapped)
{
neededCheckCount++;
var args = new List<object> { fileTarget };
//default ctor
var defaultConstructedTarget = (WrapperTargetBase)Activator.CreateInstance(targetType);
defaultConstructedTarget.Name = name;
defaultConstructedTarget.WrappedTarget = fileTarget;
//specials cases
if (targetType == typeof(FilteringTargetWrapper))
{
var cond = new ConditionLoggerNameExpression();
args.Add(cond);
var target = (FilteringTargetWrapper) defaultConstructedTarget;
target.Condition = cond;
}
else if (targetType == typeof(RepeatingTargetWrapper))
{
var repeatCount = 5;
args.Add(repeatCount);
var target = (RepeatingTargetWrapper)defaultConstructedTarget;
target.RepeatCount = repeatCount;
}
else if (targetType == typeof(RetryingTargetWrapper))
{
var retryCount = 10;
var retryDelayMilliseconds = 100;
args.Add(retryCount);
args.Add(retryDelayMilliseconds);
var target = (RetryingTargetWrapper)defaultConstructedTarget;
target.RetryCount = retryCount;
target.RetryDelayMilliseconds = retryDelayMilliseconds;
}
//ctor: target
var targetConstructedTarget = (WrapperTargetBase)Activator.CreateInstance(targetType, args.ToArray());
targetConstructedTarget.Name = name;
args.Insert(0, name);
//ctor: target+name
var namedConstructedTarget = (WrapperTargetBase)Activator.CreateInstance(targetType, args.ToArray());
CheckEquals(targetType, targetConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount);
CheckEquals(targetType, defaultConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount);
}
else if (isCompound)
{
neededCheckCount++;
//multiple targets
var args = new List<object> { fileTarget, memoryTarget };
//specials cases
//default ctor
var defaultConstructedTarget = (CompoundTargetBase)Activator.CreateInstance(targetType);
defaultConstructedTarget.Name = name;
defaultConstructedTarget.Targets.Add(fileTarget);
defaultConstructedTarget.Targets.Add(memoryTarget);
//ctor: target
var targetConstructedTarget = (CompoundTargetBase)Activator.CreateInstance(targetType, args.ToArray());
targetConstructedTarget.Name = name;
args.Insert(0, name);
//ctor: target+name
var namedConstructedTarget = (CompoundTargetBase)Activator.CreateInstance(targetType, args.ToArray());
CheckEquals(targetType, targetConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount);
CheckEquals(targetType, defaultConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount);
}
else
{
//default ctor
var targetConstructedTarget = (Target)Activator.CreateInstance(targetType);
targetConstructedTarget.Name = name;
// ctor: name
var namedConstructedTarget = (Target)Activator.CreateInstance(targetType, name);
CheckEquals(targetType, targetConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount);
}
}
catch (Exception ex)
{
var constructionFailed = true;
string failureMessage = String.Format("Error testing constructors for '{0}.{1}`\n{2}", targetType, lastPropertyName, ex.ToString());
Assert.False(constructionFailed, failureMessage);
}
}
Assert.Equal(neededCheckCount, checkCount);
}
private static void CheckEquals(Type targetType, Target defaultConstructedTarget, Target namedConstructedTarget,
ref string lastPropertyName, ref int @checked)
{
var checkedAtLeastOneProperty = false;
var properties = targetType.GetProperties(
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.FlattenHierarchy |
System.Reflection.BindingFlags.Default |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.Static);
foreach (System.Reflection.PropertyInfo pi in properties)
{
lastPropertyName = pi.Name;
if (pi.CanRead && !pi.Name.Equals("SyncRoot"))
{
var value1 = pi.GetValue(defaultConstructedTarget, null);
var value2 = pi.GetValue(namedConstructedTarget, null);
if (value1 != null && value2 != null)
{
if (value1 is IRenderable)
{
Assert.Equal((IRenderable) value1, (IRenderable) value2, new RenderableEq());
}
else if (value1 is AsyncRequestQueue)
{
Assert.Equal((AsyncRequestQueue) value1, (AsyncRequestQueue) value2, new AsyncRequestQueueEq());
}
else
{
Assert.Equal(value1, value2);
}
}
else
{
Assert.Null(value1);
Assert.Null(value2);
}
checkedAtLeastOneProperty = true;
}
}
if (checkedAtLeastOneProperty)
{
@checked++;
}
}
private class RenderableEq : EqualityComparer<IRenderable>
{
/// <summary>
/// Determines whether the specified objects are equal.
/// </summary>
/// <returns>
/// true if the specified objects are equal; otherwise, false.
/// </returns>
/// <param name="x">The first object of type <paramref name="T"/> to compare.</param><param name="y">The second object of type <paramref name="T"/> to compare.</param>
public override bool Equals(IRenderable x, IRenderable y)
{
if (x == null) return y == null;
var nullEvent = LogEventInfo.CreateNullEvent();
return x.Render(nullEvent) == y.Render(nullEvent);
}
/// <summary>
/// Returns a hash code for the specified object.
/// </summary>
/// <returns>
/// A hash code for the specified object.
/// </returns>
/// <param name="obj">The <see cref="T:System.Object"/> for which a hash code is to be returned.</param><exception cref="T:System.ArgumentNullException">The type of <paramref name="obj"/> is a reference type and <paramref name="obj"/> is null.</exception>
public override int GetHashCode(IRenderable obj)
{
return obj.ToString().GetHashCode();
}
}
private class AsyncRequestQueueEq : EqualityComparer<AsyncRequestQueue>
{
/// <summary>
/// Determines whether the specified objects are equal.
/// </summary>
/// <returns>
/// true if the specified objects are equal; otherwise, false.
/// </returns>
/// <param name="x">The first object of type <paramref name="T"/> to compare.</param><param name="y">The second object of type <paramref name="T"/> to compare.</param>
public override bool Equals(AsyncRequestQueue x, AsyncRequestQueue y)
{
if (x == null) return y == null;
return x.RequestLimit == y.RequestLimit && x.OnOverflow == y.OnOverflow;
}
/// <summary>
/// Returns a hash code for the specified object.
/// </summary>
/// <returns>
/// A hash code for the specified object.
/// </returns>
/// <param name="obj">The <see cref="T:System.Object"/> for which a hash code is to be returned.</param><exception cref="T:System.ArgumentNullException">The type of <paramref name="obj"/> is a reference type and <paramref name="obj"/> is null.</exception>
public override int GetHashCode(AsyncRequestQueue obj)
{
unchecked
{
return (obj.RequestLimit * 397) ^ (int)obj.OnOverflow;
}
}
}
[Fact]
public void InitializeTest()
{
var target = new MyTarget();
target.Initialize(null);
// initialize was called once
Assert.Equal(1, target.InitializeCount);
Assert.Equal(1, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Fact]
public void InitializeFailedTest()
{
var target = new MyTarget();
target.ThrowOnInitialize = true;
LogManager.ThrowExceptions = true;
Assert.Throws<InvalidOperationException>(() => target.Initialize(null));
// after exception in Initialize(), the target becomes non-functional and all Write() operations
var exceptions = new List<Exception>();
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
Assert.Equal(0, target.WriteCount);
Assert.Equal(1, exceptions.Count);
Assert.NotNull(exceptions[0]);
Assert.Equal("Target " + target + " failed to initialize.", exceptions[0].Message);
Assert.Equal("Init error.", exceptions[0].InnerException.Message);
}
[Fact]
public void DoubleInitializeTest()
{
var target = new MyTarget();
target.Initialize(null);
target.Initialize(null);
// initialize was called once
Assert.Equal(1, target.InitializeCount);
Assert.Equal(1, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Fact]
public void DoubleCloseTest()
{
var target = new MyTarget();
target.Initialize(null);
target.Close();
target.Close();
// initialize and close were called once each
Assert.Equal(1, target.InitializeCount);
Assert.Equal(1, target.CloseCount);
Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Fact]
public void CloseWithoutInitializeTest()
{
var target = new MyTarget();
target.Close();
// nothing was called
Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Fact]
public void WriteWithoutInitializeTest()
{
var target = new MyTarget();
List<Exception> exceptions = new List<Exception>();
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
target.WriteAsyncLogEvents(new[]
{
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
});
// write was not called
Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
Assert.Equal(4, exceptions.Count);
exceptions.ForEach(Assert.Null);
}
[Fact]
public void WriteOnClosedTargetTest()
{
var target = new MyTarget();
target.Initialize(null);
target.Close();
var exceptions = new List<Exception>();
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
target.WriteAsyncLogEvents(
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
Assert.Equal(1, target.InitializeCount);
Assert.Equal(1, target.CloseCount);
// write was not called
Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
// but all callbacks were invoked with null values
Assert.Equal(4, exceptions.Count);
exceptions.ForEach(Assert.Null);
}
[Fact]
public void FlushTest()
{
var target = new MyTarget();
List<Exception> exceptions = new List<Exception>();
target.Initialize(null);
target.Flush(exceptions.Add);
// flush was called
Assert.Equal(1, target.FlushCount);
Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
Assert.Equal(1, exceptions.Count);
exceptions.ForEach(Assert.Null);
}
[Fact]
public void FlushWithoutInitializeTest()
{
var target = new MyTarget();
List<Exception> exceptions = new List<Exception>();
target.Flush(exceptions.Add);
Assert.Equal(1, exceptions.Count);
exceptions.ForEach(Assert.Null);
// flush was not called
Assert.Equal(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Fact]
public void FlushOnClosedTargetTest()
{
var target = new MyTarget();
target.Initialize(null);
target.Close();
Assert.Equal(1, target.InitializeCount);
Assert.Equal(1, target.CloseCount);
List<Exception> exceptions = new List<Exception>();
target.Flush(exceptions.Add);
Assert.Equal(1, exceptions.Count);
exceptions.ForEach(Assert.Null);
// flush was not called
Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
}
[Fact]
public void LockingTest()
{
var target = new MyTarget();
target.Initialize(null);
var mre = new ManualResetEvent(false);
Exception backgroundThreadException = null;
Thread t = new Thread(() =>
{
try
{
target.BlockingOperation(1000);
}
catch (Exception ex)
{
backgroundThreadException = ex;
}
finally
{
mre.Set();
}
});
target.Initialize(null);
t.Start();
Thread.Sleep(50);
List<Exception> exceptions = new List<Exception>();
target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
target.WriteAsyncLogEvents(new[]
{
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
});
target.Flush(exceptions.Add);
target.Close();
exceptions.ForEach(Assert.Null);
mre.WaitOne();
if (backgroundThreadException != null)
{
Assert.True(false, backgroundThreadException.ToString());
}
}
[Fact]
public void GivenNullEvents_WhenWriteAsyncLogEvents_ThenNoExceptionAreThrown()
{
var target = new MyTarget();
try
{
target.WriteAsyncLogEvents(null);
}
catch (Exception e)
{
Assert.True(false, "Exception thrown: " + e);
}
}
[Fact]
public void WriteFormattedStringEvent_WithNullArgument()
{
var target = new MyTarget();
SimpleConfigurator.ConfigureForTargetLogging(target);
var logger = LogManager.GetLogger("WriteFormattedStringEvent_EventWithNullArguments");
string t = null;
logger.Info("Testing null:{0}", t);
Assert.Equal(1, target.WriteCount);
}
public class MyTarget : Target
{
private int inBlockingOperation;
public int InitializeCount { get; set; }
public int CloseCount { get; set; }
public int FlushCount { get; set; }
public int WriteCount { get; set; }
public int WriteCount2 { get; set; }
public bool ThrowOnInitialize { get; set; }
public int WriteCount3 { get; set; }
public MyTarget() : base()
{
}
public MyTarget(string name) : this()
{
this.Name = name;
}
protected override void InitializeTarget()
{
if (this.ThrowOnInitialize)
{
throw new InvalidOperationException("Init error.");
}
Assert.Equal(0, this.inBlockingOperation);
this.InitializeCount++;
base.InitializeTarget();
}
protected override void CloseTarget()
{
Assert.Equal(0, this.inBlockingOperation);
this.CloseCount++;
base.CloseTarget();
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
Assert.Equal(0, this.inBlockingOperation);
this.FlushCount++;
base.FlushAsync(asyncContinuation);
}
protected override void Write(LogEventInfo logEvent)
{
Assert.Equal(0, this.inBlockingOperation);
this.WriteCount++;
}
protected override void Write(AsyncLogEventInfo logEvent)
{
Assert.Equal(0, this.inBlockingOperation);
this.WriteCount2++;
base.Write(logEvent);
}
protected override void Write(AsyncLogEventInfo[] logEvents)
{
Assert.Equal(0, this.inBlockingOperation);
this.WriteCount3++;
base.Write(logEvents);
}
public void BlockingOperation(int millisecondsTimeout)
{
lock (this.SyncRoot)
{
this.inBlockingOperation++;
Thread.Sleep(millisecondsTimeout);
this.inBlockingOperation--;
}
}
}
[Fact]
public void WrongMyTargetShouldNotThrowExceptionWhenThrowExceptionsIsFalse()
{
var target = new WrongMyTarget();
LogManager.ThrowExceptions = false;
SimpleConfigurator.ConfigureForTargetLogging(target);
var logger = LogManager.GetLogger("WrongMyTargetShouldThrowException");
logger.Info("Testing");
var layouts = target.GetAllLayouts();
Assert.NotNull(layouts);
}
public class WrongMyTarget : Target
{
public WrongMyTarget() : base()
{
}
public WrongMyTarget(string name) : this()
{
this.Name = name;
}
/// <summary>
/// Initializes the target. Can be used by inheriting classes
/// to initialize logging.
/// </summary>
protected override void InitializeTarget()
{
//base.InitializeTarget() should be called
}
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Java.Beans.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 Java.Beans
{
/// <summary>
/// <para>The implementation of this listener proxy just delegates the received events to its listener. </para>
/// </summary>
/// <java-name>
/// java/beans/PropertyChangeListenerProxy
/// </java-name>
[Dot42.DexImport("java/beans/PropertyChangeListenerProxy", AccessFlags = 33)]
public partial class PropertyChangeListenerProxy : global::Java.Util.EventListenerProxy, global::Java.Beans.IPropertyChangeListener
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new listener proxy that associates a listener with a property name.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)]
public PropertyChangeListenerProxy(string propertyName, global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the name of the property associated with this listener proxy.</para><para></para>
/// </summary>
/// <returns>
/// <para>the name of the associated property. </para>
/// </returns>
/// <java-name>
/// getPropertyName
/// </java-name>
[Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetPropertyName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>The source bean calls this method when an event is raised.</para><para></para>
/// </summary>
/// <java-name>
/// propertyChange
/// </java-name>
[Dot42.DexImport("propertyChange", "(Ljava/beans/PropertyChangeEvent;)V", AccessFlags = 1)]
public virtual void PropertyChange(global::Java.Beans.PropertyChangeEvent @event) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal PropertyChangeListenerProxy() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Returns the name of the property associated with this listener proxy.</para><para></para>
/// </summary>
/// <returns>
/// <para>the name of the associated property. </para>
/// </returns>
/// <java-name>
/// getPropertyName
/// </java-name>
public string PropertyName
{
[Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetPropertyName(); }
}
}
/// <summary>
/// <para>Manages a list of listeners to be notified when a property changes. Listeners subscribe to be notified of all property changes, or of changes to a single named property.</para><para>This class is thread safe. No locking is necessary when subscribing or unsubscribing listeners, or when publishing events. Callers should be careful when publishing events because listeners may not be thread safe. </para>
/// </summary>
/// <java-name>
/// java/beans/PropertyChangeSupport
/// </java-name>
[Dot42.DexImport("java/beans/PropertyChangeSupport", AccessFlags = 33)]
public partial class PropertyChangeSupport : global::Java.Io.ISerializable
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new instance that uses the source bean as source for any event.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/Object;)V", AccessFlags = 1)]
public PropertyChangeSupport(object sourceBean) /* MethodBuilder.Create */
{
}
/// <java-name>
/// firePropertyChange
/// </java-name>
[Dot42.DexImport("firePropertyChange", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 1)]
public virtual void FirePropertyChange(string @string, object @object, object object1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// fireIndexedPropertyChange
/// </java-name>
[Dot42.DexImport("fireIndexedPropertyChange", "(Ljava/lang/String;ILjava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 1)]
public virtual void FireIndexedPropertyChange(string @string, int int32, object @object, object object1) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Unsubscribes <c> listener </c> from change notifications for the property named <c> propertyName </c> . If multiple subscriptions exist for <c> listener </c> , it will receive one fewer notifications when the property changes. If the property name or listener is null or not subscribed, this method silently does nothing. </para>
/// </summary>
/// <java-name>
/// removePropertyChangeListener
/// </java-name>
[Dot42.DexImport("removePropertyChangeListener", "(Ljava/lang/String;Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)]
public virtual void RemovePropertyChangeListener(string propertyName, global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Subscribes <c> listener </c> to change notifications for the property named <c> propertyName </c> . If the listener is already subscribed, it will receive an additional notification when the property changes. If the property name or listener is null, this method silently does nothing. </para>
/// </summary>
/// <java-name>
/// addPropertyChangeListener
/// </java-name>
[Dot42.DexImport("addPropertyChangeListener", "(Ljava/lang/String;Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)]
public virtual void AddPropertyChangeListener(string propertyName, global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the subscribers to be notified when <c> propertyName </c> changes. This includes both listeners subscribed to all property changes and listeners subscribed to the named property only. </para>
/// </summary>
/// <java-name>
/// getPropertyChangeListeners
/// </java-name>
[Dot42.DexImport("getPropertyChangeListeners", "(Ljava/lang/String;)[Ljava/beans/PropertyChangeListener;", AccessFlags = 1)]
public virtual global::Java.Beans.IPropertyChangeListener[] GetPropertyChangeListeners(string propertyName) /* MethodBuilder.Create */
{
return default(global::Java.Beans.IPropertyChangeListener[]);
}
/// <java-name>
/// firePropertyChange
/// </java-name>
[Dot42.DexImport("firePropertyChange", "(Ljava/lang/String;ZZ)V", AccessFlags = 1)]
public virtual void FirePropertyChange(string @string, bool boolean, bool boolean1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// fireIndexedPropertyChange
/// </java-name>
[Dot42.DexImport("fireIndexedPropertyChange", "(Ljava/lang/String;IZZ)V", AccessFlags = 1)]
public virtual void FireIndexedPropertyChange(string @string, int int32, bool boolean, bool boolean1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// firePropertyChange
/// </java-name>
[Dot42.DexImport("firePropertyChange", "(Ljava/lang/String;II)V", AccessFlags = 1)]
public virtual void FirePropertyChange(string @string, int int32, int int321) /* MethodBuilder.Create */
{
}
/// <java-name>
/// fireIndexedPropertyChange
/// </java-name>
[Dot42.DexImport("fireIndexedPropertyChange", "(Ljava/lang/String;III)V", AccessFlags = 1)]
public virtual void FireIndexedPropertyChange(string @string, int int32, int int321, int int322) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns true if there are listeners registered to the property with the given name.</para><para></para>
/// </summary>
/// <returns>
/// <para>true if there are listeners registered to that property, false otherwise. </para>
/// </returns>
/// <java-name>
/// hasListeners
/// </java-name>
[Dot42.DexImport("hasListeners", "(Ljava/lang/String;)Z", AccessFlags = 1)]
public virtual bool HasListeners(string propertyName) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Unsubscribes <c> listener </c> from change notifications for all properties. If the listener has multiple subscriptions, it will receive one fewer notification when properties change. If the property name or listener is null or not subscribed, this method silently does nothing. </para>
/// </summary>
/// <java-name>
/// removePropertyChangeListener
/// </java-name>
[Dot42.DexImport("removePropertyChangeListener", "(Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)]
public virtual void RemovePropertyChangeListener(global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Subscribes <c> listener </c> to change notifications for all properties. If the listener is already subscribed, it will receive an additional notification. If the listener is null, this method silently does nothing. </para>
/// </summary>
/// <java-name>
/// addPropertyChangeListener
/// </java-name>
[Dot42.DexImport("addPropertyChangeListener", "(Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)]
public virtual void AddPropertyChangeListener(global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns all subscribers. This includes both listeners subscribed to all property changes and listeners subscribed to a single property. </para>
/// </summary>
/// <java-name>
/// getPropertyChangeListeners
/// </java-name>
[Dot42.DexImport("getPropertyChangeListeners", "()[Ljava/beans/PropertyChangeListener;", AccessFlags = 1)]
public virtual global::Java.Beans.IPropertyChangeListener[] GetPropertyChangeListeners() /* MethodBuilder.Create */
{
return default(global::Java.Beans.IPropertyChangeListener[]);
}
/// <summary>
/// <para>Publishes a property change event to all listeners of that property. If the event's old and new values are equal (but non-null), no event will be published. </para>
/// </summary>
/// <java-name>
/// firePropertyChange
/// </java-name>
[Dot42.DexImport("firePropertyChange", "(Ljava/beans/PropertyChangeEvent;)V", AccessFlags = 1)]
public virtual void FirePropertyChange(global::Java.Beans.PropertyChangeEvent @event) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal PropertyChangeSupport() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Returns all subscribers. This includes both listeners subscribed to all property changes and listeners subscribed to a single property. </para>
/// </summary>
/// <java-name>
/// getPropertyChangeListeners
/// </java-name>
public global::Java.Beans.IPropertyChangeListener[] PropertyChangeListeners
{
[Dot42.DexImport("getPropertyChangeListeners", "()[Ljava/beans/PropertyChangeListener;", AccessFlags = 1)]
get{ return GetPropertyChangeListeners(); }
}
}
/// <summary>
/// <para>An event that indicates that a constraint or a boundary of a property has changed. </para>
/// </summary>
/// <java-name>
/// java/beans/PropertyChangeEvent
/// </java-name>
[Dot42.DexImport("java/beans/PropertyChangeEvent", AccessFlags = 33)]
public partial class PropertyChangeEvent : global::Java.Util.EventObject
/* scope: __dot42__ */
{
/// <summary>
/// <para>The constructor used to create a new <c> PropertyChangeEvent </c> .</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 1)]
public PropertyChangeEvent(object source, string propertyName, object oldValue, object newValue) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the name of the property that has changed. If an unspecified set of properties has changed it returns null.</para><para></para>
/// </summary>
/// <returns>
/// <para>the name of the property that has changed, or null. </para>
/// </returns>
/// <java-name>
/// getPropertyName
/// </java-name>
[Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetPropertyName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Sets the propagationId object.</para><para><para>getPropagationId() </para></para>
/// </summary>
/// <java-name>
/// setPropagationId
/// </java-name>
[Dot42.DexImport("setPropagationId", "(Ljava/lang/Object;)V", AccessFlags = 1)]
public virtual void SetPropagationId(object propagationId) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the propagationId object. This is reserved for future use. Beans 1.0 demands that a listener receiving this property and then sending its own PropertyChangeEvent sets the received propagationId on the new PropertyChangeEvent's propagationId field.</para><para></para>
/// </summary>
/// <returns>
/// <para>the propagationId object. </para>
/// </returns>
/// <java-name>
/// getPropagationId
/// </java-name>
[Dot42.DexImport("getPropagationId", "()Ljava/lang/Object;", AccessFlags = 1)]
public virtual object GetPropagationId() /* MethodBuilder.Create */
{
return default(object);
}
/// <summary>
/// <para>Returns the old value that the property had. If the old value is unknown this method returns null.</para><para></para>
/// </summary>
/// <returns>
/// <para>the old property value or null. </para>
/// </returns>
/// <java-name>
/// getOldValue
/// </java-name>
[Dot42.DexImport("getOldValue", "()Ljava/lang/Object;", AccessFlags = 1)]
public virtual object GetOldValue() /* MethodBuilder.Create */
{
return default(object);
}
/// <summary>
/// <para>Returns the new value that the property now has. If the new value is unknown this method returns null.</para><para></para>
/// </summary>
/// <returns>
/// <para>the old property value or null. </para>
/// </returns>
/// <java-name>
/// getNewValue
/// </java-name>
[Dot42.DexImport("getNewValue", "()Ljava/lang/Object;", AccessFlags = 1)]
public virtual object GetNewValue() /* MethodBuilder.Create */
{
return default(object);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal PropertyChangeEvent() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Returns the name of the property that has changed. If an unspecified set of properties has changed it returns null.</para><para></para>
/// </summary>
/// <returns>
/// <para>the name of the property that has changed, or null. </para>
/// </returns>
/// <java-name>
/// getPropertyName
/// </java-name>
public string PropertyName
{
[Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetPropertyName(); }
}
/// <summary>
/// <para>Returns the propagationId object. This is reserved for future use. Beans 1.0 demands that a listener receiving this property and then sending its own PropertyChangeEvent sets the received propagationId on the new PropertyChangeEvent's propagationId field.</para><para></para>
/// </summary>
/// <returns>
/// <para>the propagationId object. </para>
/// </returns>
/// <java-name>
/// getPropagationId
/// </java-name>
public object PropagationId
{
[Dot42.DexImport("getPropagationId", "()Ljava/lang/Object;", AccessFlags = 1)]
get{ return GetPropagationId(); }
[Dot42.DexImport("setPropagationId", "(Ljava/lang/Object;)V", AccessFlags = 1)]
set{ SetPropagationId(value); }
}
/// <summary>
/// <para>Returns the old value that the property had. If the old value is unknown this method returns null.</para><para></para>
/// </summary>
/// <returns>
/// <para>the old property value or null. </para>
/// </returns>
/// <java-name>
/// getOldValue
/// </java-name>
public object OldValue
{
[Dot42.DexImport("getOldValue", "()Ljava/lang/Object;", AccessFlags = 1)]
get{ return GetOldValue(); }
}
/// <summary>
/// <para>Returns the new value that the property now has. If the new value is unknown this method returns null.</para><para></para>
/// </summary>
/// <returns>
/// <para>the old property value or null. </para>
/// </returns>
/// <java-name>
/// getNewValue
/// </java-name>
public object NewValue
{
[Dot42.DexImport("getNewValue", "()Ljava/lang/Object;", AccessFlags = 1)]
get{ return GetNewValue(); }
}
}
/// <summary>
/// <para>A type of PropertyChangeEvent that indicates that an indexed property has changed. </para>
/// </summary>
/// <java-name>
/// java/beans/IndexedPropertyChangeEvent
/// </java-name>
[Dot42.DexImport("java/beans/IndexedPropertyChangeEvent", AccessFlags = 33)]
public partial class IndexedPropertyChangeEvent : global::Java.Beans.PropertyChangeEvent
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new property changed event with an indication of the property index.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;I)V", AccessFlags = 1)]
public IndexedPropertyChangeEvent(object source, string propertyName, object oldValue, object newValue, int index) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the index of the property that was changed in this event. </para>
/// </summary>
/// <java-name>
/// getIndex
/// </java-name>
[Dot42.DexImport("getIndex", "()I", AccessFlags = 1)]
public virtual int GetIndex() /* MethodBuilder.Create */
{
return default(int);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal IndexedPropertyChangeEvent() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Returns the index of the property that was changed in this event. </para>
/// </summary>
/// <java-name>
/// getIndex
/// </java-name>
public int Index
{
[Dot42.DexImport("getIndex", "()I", AccessFlags = 1)]
get{ return GetIndex(); }
}
}
/// <summary>
/// <para>A PropertyChangeListener can subscribe with a event source. Whenever that source raises a PropertyChangeEvent this listener will get notified. </para>
/// </summary>
/// <java-name>
/// java/beans/PropertyChangeListener
/// </java-name>
[Dot42.DexImport("java/beans/PropertyChangeListener", AccessFlags = 1537)]
public partial interface IPropertyChangeListener : global::Java.Util.IEventListener
/* scope: __dot42__ */
{
/// <summary>
/// <para>The source bean calls this method when an event is raised.</para><para></para>
/// </summary>
/// <java-name>
/// propertyChange
/// </java-name>
[Dot42.DexImport("propertyChange", "(Ljava/beans/PropertyChangeEvent;)V", AccessFlags = 1025)]
void PropertyChange(global::Java.Beans.PropertyChangeEvent @event) /* MethodBuilder.Create */ ;
}
}
| |
using Xunit;
namespace Jint.Tests.Ecma
{
public class Test_15_5_4_10 : EcmaTest
{
[Fact]
[Trait("Category", "15.5.4.10")]
public void TheStringPrototypeMatchLengthPropertyHasTheAttributeReadonly()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A10.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void TheLengthPropertyOfTheMatchMethodIs1()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A11.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void StringPrototypeMatchRegexp()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A1_T1.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void StringPrototypeMatchRegexp2()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A1_T10.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void StringPrototypeMatchRegexp3()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A1_T11.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void StringPrototypeMatchRegexp4()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A1_T12.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void StringPrototypeMatchRegexp5()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A1_T13.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void StringPrototypeMatchRegexp6()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A1_T14.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void StringPrototypeMatchRegexp7()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A1_T2.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void StringPrototypeMatchRegexp8()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A1_T3.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void StringPrototypeMatchRegexp9()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A1_T4.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void StringPrototypeMatchRegexp10()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A1_T5.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void StringPrototypeMatchRegexp11()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A1_T6.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void StringPrototypeMatchRegexp12()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A1_T7.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void StringPrototypeMatchRegexp13()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A1_T8.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void StringPrototypeMatchRegexp14()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A1_T9.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void MatchReturnsArrayAsSpecifiedIn151062()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A2_T1.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void MatchReturnsArrayAsSpecifiedIn1510622()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A2_T10.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void MatchReturnsArrayAsSpecifiedIn1510623()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A2_T11.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void MatchReturnsArrayAsSpecifiedIn1510624()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A2_T12.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void MatchReturnsArrayAsSpecifiedIn1510625()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A2_T13.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void MatchReturnsArrayAsSpecifiedIn1510626()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A2_T14.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void MatchReturnsArrayAsSpecifiedIn1510627()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A2_T15.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void MatchReturnsArrayAsSpecifiedIn1510628()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A2_T16.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void MatchReturnsArrayAsSpecifiedIn1510629()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A2_T17.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void MatchReturnsArrayAsSpecifiedIn15106210()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A2_T18.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void MatchReturnsArrayAsSpecifiedIn15106211()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A2_T2.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void MatchReturnsArrayAsSpecifiedIn15106212()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A2_T3.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void MatchReturnsArrayAsSpecifiedIn15106213()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A2_T4.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void MatchReturnsArrayAsSpecifiedIn15106214()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A2_T5.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void MatchReturnsArrayAsSpecifiedIn15106215()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A2_T6.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void MatchReturnsArrayAsSpecifiedIn15106216()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A2_T7.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void MatchReturnsArrayAsSpecifiedIn15106217()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A2_T8.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void MatchReturnsArrayAsSpecifiedIn15106218()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A2_T9.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void StringPrototypeMatchHasNotPrototypeProperty()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A6.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void StringPrototypeMatchCanTBeUsedAsConstructor()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A7.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void TheStringPrototypeMatchLengthPropertyHasTheAttributeDontenum()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A8.js", false);
}
[Fact]
[Trait("Category", "15.5.4.10")]
public void TheStringPrototypeMatchLengthPropertyHasTheAttributeDontdelete()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.10/S15.5.4.10_A9.js", false);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using NUnit.Framework;
using SIL.DictionaryServices.Model;
using SIL.Lift;
using SIL.Lift.Options;
using SIL.TestUtilities;
using SIL.Text;
namespace SIL.DictionaryServices.Tests.Model
{
[TestFixture]
public class LexEntryCloneableTests:CloneableTests<LexEntry>
{
public override LexEntry CreateNewCloneable()
{
return new LexEntry();
}
public override string ExceptionList
{
//_guid: should not be identical to the original
//_id: relies on guid and should also not be identical to original
//_creationTime: we want the creation time of the clone.. not the original
//_modificationTime: the clone is brand new. We don't care when the original was last modified.
//_isDirty|_isBeingDeleted|_modificationTimeIsLocked: all management stuff that shouldn't need to be cloned
//_listEventHelpers: No good way to clone eventhandlers
//_parent: We are doing top down clones. Children shouldn't make clones of their parents, but parents of their children.
//EmptyObjectsRemoved: No good way to clone eventhandlers. The parent should be taking care of this rather than the clone() method.
get { return "|_guid|_id|_creationTime|_modificationTime|IsDirty|IsBeingDeleted|ModifiedTimeIsLocked|_listEventHelpers|_parent|PropertyChanged|EmptyObjectsRemoved|"; }
}
protected override List<ValuesToSet> DefaultValuesForTypes
{
get
{
var sense = new LexSense();
sense.AddRelationTarget("rel", "targ");
var unequalSense = new LexSense();
unequalSense.AddRelationTarget("rel2", "targ2");
return new List<ValuesToSet>
{
new ValuesToSet("to be", "!(to be)"),
new ValuesToSet(42, 7),
new ValuesToSet(
new MultiText{Forms=new[]{new LanguageForm("en", "en_form", null)}},
new MultiText{Forms=new[]{new LanguageForm("de", "de_form", null)}}),
new ValuesToSet(
new BindingList<LexSense> {sense},
new BindingList<LexSense> {unequalSense}
),
new ValuesToSet(
new BindingList<LexVariant>{new LexVariant{EmbeddedXmlElements = new List<string>(new[]{"to", "be"})}},
new BindingList<LexVariant>{new LexVariant{EmbeddedXmlElements = new List<string>(new[]{"!", "to", "be"})}}),
new ValuesToSet(new BindingList<LexNote> {new LexNote("note"), new LexNote("music")}, new BindingList<LexNote> {new LexNote("take no note"), new LexNote("heavy metal")}),
new ValuesToSet(
new BindingList<LexPhonetic> {new LexPhonetic{EmbeddedXmlElements = new List<string>(new[]{"to", "be"})}},
new BindingList<LexPhonetic> {new LexPhonetic{EmbeddedXmlElements = new List<string>(new[]{"not", "to", "be"})}}),
new ValuesToSet(new BindingList<LexEtymology> { new LexEtymology("one", "eins") }, new BindingList<LexEtymology> { new LexEtymology("two", "zwei") }),
new ValuesToSet(true, false),
new ValuesToSet(
new List<KeyValuePair<string, IPalasoDataObjectProperty>>(new[]{
new KeyValuePair<string, IPalasoDataObjectProperty>("one", new LexNote()),
new KeyValuePair<string, IPalasoDataObjectProperty>("two", new LexNote())}),
new List<KeyValuePair<string, IPalasoDataObjectProperty>>(new[]{
new KeyValuePair<string, IPalasoDataObjectProperty>("three", new LexNote()),
new KeyValuePair<string, IPalasoDataObjectProperty>("four", new LexNote())}))
};
}
}
[Test]
public void Clone_NewGuidIsCreatedAndNotZeros()
{
var entry = new LexEntry();
var entry2 = entry.Clone();
Assert.That(entry.Guid, Is.Not.EqualTo(entry2.Guid));
Assert.That(entry.Guid, Is.Not.EqualTo(Guid.Empty));
}
[Test]
public void Clone_ClonedEntryHasId_NewIdIsCreatedForNewEntry()
{
var entry = new LexEntry();
entry.LexicalForm.SetAlternative("en","form");
entry.GetOrCreateId(true);
var entry2 = entry.Clone();
Assert.That(entry2.Id, Is.Not.EqualTo(entry.Id));
Assert.That(entry2.Id, Is.Not.Null);
}
[Test]
public void Clone_ClonedEntryHasNoId_NoIdIsCreatedForNewEntry()
{
var entry = new LexEntry();
var entry2 = entry.Clone();
Assert.That(entry.Id, Is.EqualTo(entry2.Id));
}
}
[TestFixture]
public class LexEntryTests
{
private LexEntry _entry;
private LexSense _sense;
private LexExampleSentence _examples;
private bool _removed;
[SetUp]
public void Setup()
{
_entry = new LexEntry();
_sense = new LexSense();
_entry.Senses.Add(_sense);
#if GlossMeaning
this._sense.Gloss["th"] = "sense";
#else
_sense.Definition["th"] = "sense";
#endif
MultiText customFieldInSense =
_sense.GetOrCreateProperty<MultiText>("customFieldInSense");
customFieldInSense["th"] = "custom";
_examples = new LexExampleSentence();
_sense.ExampleSentences.Add(_examples);
_examples.Sentence["th"] = "example";
_examples.Translation["en"] = "translation";
MultiText customFieldInExample =
_examples.GetOrCreateProperty<MultiText>("customFieldInExample");
customFieldInExample["th"] = "custom";
_entry.EmptyObjectsRemoved += _entry_EmptyObjectsRemoved;
_entry.PropertyChanged += _entry_PropertyChanged;
_removed = false;
}
[Test]
public void ExampleSentencePropertiesInUse_HasPropertyProp1_ReturnsProp1()
{
var ex = new LexExampleSentence();
ex.GetOrCreateProperty<MultiText>("Prop1");
Assert.That(ex.PropertiesInUse, Contains.Item("Prop1"));
Assert.That(ex.PropertiesInUse.Count(), Is.EqualTo(3));
}
[Test]
public void ExampleSentencePropertiesInUse_HasMultipleProperties_ReturnsProperties()
{
var ex = new LexExampleSentence();
ex.GetOrCreateProperty<MultiText>("Prop1");
ex.GetOrCreateProperty<MultiText>("Prop2");
Assert.That(ex.PropertiesInUse, Contains.Item("Prop1"));
Assert.That(ex.PropertiesInUse, Contains.Item("Prop2"));
Assert.That(ex.PropertiesInUse.Count(), Is.EqualTo(4));
}
[Test]
public void LexSensePropertiesInUse_HasPropertyProp1_ReturnsProp1()
{
var lexSense = new LexSense();
lexSense.GetOrCreateProperty<MultiText>("Prop1");
Assert.That(lexSense.PropertiesInUse, Contains.Item("Prop1"));
Assert.That(lexSense.PropertiesInUse.Count(), Is.EqualTo(1));
}
[Test]
public void LexSensePropertiesInUse_HasMultipleProperties_ReturnsProperties()
{
var lexSense = new LexSense();
lexSense.GetOrCreateProperty<MultiText>("Prop1");
lexSense.GetOrCreateProperty<MultiText>("Prop2");
Assert.That(lexSense.PropertiesInUse, Contains.Item("Prop1"));
Assert.That(lexSense.PropertiesInUse, Contains.Item("Prop2"));
Assert.That(lexSense.PropertiesInUse.Count(), Is.EqualTo(2));
}
[Test]
public void LexSensePropertiesInUse_SenseAndMulitipleExampleSentencesHaveMultipleProperties_ReturnsAllProperties()
{
var ex1 = new LexExampleSentence();
ex1.GetOrCreateProperty<MultiText>("Ex1Prop1");
ex1.GetOrCreateProperty<MultiText>("Ex1Prop2");
var ex2 = new LexExampleSentence();
ex2.GetOrCreateProperty<MultiText>("Ex2Prop1");
ex2.GetOrCreateProperty<MultiText>("Ex2Prop2");
var lexSense = new LexSense();
lexSense.GetOrCreateProperty<MultiText>("Prop1");
lexSense.GetOrCreateProperty<MultiText>("Prop2");
lexSense.ExampleSentences.Add(ex1);
lexSense.ExampleSentences.Add(ex2);
Assert.That(lexSense.PropertiesInUse, Contains.Item("Ex1Prop1"));
Assert.That(lexSense.PropertiesInUse, Contains.Item("Ex1Prop2"));
Assert.That(lexSense.PropertiesInUse, Contains.Item("Ex2Prop1"));
Assert.That(lexSense.PropertiesInUse, Contains.Item("Ex2Prop2"));
Assert.That(lexSense.PropertiesInUse, Contains.Item("Prop1"));
Assert.That(lexSense.PropertiesInUse, Contains.Item("Prop2"));
Assert.That(lexSense.PropertiesInUse.Count(), Is.EqualTo(10));
}
[Test]
public void LexEntryPropertiesInUse_HasPropertyProp1_ReturnsProp1()
{
var entry = new LexEntry();
entry.GetOrCreateProperty<MultiText>("Prop1");
Assert.That(entry.PropertiesInUse, Contains.Item("Prop1"));
Assert.That(entry.PropertiesInUse.Count(), Is.EqualTo(1));
}
[Test]
public void LexEntryPropertiesInUse_HasMultipleProperties_ReturnsProperties()
{
var entry = new LexEntry();
entry.GetOrCreateProperty<MultiText>("Prop1");
entry.GetOrCreateProperty<MultiText>("Prop2");
Assert.That(entry.PropertiesInUse, Contains.Item("Prop1"));
Assert.That(entry.PropertiesInUse, Contains.Item("Prop2"));
Assert.That(entry.PropertiesInUse.Count(), Is.EqualTo(2));
}
[Test]
public void LexEntryPropertiesInUse_EntryandMultipleSensesAndExampleSentencesHaveMultipleProperties_ReturnsAllProperties()
{
var ex1 = new LexExampleSentence();
ex1.GetOrCreateProperty<MultiText>("Ex1Prop1");
ex1.GetOrCreateProperty<MultiText>("Ex1Prop2");
var ex2 = new LexExampleSentence();
ex2.GetOrCreateProperty<MultiText>("Ex2Prop1");
ex2.GetOrCreateProperty<MultiText>("Ex2Prop2");
var ex3 = new LexExampleSentence();
ex3.GetOrCreateProperty<MultiText>("Ex3Prop1");
ex3.GetOrCreateProperty<MultiText>("Ex3Prop2");
var lexSense1 = new LexSense();
lexSense1.GetOrCreateProperty<MultiText>("Se1Prop1");
lexSense1.GetOrCreateProperty<MultiText>("Se1Prop2");
var lexSense2 = new LexSense();
lexSense2.GetOrCreateProperty<MultiText>("Se2Prop1");
lexSense2.GetOrCreateProperty<MultiText>("Se2Prop2");
var entry = new LexEntry();
entry.GetOrCreateProperty<MultiText>("Prop1");
entry.GetOrCreateProperty<MultiText>("Prop2");
entry.Senses.Add(lexSense1);
entry.Senses.Add(lexSense2);
lexSense1.ExampleSentences.Add(ex1);
lexSense1.ExampleSentences.Add(ex2);
lexSense2.ExampleSentences.Add(ex3);
Assert.That(entry.PropertiesInUse, Contains.Item("Ex1Prop1"));
Assert.That(entry.PropertiesInUse, Contains.Item("Ex1Prop2"));
Assert.That(entry.PropertiesInUse, Contains.Item("Ex2Prop1"));
Assert.That(entry.PropertiesInUse, Contains.Item("Ex2Prop2"));
Assert.That(entry.PropertiesInUse, Contains.Item("Ex3Prop1"));
Assert.That(entry.PropertiesInUse, Contains.Item("Ex3Prop2"));
Assert.That(entry.PropertiesInUse, Contains.Item("Se1Prop1"));
Assert.That(entry.PropertiesInUse, Contains.Item("Se1Prop2"));
Assert.That(entry.PropertiesInUse, Contains.Item("Se2Prop1"));
Assert.That(entry.PropertiesInUse, Contains.Item("Se2Prop2"));
Assert.That(entry.PropertiesInUse, Contains.Item("Prop1"));
Assert.That(entry.PropertiesInUse, Contains.Item("Prop2"));
Assert.That(entry.PropertiesInUse.Count(), Is.EqualTo(18));
}
[Test]
public void GetSomeMeaningToUseInAbsenseOfHeadWord_NoGloss_GivesDefinition()
{
var sense = new LexSense();
sense.Definition.SetAlternative("en", "blue");
var entry = new LexEntry();
entry.Senses.Add(sense);
Assert.AreEqual("blue",entry.GetSomeMeaningToUseInAbsenseOfHeadWord("en"));
}
[Test]
public void GetSomeMeaningToUseInAbsenseOfHeadWord_NoSenses_GivesMessage()
{
var entry = new LexEntry();
Assert.AreEqual("?NoMeaning?", entry.GetSomeMeaningToUseInAbsenseOfHeadWord("en"));
}
[Test]
public void GetSomeMeaningToUseInAbsenseOfHeadWord_GlossAndDef_GivesGloss()
{
var sense = new LexSense();
sense.Gloss.SetAlternative("en", "red");
sense.Definition.SetAlternative("en", "blue");
var entry = new LexEntry();
entry.Senses.Add(sense);
Assert.AreEqual("red", entry.GetSomeMeaningToUseInAbsenseOfHeadWord("en"));
}
[Test]
public void GetSomeMeaningToUseInAbsenseOfHeadWord_NoDef_GivesGloss()
{
var sense = new LexSense();
sense.Gloss.SetAlternative("en", "red");
var entry = new LexEntry();
entry.Senses.Add(sense);
Assert.AreEqual("red", entry.GetSomeMeaningToUseInAbsenseOfHeadWord("en"));
}
[Test]
public void GetSomeMeaningToUseInAbsenseOfHeadWord_MultipleGlosses_GivesRequestedOne()
{
var sense = new LexSense();
sense.Gloss.SetAlternative("en", "man");
sense.Gloss.SetAlternative("fr", "homme");
var entry = new LexEntry();
entry.Senses.Add(sense);
Assert.AreEqual("man", entry.GetSomeMeaningToUseInAbsenseOfHeadWord("en"));
Assert.AreEqual("homme", entry.GetSomeMeaningToUseInAbsenseOfHeadWord("fr"));
}
[Test]
public void GetSomeMeaningToUseInAbsenseOfHeadWord_NoGlossOrMeaningInLang_GivesMessage()
{
var sense = new LexSense();
sense.Gloss.SetAlternative("en", "man");
var entry = new LexEntry();
entry.Senses.Add(sense);
Assert.AreEqual("man", entry.GetSomeMeaningToUseInAbsenseOfHeadWord("en"));
Assert.AreEqual("?NoGlossOrDef?", entry.GetSomeMeaningToUseInAbsenseOfHeadWord("fr"));
}
[Test]
public void Cleanup_HasBaseform_PropertyIsNotRemoved()
{
var target = new LexEntry();
_entry = new LexEntry();
_entry.LexicalForm["v"] = "hello";
_entry.AddRelationTarget(LexEntry.WellKnownProperties.BaseForm, target.GetOrCreateId(true));
_entry.CleanUpAfterEditting();
Assert.IsNotNull(_entry.GetProperty<LexRelationCollection>(LexEntry.WellKnownProperties.BaseForm));
}
[Test]
public void Cleanup_HasEmptyBaseform_PropertyIsRemoved()
{
var target = new LexEntry();
_entry = new LexEntry();
_entry.LexicalForm["v"] = "hello";
_entry.AddRelationTarget(LexEntry.WellKnownProperties.BaseForm, string.Empty);
Assert.IsNotNull(_entry.GetProperty<LexRelationCollection>(LexEntry.WellKnownProperties.BaseForm));
_entry.CleanUpAfterEditting();
Assert.IsNull(_entry.GetProperty<LexRelationCollection>(LexEntry.WellKnownProperties.BaseForm));
}
private void _entry_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
_entry.CleanUpEmptyObjects();
}
private void _entry_EmptyObjectsRemoved(object sender, EventArgs e)
{
_removed = true;
}
private void ClearExampleSentence()
{
_examples.Sentence["th"] = string.Empty;
}
private void ClearExampleTranslation()
{
_examples.Translation["en"] = string.Empty;
}
private void ClearExampleCustom()
{
MultiText customFieldInExample =
_examples.GetOrCreateProperty<MultiText>("customFieldInExample");
customFieldInExample["th"] = string.Empty;
_entry.CleanUpAfterEditting();
}
private void ClearSenseMeaning()
{
#if GlossMeaning
this._sense.Gloss["th"] = string.Empty;
#else
_sense.Definition["th"] = string.Empty;
#endif
}
private void ClearSenseExample()
{
ClearExampleSentence();
ClearExampleTranslation();
ClearExampleCustom();
_removed = false;
}
private void ClearSenseCustom()
{
MultiText customFieldInSense =
_sense.GetOrCreateProperty<MultiText>("customFieldInSense");
customFieldInSense["th"] = string.Empty;
_entry.CleanUpAfterEditting();
}
[Test]
public void Example_Empty_False()
{
Assert.IsFalse(_examples.IsEmpty);
}
[Test]
public void ExampleWithOnlySentence_Empty_False()
{
ClearExampleTranslation();
ClearExampleCustom();
Assert.IsFalse(_removed);
Assert.IsFalse(_examples.IsEmpty);
}
[Test]
public void ExampleWithOnlyTranslation_Empty_False()
{
ClearExampleSentence();
ClearExampleCustom();
Assert.IsFalse(_removed);
Assert.IsFalse(_examples.IsEmpty);
}
[Test]
public void ExampleWithOnlyCustomField_Empty_False()
{
ClearExampleSentence();
ClearExampleTranslation();
Assert.IsFalse(_removed);
Assert.IsFalse(_examples.IsEmpty);
}
[Test]
public void ExampleWithNoFields_Empty_True()
{
ClearExampleSentence();
ClearExampleTranslation();
ClearExampleCustom();
Assert.IsTrue(_removed);
Assert.IsTrue(_examples.IsEmpty);
}
[Test]
public void EmptyExampleRemoved()
{
ClearExampleSentence();
ClearExampleTranslation();
ClearExampleCustom();
Assert.IsTrue(_removed);
Assert.AreEqual(0, _sense.ExampleSentences.Count);
}
[Test]
public void SenseWithOnlyMeaning_Empty_False()
{
ClearSenseExample();
ClearSenseCustom();
Assert.IsFalse(_removed);
Assert.IsFalse(_sense.IsEmpty);
}
[Test]
public void SenseWithOnlyExample_Empty_False()
{
ClearSenseMeaning();
ClearSenseCustom();
Assert.IsFalse(_removed);
Assert.IsFalse(_sense.IsEmpty);
}
[Test]
public void SenseWithOnlyCustom_Empty_False()
{
ClearSenseMeaning();
ClearSenseExample();
Assert.IsFalse(_removed);
Assert.IsFalse(_sense.IsEmpty);
}
[Test]
public void SenseWithNoExampleOrField_Empty_True()
{
ClearSenseMeaning();
ClearSenseExample();
ClearSenseCustom();
Assert.IsTrue(_removed);
Assert.IsTrue(_sense.IsEmpty);
}
[Test]
public void SenseWithOnlyPOS_ReadyForDeletion()
{
Assert.IsFalse(_sense.IsEmptyForPurposesOfDeletion);
ClearSenseMeaning();
ClearSenseExample();
ClearSenseCustom();
Assert.IsTrue(_sense.IsEmpty);
OptionRef pos =
_sense.GetOrCreateProperty<OptionRef>(LexSense.WellKnownProperties.PartOfSpeech);
pos.Value = "noun";
Assert.IsFalse(_sense.IsEmpty);
Assert.IsTrue(_sense.IsEmptyForPurposesOfDeletion);
}
//Not fixed yet [Test]
public void SenseWithAPicture_ReadyForDeletion()
{
Assert.IsFalse(_sense.IsEmptyForPurposesOfDeletion);
ClearSenseMeaning();
ClearSenseExample();
ClearSenseCustom();
Assert.IsTrue(_sense.IsEmpty);
PictureRef pict =
_sense.GetOrCreateProperty<PictureRef>(LexSense.WellKnownProperties.Picture);
pict.Value = "dummy.png";
Assert.IsFalse(_sense.IsEmpty);
Assert.IsTrue(_sense.IsEmptyForPurposesOfDeletion);
}
[Test]
public void EmptySensesRemoved()
{
ClearSenseMeaning();
ClearSenseExample();
ClearSenseCustom();
Assert.IsTrue(_removed);
Assert.AreEqual(0, _entry.Senses.Count);
}
[Test]
public void GetOrCreateSenseWithMeaning_SenseDoesNotExist_NewSenseWithMeaning()
{
MultiText meaning = new MultiText();
meaning.SetAlternative("th", "new");
LexSense sense = _entry.GetOrCreateSenseWithMeaning(meaning);
Assert.AreNotSame(_sense, sense);
#if GlossMeaning
Assert.AreEqual("new", sense.Gloss.GetExactAlternative("th"));
#else
Assert.AreEqual("new", sense.Definition.GetExactAlternative("th"));
#endif
}
[Test]
public void GetOrCreateSenseWithMeaning_SenseWithEmptyStringExists_ExistingSense()
{
ClearSenseMeaning();
MultiText meaning = new MultiText();
meaning.SetAlternative("th", string.Empty);
LexSense sense = _entry.GetOrCreateSenseWithMeaning(meaning);
Assert.AreSame(_sense, sense);
}
[Test]
public void GetOrCreateSenseWithMeaning_SenseDoesExists_ExistingSense()
{
MultiText meaning = new MultiText();
meaning.SetAlternative("th", "sense");
LexSense sense = _entry.GetOrCreateSenseWithMeaning(meaning);
Assert.AreSame(_sense, sense);
}
[Test]
public void GetHeadword_EmptyEverything_ReturnsEmptyString()
{
LexEntry entry = new LexEntry();
Assert.AreEqual(string.Empty, entry.GetHeadWordForm("a"));
}
[Test]
public void GetHeadword_LexemeForm_ReturnsCorrectAlternative()
{
LexEntry entry = new LexEntry();
entry.LexicalForm.SetAlternative("c", "can");
entry.LexicalForm.SetAlternative("a", "apple");
entry.LexicalForm.SetAlternative("b", "bart");
Assert.AreEqual("apple", entry.GetHeadWordForm("a"));
Assert.AreEqual("bart", entry.GetHeadWordForm("b"));
Assert.AreEqual(string.Empty, entry.GetHeadWordForm("donthave"));
}
[Test]
public void GetHeadword_CitationFormHasAlternative_CorrectForm()
{
LexEntry entry = new LexEntry();
entry.LexicalForm.SetAlternative("a", "apple");
MultiText citation =
entry.GetOrCreateProperty<MultiText>(LexEntry.WellKnownProperties.Citation);
citation.SetAlternative("b", "barter");
citation.SetAlternative("a", "applishus");
Assert.AreEqual("applishus", entry.GetHeadWordForm("a"));
Assert.AreEqual("barter", entry.GetHeadWordForm("b"));
Assert.AreEqual(string.Empty, entry.GetHeadWordForm("donthave"));
}
[Test]
public void GetHeadword_CitationFormLacksAlternative_GetsFormFromLexemeForm()
{
LexEntry entry = new LexEntry();
entry.LexicalForm.SetAlternative("a", "apple");
MultiText citation =
entry.GetOrCreateProperty<MultiText>(LexEntry.WellKnownProperties.Citation);
citation.SetAlternative("b", "bater");
Assert.AreEqual("apple", entry.GetHeadWordForm("a"));
}
[Test]
public void LexEntryConstructor_IsDirtyReturnsTrue()
{
LexEntry entry = new LexEntry();
Assert.IsTrue(entry.IsDirty);
}
[Test]
public void Clean_IsDirtyReturnsFalse()
{
LexEntry entry = new LexEntry();
entry.Clean();
Assert.IsFalse(entry.IsDirty);
}
[Test]
public void LexEntryChanges_IsDirtyReturnsTrue()
{
LexEntry entry = new LexEntry();
entry.Clean();
entry.Senses.Add(new LexSense());
Assert.IsTrue(entry.IsDirty);
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
#region Imports
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using NVelocity.Runtime;
using Spring.Core.TypeResolution;
using Spring.Objects;
using Spring.Objects.Factory.Config;
using Spring.Objects.Factory.Support;
using Spring.Objects.Factory.Xml;
using Spring.Util;
#endregion
namespace Spring.Template.Velocity.Config {
/// <summary>
/// Implementation of the custom configuration parser for template configurations
/// based on
/// <see cref="ObjectsNamespaceParser"/>
/// </summary>
/// <author>Erez Mazor</author>
/// <see cref="ObjectsNamespaceParser"/>
[
NamespaceParser(
Namespace = "http://www.springframework.net/nvelocity",
SchemaLocationAssemblyHint = typeof(TemplateNamespaceParser),
SchemaLocation = "/Spring.Template.Velocity.Config/spring-nvelocity-1.3.xsd")
]
public class TemplateNamespaceParser : ObjectsNamespaceParser {
private const string TemplateTypePrefix = "template: ";
static TemplateNamespaceParser() {
TypeRegistry.RegisterType(TemplateTypePrefix + TemplateDefinitionConstants.NVelocityElement, typeof(VelocityEngineFactoryObject));
}
/// <summary>
/// Initializes a new instance of the <see cref="TemplateNamespaceParser"/> class.
/// </summary>
public TemplateNamespaceParser() {
}
/// <see cref="INamespaceParser"/>
public override IObjectDefinition ParseElement(XmlElement element, ParserContext parserContext) {
string name = element.GetAttribute(ObjectDefinitionConstants.IdAttribute);
IConfigurableObjectDefinition templateDefinition = ParseTemplateDefinition(element, parserContext);
if (!StringUtils.HasText(name)) {
name = ObjectDefinitionReaderUtils.GenerateObjectName(templateDefinition, parserContext.Registry);
}
parserContext.Registry.RegisterObjectDefinition(name, templateDefinition);
return null;
}
/// <summary>
/// Parse a template definition from the templating namespace
/// </summary>
/// <param name="element">the root element defining the templating object</param>
/// <param name="parserContext">the parser context</param>
/// <returns></returns>
private IConfigurableObjectDefinition ParseTemplateDefinition(XmlElement element, ParserContext parserContext) {
switch (element.LocalName) {
case TemplateDefinitionConstants.NVelocityElement:
return ParseNVelocityEngine(element, parserContext);
default:
throw new ArgumentException(string.Format("undefined element for templating namespace: {0}", element.LocalName));
}
}
/// <summary>
/// Parses the object definition for the engine object, configures a single NVelocity template engine based
/// on the element definitions.
/// </summary>
/// <param name="element">the root element defining the velocity engine</param>
/// <param name="parserContext">the parser context</param>
private IConfigurableObjectDefinition ParseNVelocityEngine(XmlElement element, ParserContext parserContext) {
string typeName = GetTypeName(element);
IConfigurableObjectDefinition configurableObjectDefinition = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition(
typeName, null, parserContext.ReaderContext.Reader.Domain);
string preferFileSystemAccess = GetAttributeValue(element, TemplateDefinitionConstants.AttributePreferFileSystemAccess);
string overrideLogging = GetAttributeValue(element, TemplateDefinitionConstants.AttributeOverrideLogging);
string configFile = GetAttributeValue(element, TemplateDefinitionConstants.AttributeConfigFile);
MutablePropertyValues objectDefinitionProperties = new MutablePropertyValues();
if (StringUtils.HasText(preferFileSystemAccess)) {
objectDefinitionProperties.Add(TemplateDefinitionConstants.PropertyPreferFileSystemAccess, preferFileSystemAccess);
}
if (StringUtils.HasText(overrideLogging)) {
objectDefinitionProperties.Add(TemplateDefinitionConstants.PropertyOverrideLogging, overrideLogging);
}
if (StringUtils.HasText(configFile)) {
objectDefinitionProperties.Add(TemplateDefinitionConstants.PropertyConfigFile, configFile);
}
XmlNodeList childElements = element.ChildNodes;
if (childElements.Count > 0) {
ParseChildDefinitions(childElements, parserContext, objectDefinitionProperties);
}
configurableObjectDefinition.PropertyValues = objectDefinitionProperties;
return configurableObjectDefinition;
}
/// <summary>
/// Parses child element definitions for the NVelocity engine. Typically resource loaders and locally defined properties are parsed here
/// </summary>
/// <param name="childElements">the XmlNodeList representing the child configuration of the root NVelocity engine element</param>
/// <param name="parserContext">the parser context</param>
/// <param name="objectDefinitionProperties">the MutablePropertyValues used to configure this object</param>
private void ParseChildDefinitions(XmlNodeList childElements, ParserContext parserContext, MutablePropertyValues objectDefinitionProperties) {
IDictionary<string, object> properties = new Dictionary<string, object>();
foreach (XmlElement element in childElements) {
switch (element.LocalName) {
case TemplateDefinitionConstants.ElementResourceLoader:
ParseResourceLoader(element, objectDefinitionProperties, properties);
break;
case TemplateDefinitionConstants.ElementNVelocityProperties:
ParseNVelocityProperties(element, parserContext, properties);
break;
}
}
if (properties.Count > 0) {
objectDefinitionProperties.Add(TemplateDefinitionConstants.PropertyVelocityProperties, properties);
}
}
/// <summary>
/// Configures the NVelocity resource loader definitions from the xml definition
/// </summary>
/// <param name="element">the root resource loader element</param>
/// <param name="objectDefinitionProperties">the MutablePropertyValues used to configure this object</param>
/// <param name="properties">the properties used to initialize the velocity engine</param>
private void ParseResourceLoader(XmlElement element, MutablePropertyValues objectDefinitionProperties, IDictionary<string, object> properties) {
string caching = GetAttributeValue(element, TemplateDefinitionConstants.AttributeTemplateCaching);
string defaultCacheSize = GetAttributeValue(element, TemplateDefinitionConstants.AttributeDefaultCacheSize);
string modificationCheckInterval = GetAttributeValue(element, TemplateDefinitionConstants.AttributeModificationCheckInterval);
if (!string.IsNullOrEmpty(defaultCacheSize)) {
properties.Add(RuntimeConstants.RESOURCE_MANAGER_DEFAULTCACHE_SIZE, defaultCacheSize);
}
XmlNodeList loaderElements = element.ChildNodes;
switch (loaderElements[0].LocalName) {
case VelocityConstants.File:
AppendFileLoaderProperties(loaderElements, properties);
AppendResourceLoaderGlobalProperties(properties, VelocityConstants.File, caching,
modificationCheckInterval);
break;
case VelocityConstants.Assembly:
AppendAssemblyLoaderProperties(loaderElements, properties);
AppendResourceLoaderGlobalProperties(properties, VelocityConstants.Assembly, caching, null);
break;
case TemplateDefinitionConstants.Spring:
AppendResourceLoaderPaths(loaderElements, objectDefinitionProperties);
AppendResourceLoaderGlobalProperties(properties, TemplateDefinitionConstants.Spring, caching, null);
break;
case TemplateDefinitionConstants.Custom:
XmlElement firstElement = (XmlElement)loaderElements.Item(0);
AppendCustomLoaderProperties(firstElement, properties);
AppendResourceLoaderGlobalProperties(properties, firstElement.LocalName, caching, modificationCheckInterval);
break;
default:
throw new ArgumentException(string.Format("undefined element for resource loadre type: {0}", element.LocalName));
}
}
/// <summary>
/// Set the caching and modification interval checking properties of a resource loader of a given type
/// </summary>
/// <param name="properties">the properties used to initialize the velocity engine</param>
/// <param name="type">type of the resource loader</param>
/// <param name="caching">caching flag</param>
/// <param name="modificationInterval">modification interval value</param>
private void AppendResourceLoaderGlobalProperties(IDictionary<string, object> properties, string type, string caching, string modificationInterval) {
AppendResourceLoaderGlobalProperty(properties, type,
TemplateDefinitionConstants.PropertyResourceLoaderCaching,
Convert.ToBoolean(caching));
AppendResourceLoaderGlobalProperty
(properties, type, TemplateDefinitionConstants.PropertyResourceLoaderModificationCheckInterval, Convert.ToInt64(modificationInterval));
}
/// <summary>
/// Set global velocity resource loader properties (caching, modification interval etc.)
/// </summary>
/// <param name="properties">the properties used to initialize the velocity engine</param>
/// <param name="type">the type of resource loader</param>
/// <param name="property">the suffix property</param>
/// <param name="value">the value of the property</param>
private void AppendResourceLoaderGlobalProperty(IDictionary<string, object> properties, string type, string property, object value) {
if (null != value) {
properties.Add(type + VelocityConstants.Separator + property, value);
}
}
/// <summary>
/// Creates a nvelocity file based resource loader by setting the required properties
/// </summary>
/// <param name="elements">a list of nv:file elements defining the paths to template files</param>
/// <param name="properties">the properties used to initialize the velocity engine</param>
private void AppendFileLoaderProperties(XmlNodeList elements, IDictionary<string, object> properties) {
IList<string> paths = new List<string>(elements.Count);
foreach (XmlElement element in elements)
{
paths.Add(GetAttributeValue(element, VelocityConstants.Path));
}
properties.Add(RuntimeConstants.RESOURCE_LOADER, VelocityConstants.File);
properties.Add(getResourceLoaderProperty(VelocityConstants.File, VelocityConstants.Class), TemplateDefinitionConstants.FileResourceLoaderClass);
properties.Add(getResourceLoaderProperty(VelocityConstants.File, VelocityConstants.Path), StringUtils.CollectionToCommaDelimitedString(paths));
}
/// <summary>
/// Creates a nvelocity assembly based resource loader by setting the required properties
/// </summary>
/// <param name="elements">a list of nv:assembly elements defining the assemblies</param>
/// <param name="properties">the properties used to initialize the velocity engine</param>
private void AppendAssemblyLoaderProperties(XmlNodeList elements, IDictionary<string, object> properties) {
IList<string> assemblies = new List<string>(elements.Count);
foreach (XmlElement element in elements) {
assemblies.Add(GetAttributeValue(element, VelocityConstants.Name));
}
properties.Add(RuntimeConstants.RESOURCE_LOADER, VelocityConstants.Assembly);
properties.Add(getResourceLoaderProperty(VelocityConstants.Assembly, VelocityConstants.Class), TemplateDefinitionConstants.AssemblyResourceLoaderClass);
properties.Add(getResourceLoaderProperty(VelocityConstants.Assembly, VelocityConstants.Assembly), StringUtils.CollectionToCommaDelimitedString(assemblies));
}
/// <summary>
/// Creates a spring resource loader by setting the ResourceLoaderPaths of the
/// engine factory (the resource loader itself will be created internally either as
/// spring or as file resource loader based on the value of prefer-file-system-access
/// attribute).
/// </summary>
/// <param name="elements">list of resource loader path elements</param>
/// <param name="objectDefinitionProperties">the MutablePropertyValues to set the property for the engine factory</param>
private void AppendResourceLoaderPaths(XmlNodeList elements, MutablePropertyValues objectDefinitionProperties) {
IList<string> paths = new List<string>();
foreach (XmlElement element in elements) {
string path = GetAttributeValue(element, TemplateDefinitionConstants.AttributeUri);
paths.Add(path);
}
objectDefinitionProperties.Add(TemplateDefinitionConstants.PropertyResourceLoaderPaths, paths);
}
/// <summary>
/// Create a custom resource loader from an nv:custom element
/// generates the 4 required nvelocity props for a resource loader (name, description, class and path).
/// </summary>
/// <param name="element">the nv:custom xml definition element</param>
/// <param name="properties">the properties used to initialize the velocity engine</param>
private void AppendCustomLoaderProperties(XmlElement element, IDictionary<string, object> properties) {
string name = GetAttributeValue(element, VelocityConstants.Name);
string description = GetAttributeValue(element, VelocityConstants.Description);
string type = GetAttributeValue(element, VelocityConstants.Type);
string path = GetAttributeValue(element, VelocityConstants.Path);
properties.Add(RuntimeConstants.RESOURCE_LOADER, name);
properties.Add(getResourceLoaderProperty(name, VelocityConstants.Description), description);
properties.Add(getResourceLoaderProperty(name, VelocityConstants.Class), type.Replace(',', ';'));
properties.Add(getResourceLoaderProperty(name, VelocityConstants.Path), path);
}
/// <summary>
/// Parses the nvelocity properties map using <code>ObjectNamespaceParserHelper</code>
/// and appends it to the properties dictionary
/// </summary>
/// <param name="element">root element of the map element</param>
/// <param name="parserContext">the parser context</param>
/// <param name="properties">the properties used to initialize the velocity engine</param>
private void ParseNVelocityProperties(XmlElement element, ParserContext parserContext, IDictionary<string, object> properties) {
IDictionary parsedProperties = ParseDictionaryElement(element,
TemplateDefinitionConstants.ElementNVelocityProperties, parserContext);
foreach (DictionaryEntry entry in parsedProperties) {
properties.Add(Convert.ToString(entry.Key), entry.Value);
}
}
/// <summary>
/// Gets the name of the object type for the specified element.
/// </summary>
/// <param name="element">The element.</param>
/// <returns>The name of the object type.</returns>
private string GetTypeName(XmlElement element) {
string typeName = element.GetAttribute(ObjectDefinitionConstants.TypeAttribute);
if (StringUtils.IsNullOrEmpty(typeName)) {
return TemplateTypePrefix + element.LocalName;
}
return typeName;
}
/// <summary>
/// constructs an nvelocity style resource loader property in the format:
/// prefix.resource.loader.suffix
/// </summary>
/// <param name="type">the prefix</param>
/// <param name="suffix">the suffix</param>
/// <returns>a concatenated string like: prefix.resource.loader.suffix</returns>
public static string getResourceLoaderProperty(string type, string suffix) {
return type + VelocityConstants.Separator + RuntimeConstants.RESOURCE_LOADER + VelocityConstants.Separator +
suffix;
}
/// <summary>
/// This method is overriden from ObjectsNamespaceParser since when invoked on
/// sub-elements from the objets namespace (e.g., objects:objectMap for nvelocity
/// property map) the <code>element.SelectNodes</code> fails because it is in
/// the nvelocity custom namespace and not the object's namespace (http://www.springframwork.net)
/// to amend this the object's namespace is added to the provided XmlNamespaceManager
/// </summary>
///<param name="element"> The element to be searched in. </param>
/// <param name="childElementName"> The name of the child nodes to look for.
/// </param>
/// <returns> The child <see cref="System.Xml.XmlNode"/>s of the supplied
/// <paramref name="element"/> with the supplied <paramref name="childElementName"/>.
/// </returns>
/// <see cref="ObjectsNamespaceParser"/>
[Obsolete("not used anymore - ObjectsNamespaceParser will be dropped with 2.x, use ObjectDefinitionParserHelper instead")]
protected override XmlNodeList SelectNodes(XmlElement element, string childElementName) {
XmlNamespaceManager nsManager = new XmlNamespaceManager(new NameTable());
nsManager.AddNamespace(GetNamespacePrefix(element), element.NamespaceURI);
nsManager.AddNamespace(GetNamespacePrefix(element), Namespace);
return element.SelectNodes(GetNamespacePrefix(element) + ":" + childElementName, nsManager);
}
private string GetNamespacePrefix(XmlElement element) {
return StringUtils.HasText(element.Prefix) ? element.Prefix : "spring";
}
}
#region Element & Attribute Name Constants
/// <summary>
/// Template definition constants
/// </summary>
public class TemplateDefinitionConstants {
/// <summary>
/// Engine element definition
/// </summary>
public const string NVelocityElement = "engine";
/// <summary>
/// Spring resource loader element definition
/// </summary>
public const string Spring = "spring";
/// <summary>
/// Custom resource loader element definition
/// </summary>
public const string Custom = "custom";
/// <summary>
/// uri attribute of the spring element
/// </summary>
public const string AttributeUri = "uri";
/// <summary>
/// prefer-file-system-access attribute of the engine factory
/// </summary>
public const string AttributePreferFileSystemAccess = "prefer-file-system-access";
/// <summary>
/// config-file attribute of the engine factory
/// </summary>
public const string AttributeConfigFile = "config-file";
/// <summary>
/// override-logging attribute of the engine factory
/// </summary>
public const string AttributeOverrideLogging = "override-logging";
/// <summary>
/// template-caching attribute of the nvelocity engine
/// </summary>
public const string AttributeTemplateCaching = "template-caching";
/// <summary>
/// default-cache-size attribute of the nvelocity engine resource manager
/// </summary>
public const string AttributeDefaultCacheSize = "default-cache-size";
/// <summary>
/// modification-check-interval attribute of the nvelocity engine resource loader
/// </summary>
public const string AttributeModificationCheckInterval = "modification-check-interval";
/// <summary>
/// resource loader element
/// </summary>
public const string ElementResourceLoader = "resource-loader";
/// <summary>
/// nvelocity propeties element (map)
/// </summary>
public const string ElementNVelocityProperties = "nvelocity-properties";
/// <summary>
/// PreferFileSystemAccess property of the engine factory
/// </summary>
public const string PropertyPreferFileSystemAccess = "PreferFileSystemAccess";
/// <summary>
/// OverrideLogging property of the engine factory
/// </summary>
public const string PropertyOverrideLogging = "OverrideLogging";
/// <summary>
/// ConfigLocation property of the engine factory
/// </summary>
public const string PropertyConfigFile = "ConfigLocation";
/// <summary>
/// ResourceLoaderPaths property of the engine factory
/// </summary>
public const string PropertyResourceLoaderPaths = "ResourceLoaderPaths";
/// <summary>
/// VelocityProperties property of the engine factory
/// </summary>
public const string PropertyVelocityProperties = "VelocityProperties";
/// <summary>
/// resource.loader.cache property of the resource loader configuration
/// </summary>
public const string PropertyResourceLoaderCaching = "resource.loader.cache";
/// <summary>
/// resource.loader.modificationCheckInterval property of the resource loader configuration
/// </summary>
public const string PropertyResourceLoaderModificationCheckInterval = "resource.loader.modificationCheckInterval";
/// <summary>
/// the type used for file resource loader
/// </summary>
public const string FileResourceLoaderClass = "NVelocity.Runtime.Resource.Loader.FileResourceLoader; NVelocity";
/// <summary>
/// the type used for assembly resource loader
/// </summary>
public const string AssemblyResourceLoaderClass = "NVelocity.Runtime.Resource.Loader.AssemblyResourceLoader; NVelocity";
/// <summary>
/// the type used for spring resource loader
/// </summary>
public const string SpringResourceLoaderClass = "Spring.Template.Velocity.SpringResourceLoader; Spring.Template.Velocity.Castle";
}
#endregion
}
| |
// Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * 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 Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WSABoo.Parser.Tests
{
using NUnit.Framework;
using Boo.Lang.Compiler;
using Boo.Lang.Compiler.Ast;
using Boo.Lang.Compiler.IO;
using Boo.Lang.Parser;
[TestFixture]
public class WSABooParserTestFixture
{
[Test]
public void SanityCheck()
{
string code = @"
class Foo(Bar):
def foo():
if foo:
print 'foo'
end
if bar:
print 'bar'
elif foo:
print 'foo'
else:
print 'uops...'
end
print 'foo again'
end
item[key]:
get:
return key
end
end
def empty():
end
end
";
Module module = parse(code);
string expected = @"
class Foo(Bar):
def foo():
if foo:
print 'foo'
if bar:
print 'bar'
elif foo:
print 'foo'
else:
print 'uops...'
print 'foo again'
item[key]:
get:
return key
def empty():
pass
";
Assert.AreEqual(normalize(expected), normalize(module.ToCodeString()));
}
[Test]
public void EmptyModule()
{
Assert.AreEqual("", normalize(parse("").ToCodeString()));
}
[Test]
public void SanityCheckUsingDoubleQuotes()
{
string code = @"
def SayHello(name as string):
return ""Hello, $name""
end
";
Module module = parse(code);
string expected = @"
def SayHello(name as string):
return ""Hello, $name""
";
Assert.AreEqual(normalize(expected), normalize(module.ToCodeString()));
}
[Test]
public void NoLineBreakBeforeEOF()
{
string code = "print \"hello\"";
Module module = parse(code);
string expected = "print 'hello'";
Assert.AreEqual(normalize(expected), normalize(module.ToCodeString()));
}
[Test]
public void InputNameIsPreserved()
{
string inputName = "File.boo";
Module module = parse(new StringInput(inputName, "class Foo:\nend"));
AssertInputName(inputName, module);
foreach (TypeMember member in module.Members)
AssertInputName(inputName, member);
}
[Test]
public void NonBlockColons()
{
string inputName = "File.boo";
Module module = parse(new StringInput(inputName, "class Foo:\nlst = (of int: 1)\ndct = {'foo':\n\t'bar'}\nend"));
AssertInputName(inputName, module);
foreach (TypeMember member in module.Members)
AssertInputName(inputName, member);
}
[Test]
public void LabelColons()
{
string inputName = "File.boo";
string expected = ":label\nprint 'foo'\ngoto label";
Module module = parse(new StringInput(inputName, expected));
AssertInputName(inputName, module);
Assert.AreEqual(normalize(expected), normalize(module.ToCodeString()));
}
[Test]
public void LogicalOr()
{
string code = "a = (false or true)";
string expected = code;
Module module = parse (new StringInput ("test", code));
Assert.AreEqual (normalize (expected), normalize (module.ToCodeString ()));
}
[Test]
public void ForOr()
{
string code = "for i in items:\nor:\nend";
string expected = "for i in items:\n\tpass\nor:\n\tpass";
Module module = parse(new StringInput("test", code));
Assert.AreEqual(normalize(expected), normalize(module.ToCodeString()));
}
[Test]
public void Property()
{
string code = "class Foo:\nprop as int:\nget: return 10\nend\nend\nend";
string expected = "class Foo:\n\n\tprop as int:\n\t\tget:\n\t\t\treturn 10";
Module module = parse(new StringInput("test", code));
Assert.AreEqual(normalize(expected), normalize(module.ToCodeString()));
}
[Test]
public void WithComment()
{
string code = "def foo():# comment\nend";
string expected = "def foo():\n\tpass";
Module module = parse(new StringInput("test", code));
Assert.AreEqual(normalize(expected), normalize(module.ToCodeString()));
}
[Test]
public void DocStrings()
{
string code = "def foo():\n\"\"\" docu \"\"\"\nend";
Module module = parse(new StringInput("test", code));
foreach (TypeMember member in module.Members)
Assert.AreEqual(member.Documentation, " docu ");
}
private void AssertInputName(string inputName, Node module)
{
Assert.AreEqual(inputName, module.LexicalInfo.FileName);
}
string normalize(string s)
{
return s.Trim().Replace("\r\n", "\n");
}
Module parse(string code)
{
StringInput input = new StringInput("code", code);
return parse(input);
}
Module parse(StringInput input)
{
CompilerPipeline pipeline = new CompilerPipeline();
pipeline.Add(new WSABooParsingStep());
BooCompiler compiler = new BooCompiler();
compiler.Parameters.Pipeline = pipeline;
compiler.Parameters.Input.Add(input);
CompilerContext result = compiler.Run();
Assert.AreEqual(0, result.Errors.Count, result.Errors.ToString());
Assert.AreEqual(1, result.CompileUnit.Modules.Count);
return result.CompileUnit.Modules[0];
}
}
}
| |
//Copyright 2014 Spin Services Limited
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using SS.Integration.Adapter.MarketRules.Interfaces;
using SS.Integration.Adapter.Model;
using SS.Integration.Adapter.Model.Interfaces;
namespace SS.Integration.Adapter.MarketRules.Model
{
[Serializable]
internal class MarketState : IUpdatableMarketState
{
protected internal readonly Dictionary<string, IUpdatableSelectionState> _selectionStates;
private Dictionary<string, string> _tags;
/// <summary>
/// DO NOT USE it's for copying object purpose only!
/// </summary>
public MarketState()
{
_selectionStates = new Dictionary<string, IUpdatableSelectionState>();
_tags = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
}
internal MarketState(string Id)
: this()
{
this.Id = Id;
}
public MarketState(Market market, bool fullSnapshot)
: this(market.Id)
{
IsRollingMarket = market is RollingMarket;
this.Update(market, fullSnapshot);
}
#region IMarketState
public string Id { get; private set; }
public string Name { get { return GetTagValue("name"); } }
public bool IsActive
{
get
{
return _selectionStates.Any(s => s.Value.Status == SelectionStatus.Active);
}
}
public bool IsSuspended
{
get
{
return _selectionStates.Where(s => s.Value.Status == SelectionStatus.Active && s.Value.Tradability.HasValue).All(s => !s.Value.Tradability.Value);
}
}
public bool IsPending
{
get
{
return _selectionStates.All(s => s.Value.Status == SelectionStatus.Pending);
}
}
public bool IsResulted
{
get
{
return Selections.All(x => x.Status == SelectionStatus.Settled || x.Status == SelectionStatus.Void);
}
}
public bool IsVoided
{
get
{
return Selections.All(x => x.Status == SelectionStatus.Void);
}
}
public bool IsTradedInPlay { get; set; }
public bool HasBeenActive { get; set; }
public bool HasBeenProcessed { get; set; }
public bool IsForcedSuspended { get; private set; }
public bool IsRollingMarket { get; private set; }
public double? Line { get; set; }
public bool IsDeleted { get; set; }
public int Index { get; set; }
#region Tags
public IEnumerable<string> TagKeys
{
get
{
return _tags.Keys;
}
}
public bool HasTag(string tagKey)
{
return _tags.ContainsKey(tagKey);
}
public string GetTagValue(string tagKey)
{
return !string.IsNullOrEmpty(tagKey) && _tags.ContainsKey(tagKey.ToLower()) ? _tags[tagKey.ToLower()] : null;
}
public bool IsTagValueMatch(string tagKey, string value) => IsTagValueMatch(tagKey, value, false);
public bool IsTagValueMatch(string tagKey, string value, bool caseSensitive) =>
!string.IsNullOrEmpty(tagKey)
&& !string.IsNullOrEmpty(value)
&& value.Equals(GetTagValue(tagKey), caseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase);
public int TagsCount
{
get { return _tags.Count; }
}
#endregion
#region Selections
public IEnumerable<ISelectionState> Selections
{
get { return _selectionStates.Values; }
}
public ISelectionState this[string selectionId]
{
get
{
return !HasSelection(selectionId) ? null : _selectionStates[selectionId];
}
}
public bool HasSelection(string selectionId)
{
return _selectionStates.ContainsKey(selectionId);
}
public int SelectionsCount
{
get { return _selectionStates.Count; }
}
#endregion
public bool IsEqualTo(IMarketState marketState)
{
if (marketState == null)
throw new ArgumentNullException("marketState");
if (ReferenceEquals(this, marketState))
return true;
if (marketState.Id != this.Id)
throw new Exception("Cannot compare two markets with different Ids");
if (marketState.Name != this.Name)
return false;
var isStatusEqual = this.IsPending == marketState.IsPending &&
this.IsResulted == marketState.IsResulted &&
this.IsSuspended == marketState.IsSuspended &&
this.IsActive == marketState.IsActive &&
this.IsDeleted == marketState.IsDeleted &&
this.IsForcedSuspended == marketState.IsForcedSuspended &&
this.IsVoided == marketState.IsVoided;
if (isStatusEqual)
{
if (this.HasTag("line") && marketState.HasTag("line"))
{
isStatusEqual = string.Equals(this.GetTagValue("line"), marketState.GetTagValue("line"));
}
if (IsRollingMarket)
{
isStatusEqual &= Line == marketState.Line;
}
isStatusEqual = isStatusEqual && marketState.Selections.All(s => _selectionStates.ContainsKey(s.Id) && _selectionStates[s.Id].IsEqualTo(s));
}
return isStatusEqual;
}
public bool IsEquivalentTo(Market market, bool checkTags, bool checkSelections)
{
if (market == null)
return false;
if (market.Id != Id)
return false;
if(checkTags)
{
if (market.TagsCount != TagsCount)
return false;
if (market.TagKeys.Any(tag => !HasTag(tag) || GetTagValue(tag) != market.GetTagValue(tag)))
return false;
}
if (checkSelections)
{
if (Selections.Count() != market.Selections.Count())
return false;
foreach (var seln in market.Selections)
{
ISelectionState seln_state = this[seln.Id];
if (seln_state == null)
return false;
if (!seln_state.IsEquivalentTo(seln, checkTags))
return false;
}
}
var result = IsSuspended == market.IsSuspended &&
IsActive == market.IsActive &&
IsResulted == market.IsResulted &&
IsPending == market.IsPending &&
IsVoided == market.IsVoided;
if (IsRollingMarket)
result &= Line == ((RollingMarket)market).Line;
// the only case we really should pay attention
// is when we have forced the suspension
// when the market was active
if(IsForcedSuspended)
result &= market.IsSuspended;
return result;
}
#endregion
#region IUpdatableMarketState
public void Update(Market market, bool fullSnapshot)
{
MergeSelectionStates(market, fullSnapshot);
if (fullSnapshot)
{
_tags = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
foreach (var key in market.TagKeys)
_tags.Add(key, market.GetTagValue(key, false));
if (market.HasTag("traded_in_play"))
IsTradedInPlay = market.IsTagValueMatch("traded_in_play", "true", false, false);
}
// always set to false at each update
IsForcedSuspended = false;
market.IsPending = IsPending;
market.IsActive = IsActive;
market.IsResulted = IsResulted;
market.IsSuspended = IsSuspended;
market.IsTradedInPlay = IsTradedInPlay;
market.IsVoided = IsVoided;
UpdateLineOnRollingHandicap(market);
}
public IUpdatableMarketState Clone()
{
MarketState clone = new MarketState
{
Id = this.Id,
HasBeenActive = this.HasBeenActive,
HasBeenProcessed = this.HasBeenProcessed,
IsTradedInPlay = this.IsTradedInPlay,
IsRollingMarket = this.IsRollingMarket,
IsDeleted = this.IsDeleted,
Line = this.Line,
Index = this.Index,
IsForcedSuspended = this.IsForcedSuspended
};
foreach(var key in this.TagKeys)
clone._tags.Add(key, this.GetTagValue(key));
foreach (var seln in this._selectionStates.Values)
clone._selectionStates.Add(seln.Id, seln.Clone());
return clone;
}
public void SetForcedSuspensionState(bool isSuspended = true)
{
IsForcedSuspended = isSuspended;
}
public void CommitChanges()
{
if(!HasBeenActive && IsActive)
HasBeenActive = true;
}
public void ApplyPostRulesProcessing()
{
HasBeenProcessed = true;
}
#endregion
private void UpdateLineOnRollingHandicap(Market market)
{
var rollingHandicap = market as RollingMarket;
if (rollingHandicap == null)
return;
var oneLine = _selectionStates.Values.All(s => s.Line == _selectionStates.Values.First().Line);
if (oneLine)
rollingHandicap.Line = rollingHandicap.Selections.First().Line;
else
{
var selectionWithHomeTeam =
_selectionStates.Values.FirstOrDefault(s => s.HasTag("team") && s.GetTagValue("team") == "1");
if (selectionWithHomeTeam == null)
throw new ArgumentException(string.Format("Rolling handicap line for market {0} can't be verified", market));
var homeSelection = rollingHandicap.Selections.FirstOrDefault(s => s.Id == selectionWithHomeTeam.Id);
//during update we may not receive an update for all selections
if (homeSelection != null)
{
rollingHandicap.Line = homeSelection.Line;
}
else
{
var selectionWithAwayTeam =
_selectionStates.Values.FirstOrDefault(s => s.HasTag("team") && s.GetTagValue("team") == "2");
// invert the line
rollingHandicap.Line = selectionWithAwayTeam.Line * (-1);
}
}
this.Line = rollingHandicap.Line;
}
private void MergeSelectionStates(Market market, bool fullSnapshot)
{
if (market.Selections == null)
return;
foreach (var selection in market.Selections)
{
if (_selectionStates.ContainsKey(selection.Id))
_selectionStates[selection.Id].Update(selection, fullSnapshot);
else
{
_selectionStates[selection.Id] = new SelectionState(selection, fullSnapshot);
}
}
}
public override string ToString()
{
return string.Format("Market marketId={0} marketName={1}", Id, Name);
}
}
}
| |
// 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.WebSites
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for WebSiteManagementClient.
/// </summary>
public static partial class WebSiteManagementClientExtensions
{
/// <summary>
/// Gets publishing user
/// </summary>
/// <remarks>
/// Gets publishing user
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static User GetPublishingUser(this IWebSiteManagementClient operations)
{
return operations.GetPublishingUserAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets publishing user
/// </summary>
/// <remarks>
/// Gets publishing user
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<User> GetPublishingUserAsync(this IWebSiteManagementClient operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetPublishingUserWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates publishing user
/// </summary>
/// <remarks>
/// Updates publishing user
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='userDetails'>
/// Details of publishing user
/// </param>
public static User UpdatePublishingUser(this IWebSiteManagementClient operations, User userDetails)
{
return operations.UpdatePublishingUserAsync(userDetails).GetAwaiter().GetResult();
}
/// <summary>
/// Updates publishing user
/// </summary>
/// <remarks>
/// Updates publishing user
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='userDetails'>
/// Details of publishing user
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<User> UpdatePublishingUserAsync(this IWebSiteManagementClient operations, User userDetails, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdatePublishingUserWithHttpMessagesAsync(userDetails, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the source controls available for Azure websites.
/// </summary>
/// <remarks>
/// Gets the source controls available for Azure websites.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<SourceControl> ListSourceControls(this IWebSiteManagementClient operations)
{
return operations.ListSourceControlsAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the source controls available for Azure websites.
/// </summary>
/// <remarks>
/// Gets the source controls available for Azure websites.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SourceControl>> ListSourceControlsAsync(this IWebSiteManagementClient operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListSourceControlsWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates source control token
/// </summary>
/// <remarks>
/// Updates source control token
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='sourceControlType'>
/// Type of source control
/// </param>
/// <param name='requestMessage'>
/// Source control token information
/// </param>
public static SourceControl UpdateSourceControl(this IWebSiteManagementClient operations, string sourceControlType, SourceControl requestMessage)
{
return operations.UpdateSourceControlAsync(sourceControlType, requestMessage).GetAwaiter().GetResult();
}
/// <summary>
/// Updates source control token
/// </summary>
/// <remarks>
/// Updates source control token
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='sourceControlType'>
/// Type of source control
/// </param>
/// <param name='requestMessage'>
/// Source control token information
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SourceControl> UpdateSourceControlAsync(this IWebSiteManagementClient operations, string sourceControlType, SourceControl requestMessage, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateSourceControlWithHttpMessagesAsync(sourceControlType, requestMessage, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Check if a resource name is available.
/// </summary>
/// <remarks>
/// Check if a resource name is available.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// Resource name to verify.
/// </param>
/// <param name='type'>
/// Resource type used for verification. Possible values include: 'Site',
/// 'Slot', 'HostingEnvironment'
/// </param>
/// <param name='isFqdn'>
/// Is fully qualified domain name.
/// </param>
public static ResourceNameAvailability CheckNameAvailability(this IWebSiteManagementClient operations, string name, string type, bool? isFqdn = default(bool?))
{
return operations.CheckNameAvailabilityAsync(name, type, isFqdn).GetAwaiter().GetResult();
}
/// <summary>
/// Check if a resource name is available.
/// </summary>
/// <remarks>
/// Check if a resource name is available.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// Resource name to verify.
/// </param>
/// <param name='type'>
/// Resource type used for verification. Possible values include: 'Site',
/// 'Slot', 'HostingEnvironment'
/// </param>
/// <param name='isFqdn'>
/// Is fully qualified domain name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ResourceNameAvailability> CheckNameAvailabilityAsync(this IWebSiteManagementClient operations, string name, string type, bool? isFqdn = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CheckNameAvailabilityWithHttpMessagesAsync(name, type, isFqdn, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get a list of available geographical regions.
/// </summary>
/// <remarks>
/// Get a list of available geographical regions.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='sku'>
/// Name of SKU used to filter the regions. Possible values include: 'Free',
/// 'Shared', 'Basic', 'Standard', 'Premium', 'Dynamic', 'Isolated'
/// </param>
/// <param name='linuxWorkersEnabled'>
/// Specify <code>true</code> if you want to filter to only regions
/// that support Linux workers.
/// </param>
public static IPage<GeoRegion> ListGeoRegions(this IWebSiteManagementClient operations, string sku = default(string), bool? linuxWorkersEnabled = default(bool?))
{
return operations.ListGeoRegionsAsync(sku, linuxWorkersEnabled).GetAwaiter().GetResult();
}
/// <summary>
/// Get a list of available geographical regions.
/// </summary>
/// <remarks>
/// Get a list of available geographical regions.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='sku'>
/// Name of SKU used to filter the regions. Possible values include: 'Free',
/// 'Shared', 'Basic', 'Standard', 'Premium', 'Dynamic', 'Isolated'
/// </param>
/// <param name='linuxWorkersEnabled'>
/// Specify <code>true</code> if you want to filter to only regions
/// that support Linux workers.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<GeoRegion>> ListGeoRegionsAsync(this IWebSiteManagementClient operations, string sku = default(string), bool? linuxWorkersEnabled = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListGeoRegionsWithHttpMessagesAsync(sku, linuxWorkersEnabled, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List all premier add-on offers.
/// </summary>
/// <remarks>
/// List all premier add-on offers.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<PremierAddOnOffer> ListPremierAddOnOffers(this IWebSiteManagementClient operations)
{
return operations.ListPremierAddOnOffersAsync().GetAwaiter().GetResult();
}
/// <summary>
/// List all premier add-on offers.
/// </summary>
/// <remarks>
/// List all premier add-on offers.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<PremierAddOnOffer>> ListPremierAddOnOffersAsync(this IWebSiteManagementClient operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListPremierAddOnOffersWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List all SKUs.
/// </summary>
/// <remarks>
/// List all SKUs.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static SkuInfos ListSkus(this IWebSiteManagementClient operations)
{
return operations.ListSkusAsync().GetAwaiter().GetResult();
}
/// <summary>
/// List all SKUs.
/// </summary>
/// <remarks>
/// List all SKUs.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SkuInfos> ListSkusAsync(this IWebSiteManagementClient operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListSkusWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Verifies if this VNET is compatible with an App Service Environment.
/// </summary>
/// <remarks>
/// Verifies if this VNET is compatible with an App Service Environment by
/// analyzing the Network Security Group rules.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='parameters'>
/// VNET information
/// </param>
public static VnetValidationFailureDetails VerifyHostingEnvironmentVnet(this IWebSiteManagementClient operations, VnetParameters parameters)
{
return operations.VerifyHostingEnvironmentVnetAsync(parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Verifies if this VNET is compatible with an App Service Environment.
/// </summary>
/// <remarks>
/// Verifies if this VNET is compatible with an App Service Environment by
/// analyzing the Network Security Group rules.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='parameters'>
/// VNET information
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VnetValidationFailureDetails> VerifyHostingEnvironmentVnetAsync(this IWebSiteManagementClient operations, VnetParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.VerifyHostingEnvironmentVnetWithHttpMessagesAsync(parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Move resources between resource groups.
/// </summary>
/// <remarks>
/// Move resources between resource groups.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='moveResourceEnvelope'>
/// Object that represents the resource to move.
/// </param>
public static void Move(this IWebSiteManagementClient operations, string resourceGroupName, CsmMoveResourceEnvelope moveResourceEnvelope)
{
operations.MoveAsync(resourceGroupName, moveResourceEnvelope).GetAwaiter().GetResult();
}
/// <summary>
/// Move resources between resource groups.
/// </summary>
/// <remarks>
/// Move resources between resource groups.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='moveResourceEnvelope'>
/// Object that represents the resource to move.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task MoveAsync(this IWebSiteManagementClient operations, string resourceGroupName, CsmMoveResourceEnvelope moveResourceEnvelope, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.MoveWithHttpMessagesAsync(resourceGroupName, moveResourceEnvelope, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Validate if a resource can be created.
/// </summary>
/// <remarks>
/// Validate if a resource can be created.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='validateRequest'>
/// Request with the resources to validate.
/// </param>
public static ValidateResponse Validate(this IWebSiteManagementClient operations, string resourceGroupName, ValidateRequest validateRequest)
{
return operations.ValidateAsync(resourceGroupName, validateRequest).GetAwaiter().GetResult();
}
/// <summary>
/// Validate if a resource can be created.
/// </summary>
/// <remarks>
/// Validate if a resource can be created.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='validateRequest'>
/// Request with the resources to validate.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ValidateResponse> ValidateAsync(this IWebSiteManagementClient operations, string resourceGroupName, ValidateRequest validateRequest, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ValidateWithHttpMessagesAsync(resourceGroupName, validateRequest, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Validate whether a resource can be moved.
/// </summary>
/// <remarks>
/// Validate whether a resource can be moved.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='moveResourceEnvelope'>
/// Object that represents the resource to move.
/// </param>
public static void ValidateMove(this IWebSiteManagementClient operations, string resourceGroupName, CsmMoveResourceEnvelope moveResourceEnvelope)
{
operations.ValidateMoveAsync(resourceGroupName, moveResourceEnvelope).GetAwaiter().GetResult();
}
/// <summary>
/// Validate whether a resource can be moved.
/// </summary>
/// <remarks>
/// Validate whether a resource can be moved.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='moveResourceEnvelope'>
/// Object that represents the resource to move.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ValidateMoveAsync(this IWebSiteManagementClient operations, string resourceGroupName, CsmMoveResourceEnvelope moveResourceEnvelope, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.ValidateMoveWithHttpMessagesAsync(resourceGroupName, moveResourceEnvelope, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the source controls available for Azure websites.
/// </summary>
/// <remarks>
/// Gets the source controls available for Azure websites.
/// </remarks>
/// <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<SourceControl> ListSourceControlsNext(this IWebSiteManagementClient operations, string nextPageLink)
{
return operations.ListSourceControlsNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the source controls available for Azure websites.
/// </summary>
/// <remarks>
/// Gets the source controls available for Azure websites.
/// </remarks>
/// <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<SourceControl>> ListSourceControlsNextAsync(this IWebSiteManagementClient operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListSourceControlsNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get a list of available geographical regions.
/// </summary>
/// <remarks>
/// Get a list of available geographical regions.
/// </remarks>
/// <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<GeoRegion> ListGeoRegionsNext(this IWebSiteManagementClient operations, string nextPageLink)
{
return operations.ListGeoRegionsNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Get a list of available geographical regions.
/// </summary>
/// <remarks>
/// Get a list of available geographical regions.
/// </remarks>
/// <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<GeoRegion>> ListGeoRegionsNextAsync(this IWebSiteManagementClient operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListGeoRegionsNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List all premier add-on offers.
/// </summary>
/// <remarks>
/// List all premier add-on offers.
/// </remarks>
/// <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<PremierAddOnOffer> ListPremierAddOnOffersNext(this IWebSiteManagementClient operations, string nextPageLink)
{
return operations.ListPremierAddOnOffersNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// List all premier add-on offers.
/// </summary>
/// <remarks>
/// List all premier add-on offers.
/// </remarks>
/// <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<PremierAddOnOffer>> ListPremierAddOnOffersNextAsync(this IWebSiteManagementClient operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListPremierAddOnOffersNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
#region License Header
/*
* QUANTLER.COM - Quant Fund Development Platform
* Quantler Core Trading Engine. Copyright 2018 Quantler B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion License Header
using NLog;
using Quantler.Account;
using Quantler.Account.Cash;
using Quantler.Broker;
using Quantler.Broker.Model;
using Quantler.Data;
using Quantler.Interfaces;
using Quantler.Orders;
using Quantler.Trades;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using Quantler.Configuration;
namespace Quantler.Brokers.Simulated
{
/// <summary>
/// A simulated broker class for Quantler. Processes orders and fills them against external
/// tick feed. (live or historical)
/// </summary>
[Export(typeof(BrokerConnection))]
public class SimBroker : SimBrokerConnection
{
#region Private Fields
/// <summary>
/// The currently active orders
/// </summary>
private readonly ConcurrentDictionary<long, PendingOrder> _activeOrders = new ConcurrentDictionary<long, PendingOrder>();
/// <summary>
/// Thread locking
/// </summary>
private readonly object _locker = new object();
/// <summary>
/// Current instance logging
/// </summary>
private readonly ILogger _log = LogManager.GetCurrentClassLogger();
/// <summary>
/// The portfolio manager under test
/// </summary>
private IPortfolio _portfolio;
/// <summary>
/// Keeps track for if we need to use highly liquid fills
/// </summary>
private bool _usehighlyliquidfills;
#endregion Private Fields
#region Public Events
/// <summary>
/// Occurs when [account balance change].
/// </summary>
public event EventHandler<AccountAction> BalanceChange;
/// <summary>
/// Occurs when [order state change].
/// </summary>
public event EventHandler<OrderTicketEvent> OrderStateChange;
#endregion Public Events
#region Public Properties
/// <summary>
/// Gets the broker model.
/// </summary>
public BrokerModel BrokerModel => _portfolio.BrokerModel;
/// <summary>
/// Gets the type of the broker.
/// </summary>
public BrokerType BrokerType => BrokerModel.BrokerType;
/// <summary>
/// Gets a value indicating whether this instance is connected.
/// </summary>
/// <value>
/// <c>true</c> if this instance is connected; otherwise, <c>false</c>.
/// </value>
public bool IsConnected => true;
/// <summary>
/// Gets a value indicating whether this instance is ready.
/// </summary>
/// <value>
/// <c>true</c> if this instance is ready; otherwise, <c>false</c>.
/// </value>
public bool IsReady => true;
/// <summary>
/// Gets the latency in ms.
/// </summary>
public int LatencyInMS => 0;
/// <summary>
/// Gets a value indicating whether this is a live feed with live updates.
/// </summary>
/// <value>
/// <c>true</c> if [live feed]; otherwise, <c>false</c>.
/// </value>
public bool LiveFeed => true;
#endregion Public Properties
#region Public Methods
/// <summary>
/// Cancels the order.
/// </summary>
/// <param name="order">The order.</param>
/// <returns></returns>
public bool CancelOrder(PendingOrder order)
{
//Check if we can remove this order
if (!_activeOrders.TryRemove(order.OrderId, out PendingOrder active))
return false; //Cannot find order
//Send cancelled order notification
OrderStateChange?.Invoke(this, OrderTicketEvent.Cancelled(order.OrderId, "Order was cancelled"));
return true;
}
/// <summary>
/// Connects this instance.
/// </summary>
public void Connect()
{
//Not needed
}
/// <summary>
/// Disconnects this instance.
/// </summary>
public void Disconnect()
{
//Not needed
}
/// <summary>
/// Gets the account funds currently known.
/// </summary>
/// <returns></returns>
public IReadOnlyList<CashPosition> GetAccountFunds() =>
_portfolio.CashManager.GetCashPositions().Values.ToList();
/// <summary>
/// Gets the currently active orders.
/// </summary>
/// <returns></returns>
public IReadOnlyList<PendingOrder> GetActiveOrders() =>
_activeOrders.Values.ToList();
/// <summary>
/// Gets the position overview.
/// </summary>
/// <returns></returns>
public IReadOnlyList<Position> GetPositionOverview() =>
_portfolio.BrokerAccount.Positions.ToList();
/// <summary>
/// Initializes this instance.
/// </summary>
public void Initialize()
{
_log.Info($"Initializing sim broker");
_usehighlyliquidfills = Config.SimulationConfig.HighlyLiquidFills;
}
/// <summary>
/// Processes the market data.
/// </summary>
/// <param name="dataupdates">The data updates.</param>
public void ProcessMarketData(DataUpdates dataupdates)
{
//Only accept market data
if (_activeOrders.Count == 0)
return;
//Check if we have any data
if (!dataupdates.HasUpdates)
return;
lock (_locker)
{
foreach (var pkv in _activeOrders.OrderBy(x => x.Key))
{
//get the order
var pendingorder = pkv.Value;
var order = pendingorder.Order;
//Get datapoint
if (!dataupdates[order.Security].HasUpdates)
continue;
var datapoint = dataupdates[order.Security].Ticks.Count > 0
? dataupdates[order.Security].Ticks.First().Value.First() as DataPoint
: dataupdates[order.Security].QuoteBars.Count > 0
? dataupdates[order.Security].QuoteBars.First().Value as DataPoint
: dataupdates[order.Security].TradeBars.Count > 0
? dataupdates[order.Security].TradeBars.First().Value as DataPoint
: null;
if (datapoint == null)
continue;
//Check if order is already done
if (order.State.IsDone())
{
_activeOrders.TryRemove(pkv.Key, out pendingorder);
continue;
}
//Check if we have enough buying power
if (!_portfolio.OrderTicketHandler.GetSufficientCapitalForOrder(pendingorder))
{
//Remove order from active orders, as it is cancelled by the broker instance
_activeOrders.TryRemove(pkv.Key, out pendingorder);
_portfolio.Log(LogLevel.Error, $"Insufficient funds to process order by sim broker");
OrderStateChange?.Invoke(this, OrderTicketEvent.Cancelled(pendingorder.OrderId, "Insufficient funds to process order by sim broker"));
}
//Check if we need to fill this order
var fillmodel = BrokerModel.GetFillModel(order);
Fill filledresult = Fill.NoFill();
try
{
filledresult = fillmodel.FillOrder(BrokerModel, datapoint, pendingorder, _usehighlyliquidfills);
}
catch (Exception exc)
{
_log.Error(exc);
_portfolio.Log(LogLevel.Error, string.Format("Order Error: id: {0}, Transaction model failed to fill for order type: {1} with error: {2}", order.InternalId, order.Type, exc.Message));
OrderStateChange?.Invoke(this, OrderTicketEvent.Cancelled(pendingorder.OrderId, "Exception during processing fill for this order, please check logs"));
}
//Check for any full or partial fills
if (filledresult.FillQuantity > 0)
{
if (filledresult.Status == OrderState.Filled)
OrderStateChange?.Invoke(this, OrderTicketEvent.Filled(order.InternalId, filledresult));
else if (filledresult.Status == OrderState.PartialFilled)
OrderStateChange?.Invoke(this, OrderTicketEvent.PartiallyFilled(order.InternalId, filledresult));
}
//Check if order is done
if (filledresult.Status.IsDone())
_activeOrders.TryRemove(pkv.Key, out pendingorder);
}
}
}
/// <summary>
/// Sets the broker model.
/// </summary>
/// <param name="portfolio">The Portfolio Manager.</param>
public void SetPortfolio(IPortfolio portfolio) =>
_portfolio = portfolio;
/// <summary>
/// Submits the order.
/// </summary>
/// <param name="pendingorder">The order.</param>
/// <returns></returns>
public bool SubmitOrder(PendingOrder pendingorder)
{
//get the underlying order
var order = pendingorder.Order;
//Check current order state
if (order.State == OrderState.New)
{
//Set order
lock (_locker)
{
_activeOrders[pendingorder.OrderId] = pendingorder;
}
//Check order id
if (order.BrokerId.Contains(order.InternalId.ToString()))
order.BrokerId.Add(order.InternalId.ToString());
//Order event
OrderStateChange?.Invoke(this, OrderTicketEvent.Submitted(order.InternalId));
return true;
}
return false;
}
/// <summary>
/// Tests the connection latency between the current instance and the broker.
/// </summary>
public void TestLatency()
{
//Not Applicable
}
/// <summary>
/// Updates the order.
/// </summary>
/// <param name="pendingorder">The order.</param>
/// <returns></returns>
public bool UpdateOrder(PendingOrder pendingorder)
{
//Check if we can find this order
if (!_activeOrders.TryGetValue(pendingorder.OrderId, out PendingOrder active))
return false; //Cannot find order
lock (_locker)
{
//Update order instance
pendingorder.UpdateOrder(active.Order);
}
//Send updated order notification
OrderStateChange?.Invoke(this, OrderTicketEvent.Updated(active.OrderId, "Order was updated"));
return true;
}
#endregion Public Methods
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace SnapCall
{
using System.IO;
public class Evaluator
{
private bool debug;
private HashMap handRankMap;
private Dictionary<ulong, ulong> monteCarloMap;
const float loadfactor = 1.25f;
string fileName = null;
public Evaluator(
string filePathToLoadFrom = null,
bool fiveCard = true,
bool sixCard = true,
bool sevenCard = true,
double loadFactor = loadfactor,
bool debug = true,
bool runCustom = false)
{
DateTime start = DateTime.UtcNow;
this.debug = debug;
if (sixCard && !fiveCard) throw new ArgumentException("Six card eval requires five card eval");
if (sevenCard && !sixCard) throw new ArgumentException("Seven card eval requires six card eval");
// Load hand rank table or create one if no filename was given
if (filePathToLoadFrom != null)
{
fileName = filePathToLoadFrom;
LoadFromFile(filePathToLoadFrom);
return;
}
int minHashMapSize = (fiveCard ? 2598960 : 0) + (sixCard ? 20358520 : 0) + (sevenCard ? 133784560 : 0);
handRankMap = new HashMap((uint)(minHashMapSize * loadFactor));
if (fiveCard)
{
if (debug) Console.WriteLine("Generating new five card lookup table");
GenerateFiveCardTable();
}
if (sixCard)
{
if (debug) Console.WriteLine("Generating new six card lookup table");
GenerateSixCardTable();
}
if (sevenCard)
{
if (debug) Console.WriteLine("Generating new seven card lookup table");
GenerateSevenCardTable();
}
// Run custom scripts like monte carlo generation
if (runCustom)
{
Console.WriteLine("Running monte carlo simulation");
GenerateMonteCarloMap(100000);
Console.WriteLine("Writing table to disk");
SaveToFile(filePathToLoadFrom);
}
TimeSpan elapsed = DateTime.UtcNow - start;
if (debug) Console.WriteLine("Hand evaluator setup completed in {0:0.00}s", elapsed.TotalSeconds);
}
public HashMap HandRankMap => this.handRankMap;
public int Evaluate(ulong bitmap)
{
// Check if 2-card monte carlo map has an evaluation for this hand
//if (monteCarloMap.ContainsKey(bitmap)) return (int)monteCarloMap[bitmap];
// Otherwise return the real evaluation
if (handRankMap == null)
Reload();
return (int)handRankMap[bitmap];
}
public void SaveToFile(string fileName)
{
if (debug) Console.WriteLine("Saving table to {0}", fileName);
using (var file = File.Create(fileName))
{
ProtoBuf.Serializer.Serialize(file, handRankMap);
}
if (debug) Console.WriteLine("Done Saving!");
}
public void Unload()
{
handRankMap = null;
GC.Collect();
}
public void Reload()
{
if (handRankMap != null)
return;
LoadFromFile(fileName);
}
private void LoadFromFile(string path)
{
if (!string.IsNullOrWhiteSpace(path) && !File.Exists(path))
{
throw new ArgumentException(string.Format("File {0} does not exist", path));
}
else
{
if (debug) Console.WriteLine("Loading table from {0}", path);
using (FileStream fs = new FileStream(path, FileMode.Open))
{
handRankMap = HashMap.Deserialize(fs);
}
}
}
private void GenerateFiveCardTable()
{
var sourceSet = Enumerable.Range(0, 52).ToList();
var combinations = new Combinatorics.Collections.Combinations<int>(sourceSet, 5);
// Generate all possible 5 card hand bitmaps
Console.WriteLine("Generating bitmaps");
var handBitmaps = new List<ulong>();
int count = 0;
foreach (List<int> values in combinations)
{
if (debug && count++ % 1000 == 0) Console.Write("{0} / {1}\r", count, combinations.Count);
handBitmaps.Add(values.Aggregate(0ul, (acc, el) => acc | (1ul << el)));
}
// Calculate hand strength of each hand
Console.WriteLine("Calculating hand strength");
var handStrengths = new Dictionary<ulong, HandStrength>();
count = 0;
foreach (ulong bitmap in handBitmaps)
{
if (debug && count++ % 1000 == 0) Console.Write("{0} / {1}\r", count, handBitmaps.Count);
var hand = new Hand(bitmap);
handStrengths.Add(bitmap, hand.GetStrength());
}
// Generate a list of all unique hand strengths
Console.WriteLine("Generating equivalence classes");
var uniqueHandStrengths = new List<HandStrength>();
count = 0;
foreach (KeyValuePair<ulong, HandStrength> strength in handStrengths)
{
if (debug && count++ % 1000 == 0) Console.Write("{0} / {1}\r", count, handStrengths.Count);
Utilities.BinaryInsert<HandStrength>(uniqueHandStrengths, strength.Value);
}
Console.WriteLine("{0} unique hand strengths", uniqueHandStrengths.Count);
// Create a map of hand bitmaps to hand strength indices
Console.WriteLine("Creating lookup table");
count = 0;
foreach (ulong bitmap in handBitmaps)
{
if (debug && count++ % 1000 == 0) Console.Write("{0} / {1}\r", count, handBitmaps.Count);
var hand = new Hand(bitmap);
HandStrength strength = hand.GetStrength();
var equivalence = Utilities.BinarySearch<HandStrength>(uniqueHandStrengths, strength);
if (equivalence == null) throw new Exception(string.Format("{0} hand not found", hand));
else
{
handRankMap[bitmap] = (ulong)equivalence;
}
}
}
private void GenerateSixCardTable()
{
var sourceSet = Enumerable.Range(0, 52).ToList();
var combinations = new Combinatorics.Collections.Combinations<int>(sourceSet, 6);
int count = 0;
foreach (List<int> cards in combinations)
{
if (debug && count++ % 1000 == 0) Console.Write("{0} / {1}\r", count, combinations.Count);
var subsets = new Combinatorics.Collections.Combinations<int>(cards, 5);
var subsetValues = new List<ulong>();
foreach (List<int> subset in subsets)
{
ulong subsetBitmap = subset.Aggregate(0ul, (acc, el) => acc | (1ul << el));
subsetValues.Add(handRankMap[subsetBitmap]);
}
ulong bitmap = cards.Aggregate(0ul, (acc, el) => acc | (1ul << el));
handRankMap[bitmap] = subsetValues.Max();
}
}
private void GenerateSevenCardTable()
{
var sourceSet = Enumerable.Range(0, 52).ToList();
var combinations = new Combinatorics.Collections.Combinations<int>(sourceSet, 7);
int count = 0;
foreach (List<int> cards in combinations)
{
if (debug && count++ % 1000 == 0) Console.Write("{0} / {1}\r", count, combinations.Count);
var subsets = new Combinatorics.Collections.Combinations<int>(cards, 6);
var subsetValues = new List<ulong>();
foreach (List<int> subset in subsets)
{
ulong subsetBitmap = subset.Aggregate(0ul, (acc, el) => acc | (1ul << el));
subsetValues.Add(handRankMap[subsetBitmap]);
}
ulong bitmap = cards.Aggregate(0ul, (acc, el) => acc | (1ul << el));
handRankMap[bitmap] = subsetValues.Max();
}
}
private void GenerateMonteCarloMap(int iterations)
{
monteCarloMap = new Dictionary<ulong, ulong>();
var sourceSet = Enumerable.Range(1, 52).ToList();
var combinations = new Combinatorics.Collections.Combinations<int>(sourceSet, 2);
int count = 0;
foreach (List<int> cards in combinations)
{
Console.Write("{0}\r", count++);
ulong bitmap = cards.Aggregate(0ul, (acc, el) => acc | (1ul << el));
var hand = new Hand(bitmap);
var deck = new Deck(removedCards: bitmap);
ulong evaluationSum = 0;
for (int i = 0; i < iterations; i++)
{
if (deck.CardsRemaining < 13) deck.Shuffle();
evaluationSum += handRankMap[bitmap | deck.Draw(5)];
}
monteCarloMap[bitmap] = evaluationSum / (ulong)iterations;
}
foreach (KeyValuePair<ulong, ulong> kvp in monteCarloMap.OrderBy(kvp => kvp.Value))
{
var hand = new Hand(kvp.Key);
hand.PrintColoredCards("\t");
Console.WriteLine(kvp.Value);
handRankMap[kvp.Key] = kvp.Value;
}
Console.ReadLine();
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Linq;
using System.Collections.Generic;
using System.Web;
using Adxstudio.Xrm.Cms;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Diagnostics;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Portal.Web;
using Microsoft.Xrm.Portal.Web.Providers;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Adxstudio.Xrm.AspNet.Cms;
using Adxstudio.Xrm.Cms.SolutionVersions;
namespace Adxstudio.Xrm.Web.Providers
{
public class ContentMapEntityUrlProvider : AdxEntityUrlProvider, IContentMapEntityUrlProvider
{
private readonly IContentMapProvider _contentMapProvider;
internal ContentMapEntityUrlProvider(IEntityWebsiteProvider websiteProvider, IContentMapProvider contentMapProvider, string portalName = null)
: base(websiteProvider)
{
_contentMapProvider = contentMapProvider;
PortalName = portalName;
}
protected new string PortalName { get; private set; }
public override ApplicationPath GetApplicationPath(OrganizationServiceContext context, Entity entity)
{
return _contentMapProvider.Using(map => GetApplicationPath(context, entity, map));
}
/// <summary>
/// This method is created to wrap GetApplicationPath and prepend language code to link if required
/// </summary>
private ApplicationPath GetApplicationPath(OrganizationServiceContext context, Entity entity, ContentMap map)
{
var path = GetApplicationPathBase(context, entity, map);
if (path == null || !ContextLanguageInfo.DisplayLanguageCodeInUrl)
{
return path;
}
switch (entity.LogicalName)
{
case "adx_weblink":
case "adx_webpage":
return ContextLanguageInfo.PrependLanguageCode(path);
}
return path;
}
private ApplicationPath GetApplicationPathBase(OrganizationServiceContext context, Entity entity, ContentMap map)
{
ApplicationPath result = null;
switch (entity.LogicalName)
{
case "adx_weblink":
result = GetApplicationPath(map, entity);
//no need to continue as it will return null from the base call at this point.
return result;
case "adx_webpage":
return GetApplicationPath(map, entity);
case "adx_webfile":
result = GetApplicationPath(map, entity);
break;
case "adx_shortcut":
result = GetApplicationPath(map, entity);
break;
case "adx_blog":
result = GetApplicationPath(map, entity, "adx_partialurl", "adx_parentpageid", true, true);
break;
case "adx_communityforum":
result = GetApplicationPath(map, entity, "adx_partialurl", "adx_parentpageid", prependLangCode: true);
break;
case "adx_event":
result = GetApplicationPath(map, entity, "adx_partialurl", "adx_parentpageid");
break;
case "annotation":
result = entity.GetFileAttachmentPath();
break;
}
return result ?? base.GetApplicationPath(context, entity);
}
private ApplicationPath GetApplicationPath(ContentMap map, Entity entity)
{
EntityNode node;
if (map.TryGetValue(entity, out node))
{
return GetApplicationPath(map, node);
}
return null;
}
public virtual string GetUrl(ContentMap map, EntityNode node)
{
var applicationPath = GetApplicationPath(map, node);
if (applicationPath != null)
{
return applicationPath.ExternalUrl ?? applicationPath.AbsolutePath;
}
return null;
}
public virtual ApplicationPath GetApplicationPath(ContentMap map, EntityNode node)
{
var link = node as WebLinkNode;
if (link != null)
{
if (!string.IsNullOrWhiteSpace(link.ExternalUrl))
{
return ApplicationPath.FromExternalUrl(link.ExternalUrl);
}
ApplicationPath path = null;
// Check .IsReference incase the linked-to root WebPage is deactivated.
if (link.WebPage != null && !link.WebPage.IsReference)
{
// If language content page exists, replace web link page with the content page
var langInfo = HttpContext.Current.GetContextLanguageInfo();
var linkWebPage = langInfo.FindLanguageSpecificWebPageNode(link.WebPage, false);
// If web page doesn't exist for current language, return null path
if (linkWebPage != null)
{
path = GetApplicationPath(linkWebPage);
}
}
return path;
}
var page = node as WebPageNode;
if (page != null)
{
var path = GetApplicationPath(page);
return path;
}
var file = node as WebFileNode;
if (file != null)
{
var path = GetApplicationPath(file);
return path;
}
var shortcut = node as ShortcutNode;
if (shortcut != null)
{
var path = GetApplicationPath(shortcut);
return path;
}
return null;
}
private ApplicationPath GetApplicationPath(ContentMap map, Entity entity, string partialUrlAttribute, string parentReferenceAttribute, bool trailingSlash = false, bool prependLangCode = false)
{
var partialUrl = entity.GetAttributeValue<string>(partialUrlAttribute);
if (string.IsNullOrEmpty(partialUrl))
{
return null;
}
var parentReference = entity.GetAttributeValue<EntityReference>(parentReferenceAttribute);
if (parentReference == null)
{
return null;
}
EntityNode parentNode;
if (!map.TryGetValue(parentReference, out parentNode))
{
return null;
}
var parentPath = GetApplicationPath(map, parentNode);
if (parentPath == null || parentPath.PartialPath == null)
{
return null;
}
partialUrl = trailingSlash && !partialUrl.EndsWith("/") ? partialUrl + "/" : partialUrl;
var parentPartialPath = parentPath.PartialPath.EndsWith("/") ? parentPath.PartialPath : parentPath.PartialPath + "/";
var resultAppPath = ApplicationPath.FromPartialPath(parentPartialPath + partialUrl);
if (ContextLanguageInfo.DisplayLanguageCodeInUrl
&& ContextLanguageInfo.IsCrmMultiLanguageEnabledInWebsite(PortalContext.Current.Website)
&& prependLangCode)
{
resultAppPath = ContextLanguageInfo.PrependLanguageCode(resultAppPath);
}
return resultAppPath;
}
protected virtual string GetUrl(WebPageNode page)
{
var applicationPath = GetApplicationPath(page);
if (applicationPath != null)
{
return applicationPath.ExternalUrl ?? applicationPath.AbsolutePath;
}
return null;
}
protected virtual string GetUrl(WebFileNode file)
{
var applicationPath = GetApplicationPath(file);
if (applicationPath != null)
{
return applicationPath.ExternalUrl ?? applicationPath.AbsolutePath;
}
return null;
}
protected virtual string GetUrl(ShortcutNode shortcut)
{
var applicationPath = GetApplicationPath(shortcut);
if (applicationPath != null)
{
return applicationPath.ExternalUrl ?? applicationPath.AbsolutePath;
}
return null;
}
private ApplicationPath GetApplicationPath(WebPageNode page)
{
var websiteRelativeUrl = InternalGetApplicationPath(page);
if (websiteRelativeUrl == null) return null;
var path = websiteRelativeUrl.PartialPath;
var appPath = ApplicationPath.FromPartialPath(path);
if (appPath.ExternalUrl != null) return appPath;
var canonicalPath = appPath.AppRelativePath.EndsWith("/")
? appPath
: ApplicationPath.FromAppRelativePath("{0}/".FormatWith(appPath.AppRelativePath));
return canonicalPath;
}
private ApplicationPath InternalGetApplicationPath(WebPageNode page)
{
var parent = page.Parent;
var partialUrl = page.PartialUrl;
var url = ApplicationPath.FromPartialPath(string.Empty);
if (parent == null || parent.IsReference)
{
// Home page (with partial url "/") are not expected to have a parent page.
if (partialUrl == "/")
{
return ApplicationPath.FromPartialPath(partialUrl);
}
var traceMessage = parent == null ? string.Format("Parent is Null. Page.Id = {0}", page.Id) : string.Format("Parent is Reference. Page.Id = {0}, ParentId = {1}", page.Id, parent.Id);
ADXTrace.Instance.TraceWarning(TraceCategory.Application, traceMessage);
return null;
}
Version currentVersion = page.Website.CurrentBaseSolutionCrmVersion;
Version centaurusVersion = BaseSolutionVersions.CentaurusVersion;
if (currentVersion.Major >= centaurusVersion.Major && currentVersion.Minor >= centaurusVersion.Minor)
{
url = InternalJoinApplicationPath(parent, partialUrl);
}
else
{
if (CircularReferenceCheck(page) == true)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Circular reference with page {0}", page.Id));
return url;
}
else
{
url = InternalJoinApplicationPath(parent, partialUrl);
}
}
return url;
}
/// <summary>
/// Returns application path url by joining the partial url and partial path of parent url.
/// </summary>
/// <param name="parent">Contains Parent page of Webpage node.</param>
/// <param name="partialUrl">Contains partial url of Webpage node.</param>
private ApplicationPath InternalJoinApplicationPath(WebPageNode parent, string partialUrl)
{
var applicationPathUrl = ApplicationPath.FromPartialPath(string.Empty);
var parentUrl = InternalGetApplicationPath(parent);
if (parentUrl == null)
{
ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("Parent is Null. PartialUrl = {0}", partialUrl));
return null;
}
applicationPathUrl = JoinApplicationPath(parentUrl.PartialPath, partialUrl);
return applicationPathUrl;
}
/// <summary>
/// Checks for the circular reference over web pages.
/// </summary>
/// <param name="page">Webpage node to check for circular reference.</param>
private bool? CircularReferenceCheck(WebPageNode page)
{
var pageDetails = new Dictionary<Guid, string>();
if (page.IsCircularReference == null)
{
while (page.Parent != null)
{
if (pageDetails.ContainsKey(page.Id) && page.Id != Guid.Empty)
{
page.IsCircularReference = true;
return true;
}
else
{
pageDetails.Add(page.Id, page.Name);
}
page = page.Parent;
}
page.IsCircularReference = false;
}
return page.IsCircularReference;
}
private ApplicationPath GetApplicationPath(WebFileNode file)
{
var websiteRelativeUrl = InternalGetApplicationPath(file);
var path = websiteRelativeUrl.PartialPath;
var appPath = ApplicationPath.FromPartialPath(path);
return appPath;
}
private ApplicationPath InternalGetApplicationPath(WebFileNode file)
{
var partialUrl = file.PartialUrl;
if (file.Parent != null)
{
var parentUrl = InternalGetApplicationPath(file.Parent);
if (parentUrl == null)
{
return null;
}
return JoinApplicationPath(parentUrl.PartialPath, partialUrl);
}
if (file.BlogPost != null)
{
var serviceContext = PortalCrmConfigurationManager.CreateServiceContext(PortalName);
var blogPost = serviceContext.CreateQuery("adx_blogpost")
.FirstOrDefault(e => e.GetAttributeValue<Guid>("adx_blogpostid") == file.BlogPost.Id);
if (blogPost == null)
{
return null;
}
var parentUrl = GetApplicationPath(serviceContext, blogPost);
if (parentUrl == null)
{
return null;
}
return JoinApplicationPath(parentUrl.PartialPath, partialUrl);
}
return ApplicationPath.FromPartialPath(partialUrl);
}
private ApplicationPath GetApplicationPath(ShortcutNode shortcut)
{
if (shortcut.WebPage != null && !shortcut.WebPage.IsReference)
{
return GetApplicationPath(shortcut.WebPage);
}
if (shortcut.WebFile != null && !shortcut.WebFile.IsReference)
{
return GetApplicationPath(shortcut.WebFile);
}
if (!string.IsNullOrEmpty(shortcut.ExternalUrl))
{
return ApplicationPath.FromExternalUrl(shortcut.ExternalUrl);
}
return null;
}
private new ApplicationPath JoinApplicationPath(string basePath, string extendedPath)
{
if (string.IsNullOrWhiteSpace(basePath) || basePath.Contains("?") || basePath.Contains(":") || basePath.Contains("//") || basePath.Contains("&")
|| basePath.Contains("%3f") || basePath.Contains("%2f%2f") || basePath.Contains("%26"))
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "The basePath is invalid.");
return null;
}
if (string.IsNullOrWhiteSpace(extendedPath) || extendedPath.Contains("?") || extendedPath.Contains("&") || extendedPath.Contains("//")
|| extendedPath.Contains(":") || extendedPath.Contains("%3f") || extendedPath.Contains("%2f%2f") || extendedPath.Contains("%26"))
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "The extendedPath is invalid.");
return null;
}
var path = "{0}/{1}".FormatWith(basePath.TrimEnd('/'), extendedPath.TrimStart('/'));
return ApplicationPath.FromPartialPath(path);
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Model;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests.ConfigDataInfo;
namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests
{
[TestClass]
public class BVTTest : ServiceManagementTest
{
private string serviceName;
[TestInitialize]
public void Initialize()
{
serviceName = Utilities.GetUniqueShortName(serviceNamePrefix);
pass = false;
testStartTime = DateTime.Now;
}
/// <summary>
/// BVT test for IaaS cmdlets.
/// </summary>
[TestMethod(), TestCategory(Category.BVT), TestCategory(Category.Scenario), TestProperty("Feature", "IaaS"), Priority(1), Owner("hylee"), Description("BVT Test for IaaS")]
public void AzureIaaSBVT()
{
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
DateTime prevTime = DateTime.Now;
string diskLabel1 = "disk1";
int diskSize1 = 30;
int lunSlot1 = 0;
string diskLabel2 = "disk2";
int diskSize2 = 50;
int lunSlot2 = 2;
string ep1Name = "tcp1";
int ep1LocalPort = 60010;
int ep1PublicPort = 60011;
string ep1LBSetName = "lbset1";
int ep1ProbePort = 60012;
string ep1ProbePath = string.Empty;
int? ep1ProbeInterval = 7;
int? ep1ProbeTimeout = null;
NetworkAclObject ep1AclObj = vmPowershellCmdlets.NewAzureAclConfig();
bool ep1DirectServerReturn = false;
string ep2Name = "tcp2";
int ep2LocalPort = 60020;
int ep2PublicPort = 60021;
int ep2LocalPortChanged = 60030;
int ep2PublicPortChanged = 60031;
string ep2LBSetName = "lbset2";
int ep2ProbePort = 60022;
string ep2ProbePath = @"/";
int? ep2ProbeInterval = null;
int? ep2ProbeTimeout = 32;
NetworkAclObject ep2AclObj = vmPowershellCmdlets.NewAzureAclConfig();
bool ep2DirectServerReturn = false;
string cerFileName = "testcert.cer";
string thumbprintAlgorithm = "sha1";
try
{
// Create a certificate
X509Certificate2 certCreated = Utilities.CreateCertificate(password);
byte[] certData2 = certCreated.Export(X509ContentType.Cert);
File.WriteAllBytes(cerFileName, certData2);
// Install the .cer file to local machine.
StoreLocation certStoreLocation = StoreLocation.CurrentUser;
StoreName certStoreName = StoreName.My;
X509Certificate2 installedCert = Utilities.InstallCert(cerFileName, certStoreLocation, certStoreName);
PSObject certToUpload = vmPowershellCmdlets.RunPSScript(
String.Format("Get-Item cert:\\{0}\\{1}\\{2}", certStoreLocation.ToString(), certStoreName.ToString(), installedCert.Thumbprint))[0];
string certData = Convert.ToBase64String(((X509Certificate2)certToUpload.BaseObject).RawData);
string newAzureVMName = Utilities.GetUniqueShortName(vmNamePrefix);
imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false, 50);
RecordTimeTaken(ref prevTime);
//
// New-AzureService and verify with Get-AzureService
//
vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName);
Assert.IsTrue(Verify.AzureService(serviceName, serviceName, locationName));
RecordTimeTaken(ref prevTime);
//
// Add-AzureCertificate and verify with Get-AzureCertificate
//
vmPowershellCmdlets.AddAzureCertificate(serviceName, certToUpload);
Assert.IsTrue(Verify.AzureCertificate(serviceName, certCreated.Thumbprint, thumbprintAlgorithm, certData));
RecordTimeTaken(ref prevTime);
//
// Remove-AzureCertificate
//
vmPowershellCmdlets.RemoveAzureCertificate(serviceName, certCreated.Thumbprint, thumbprintAlgorithm);
Assert.IsTrue(Utilities.CheckRemove(vmPowershellCmdlets.GetAzureCertificate, serviceName, certCreated.Thumbprint, thumbprintAlgorithm));
RecordTimeTaken(ref prevTime);
//
// New-AzureVMConfig
//
var azureVMConfigInfo = new AzureVMConfigInfo(newAzureVMName, InstanceSize.Small.ToString(), imageName);
PersistentVM vm = vmPowershellCmdlets.NewAzureVMConfig(azureVMConfigInfo);
RecordTimeTaken(ref prevTime);
//
// Add-AzureCertificate
//
vmPowershellCmdlets.AddAzureCertificate(serviceName, certToUpload);
//
// New-AzureCertificateSetting
//
CertificateSettingList certList = new CertificateSettingList();
certList.Add(vmPowershellCmdlets.NewAzureCertificateSetting(certStoreName.ToString(), installedCert.Thumbprint));
RecordTimeTaken(ref prevTime);
//
// Add-AzureProvisioningConfig
//
AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, certList, username, password);
azureProvisioningConfig.Vm = vm;
vm = vmPowershellCmdlets.AddAzureProvisioningConfig(azureProvisioningConfig);
RecordTimeTaken(ref prevTime);
//
// Add-AzureDataDisk (two disks)
//
AddAzureDataDiskConfig azureDataDiskConfigInfo1 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, diskSize1, diskLabel1, lunSlot1);
azureDataDiskConfigInfo1.Vm = vm;
vm = vmPowershellCmdlets.AddAzureDataDisk(azureDataDiskConfigInfo1);
AddAzureDataDiskConfig azureDataDiskConfigInfo2 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, diskSize2, diskLabel2, lunSlot2);
azureDataDiskConfigInfo2.Vm = vm;
vm = vmPowershellCmdlets.AddAzureDataDisk(azureDataDiskConfigInfo2);
RecordTimeTaken(ref prevTime);
//
// Add-AzureEndpoint (two endpoints)
//
AzureEndPointConfigInfo azureEndPointConfigInfo1 = new AzureEndPointConfigInfo(
AzureEndPointConfigInfo.ParameterSet.CustomProbe,
ProtocolInfo.tcp,
ep1LocalPort,
ep1PublicPort,
ep1Name,
ep1LBSetName,
ep1ProbePort,
ProtocolInfo.tcp,
ep1ProbePath,
ep1ProbeInterval,
ep1ProbeTimeout,
ep1AclObj,
ep1DirectServerReturn,
null,
null,
LoadBalancerDistribution.SourceIP);
azureEndPointConfigInfo1.Vm = vm;
vm = vmPowershellCmdlets.AddAzureEndPoint(azureEndPointConfigInfo1);
AzureEndPointConfigInfo azureEndPointConfigInfo2 = new AzureEndPointConfigInfo(
AzureEndPointConfigInfo.ParameterSet.CustomProbe,
ProtocolInfo.tcp,
ep2LocalPort,
ep2PublicPort,
ep2Name,
ep2LBSetName,
ep2ProbePort,
ProtocolInfo.http,
ep2ProbePath,
ep2ProbeInterval,
ep2ProbeTimeout,
ep2AclObj,
ep2DirectServerReturn);
azureEndPointConfigInfo2.Vm = vm;
vm = vmPowershellCmdlets.AddAzureEndPoint(azureEndPointConfigInfo2);
RecordTimeTaken(ref prevTime);
//
// Set-AzureAvailabilitySet
//
string testAVSetName = "testAVSet1";
vm = vmPowershellCmdlets.SetAzureAvailabilitySet(testAVSetName, vm);
RecordTimeTaken(ref prevTime);
//
// Set-AzureOSDisk
//
vm = vmPowershellCmdlets.SetAzureOSDisk(null, vm, 100);
//
// New-AzureDns
//
string dnsName = "OpenDns1";
string ipAddress = "208.67.222.222";
DnsServer dns = vmPowershellCmdlets.NewAzureDns(dnsName, ipAddress);
RecordTimeTaken(ref prevTime);
//
// New-AzureVM
//
vmPowershellCmdlets.NewAzureVM(serviceName, new[] { vm }, null, new[] { dns }, null, null, null, null);
RecordTimeTaken(ref prevTime);
//
// Get-AzureVM without any parameter (List VMs)
//
var vmlist = vmPowershellCmdlets.GetAzureVM();
Console.WriteLine("The number of VMs: {0}", vmlist.Count);
Assert.AreNotSame(0, vmlist.Count, "No VM exists!!!");
PersistentVMRoleListContext returnedVMlist =
vmlist.First(item => item.ServiceName.Equals(serviceName) && item.Name.Equals(newAzureVMName));
Assert.IsNotNull(returnedVMlist, "Created VM does not exist!!!");
Utilities.PrintContext((PersistentVMRoleContext) returnedVMlist);
//
// Get-AzureVM
//
PersistentVMRoleContext returnedVM = vmPowershellCmdlets.GetAzureVM(newAzureVMName, serviceName);
vm = returnedVM.VM;
RecordTimeTaken(ref prevTime);
//
// Verify AzureDataDisk
//
Assert.IsTrue(Verify.AzureDataDisk(vm, diskLabel1, diskSize1, lunSlot1, HostCaching.None), "Data disk is not properly added");
Assert.IsTrue(Verify.AzureDataDisk(vm, diskLabel2, diskSize2, lunSlot2, HostCaching.None), "Data disk is not properly added");
Console.WriteLine("Data disk added correctly.");
RecordTimeTaken(ref prevTime);
//
// Verify AzureEndpoint
//
Assert.IsTrue(Verify.AzureEndpoint(vm, new[]{azureEndPointConfigInfo1, azureEndPointConfigInfo2}));
//
// Verify RDP & PowerShell Endpoints
//
var endpoints = vmPowershellCmdlets.GetAzureEndPoint(vm);
Assert.IsTrue(endpoints.Count(e => e.Name == "PowerShell" && e.LocalPort == 5986 && e.Protocol == "tcp") == 1);
Assert.IsTrue(endpoints.Count(e => e.Name == "RemoteDesktop" && e.LocalPort == 3389 && e.Protocol == "tcp") == 1);
//
// Verify DebugSettings
//
Assert.IsTrue(vm.DebugSettings.BootDiagnosticsEnabled);
//
// Verify AzureDns
//
Assert.IsTrue(Verify.AzureDns(vmPowershellCmdlets.GetAzureDeployment(serviceName).DnsSettings, dns));
//
// Verify AzureAvailibilitySet
//
Assert.IsTrue(Verify.AzureAvailabilitySet(vm, testAVSetName));
//
// Verify AzureOsDisk
//
Assert.IsTrue(Verify.AzureOsDisk(vm, "Windows", HostCaching.ReadWrite));
//
// Set-AzureDataDisk
//
SetAzureDataDiskConfig setAzureDataDiskConfigInfo = new SetAzureDataDiskConfig(HostCaching.ReadOnly, lunSlot1);
setAzureDataDiskConfigInfo.Vm = vm;
vm = vmPowershellCmdlets.SetAzureDataDisk(setAzureDataDiskConfigInfo);
RecordTimeTaken(ref prevTime);
//
// Remove-AzureDataDisk
//
RemoveAzureDataDiskConfig removeAzureDataDiskConfig = new RemoveAzureDataDiskConfig(lunSlot2, vm);
vm = vmPowershellCmdlets.RemoveAzureDataDisk(removeAzureDataDiskConfig);
RecordTimeTaken(ref prevTime);
//
// Set-AzureEndpoint
//
azureEndPointConfigInfo2 = new AzureEndPointConfigInfo(
AzureEndPointConfigInfo.ParameterSet.CustomProbe,
ProtocolInfo.tcp,
ep2LocalPortChanged,
ep2PublicPortChanged,
ep2Name,
ep2LBSetName,
ep2ProbePort,
ProtocolInfo.http,
ep2ProbePath,
ep2ProbeInterval,
ep2ProbeTimeout,
ep2AclObj,
ep2DirectServerReturn);
azureEndPointConfigInfo2.Vm = vm;
vm = vmPowershellCmdlets.SetAzureEndPoint(azureEndPointConfigInfo2);
RecordTimeTaken(ref prevTime);
//
// Remove-AzureEndpoint
//
vm = vmPowershellCmdlets.RemoveAzureEndPoint(azureEndPointConfigInfo1.EndpointName, vm);
RecordTimeTaken(ref prevTime);
//
// Set-AzureVMSize
//
var vmSizeConfig = new SetAzureVMSizeConfig(InstanceSize.Medium.ToString());
vmSizeConfig.Vm = vm;
vm = vmPowershellCmdlets.SetAzureVMSize(vmSizeConfig);
RecordTimeTaken(ref prevTime);
//
// Set-AzureOSDisk
//
vm = vmPowershellCmdlets.SetAzureOSDisk(HostCaching.ReadOnly, vm);
//
// Update-AzureVM
//
vmPowershellCmdlets.UpdateAzureVM(newAzureVMName, serviceName, vm);
RecordTimeTaken(ref prevTime);
//
// Get-AzureVM and Verify the VM
//
vm = vmPowershellCmdlets.GetAzureVM(newAzureVMName, serviceName).VM;
// Verify setting data disk
Assert.IsTrue(Verify.AzureDataDisk(vm, diskLabel1, diskSize1, lunSlot1, HostCaching.ReadOnly), "Data disk is not properly added");
// Verify removing a data disk
Assert.AreEqual(1, vmPowershellCmdlets.GetAzureDataDisk(vm).Count, "DataDisk is not removed.");
// Verify setting an endpoint
Assert.IsTrue(Verify.AzureEndpoint(vm, new[]{azureEndPointConfigInfo2}));
// Verify removing an endpoint
Assert.IsFalse(Verify.AzureEndpoint(vm, new[] { azureEndPointConfigInfo1 }));
// Verify os disk
Assert.IsTrue(Verify.AzureOsDisk(vm, "Windows", HostCaching.ReadOnly));
//
// Remove-AzureVM
//
vmPowershellCmdlets.RemoveAzureVM(newAzureVMName, serviceName, false, true);
Assert.AreNotEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureVMName, serviceName));
vmPowershellCmdlets.RemoveAzureVM(newAzureVMName, serviceName);
RecordTimeTaken(ref prevTime);
Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureVMName, serviceName));
pass = true;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
throw;
}
}
[TestCleanup]
public virtual void CleanUp()
{
Console.WriteLine("Test {0}", pass ? "passed" : "failed");
// Remove the service
if ((cleanupIfPassed && pass) || (cleanupIfFailed && !pass))
{
try
{
vmPowershellCmdlets.RemoveAzureService(serviceName);
}
catch (Exception e)
{
Console.WriteLine("Error occurred while deleting service: {0}", e.ToString());
}
try
{
vmPowershellCmdlets.GetAzureService(serviceName);
Console.WriteLine("The service, {0}, is not removed", serviceName);
}
catch (Exception e)
{
if (e.ToString().ToLowerInvariant().Contains("does not exist"))
{
Console.WriteLine("The service, {0}, is successfully removed", serviceName);
}
else
{
Console.WriteLine("Error occurred: {0}", e.ToString());
}
}
}
}
private void RecordTimeTaken(ref DateTime prev)
{
var period = DateTime.Now - prev;
Console.WriteLine("{0} seconds and {1} ms passed...", period.Seconds.ToString(), period.Milliseconds.ToString());
prev = DateTime.Now;
}
}
}
| |
<?cs
def:fullpage() ?>
<div id="body-content">
<?cs /def ?>
<?cs
def:sdk_nav() ?>
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav" class="scroll-pane">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<?cs
include:"../../../../frameworks/base/docs/html/sdk/sdk_toc.cs" ?>
</div>
</div> <!-- end side-nav -->
<?cs /def ?>
<?cs
def:resources_tab_nav() ?>
<div class="wrap clearfix" id="body-content">
<a
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav" class="scroll-pane">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<?cs
include:"../../../../frameworks/base/docs/html/resources/resources_toc.cs" ?>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs
def:tools_nav() ?>
<div class="wrap clearfix" id="body-content">
<div class="col-3" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav" class="scroll-pane">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<?cs
include:"../../../../frameworks/base/docs/html/tools/tools_toc.cs" ?>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs
def:training_nav() ?>
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav" class="scroll-pane">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<?cs
include:"../../../../frameworks/base/docs/html/training/training_toc.cs" ?>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs
def:guide_nav() ?>
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav" class="scroll-pane">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<?cs
include:"../../../../frameworks/base/docs/html/guide/guide_toc.cs" ?>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs
def:design_nav() ?>
<div class="wrap clearfix" id="body-content">
<div class="col-3" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav" class="scroll-pane">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<?cs
include:"../../../../frameworks/base/docs/html/design/design_toc.cs" ?>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs
def:distribute_nav() ?>
<div class="wrap clearfix" id="body-content">
<div class="col-3" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav" class="scroll-pane">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<?cs
include:"../../../../frameworks/base/docs/html/distribute/distribute_toc.cs" ?>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs
def:google_nav() ?>
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav" class="scroll-pane">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<?cs
include:"../../../../frameworks/base/docs/html/google/google_toc.cs" ?>
</div>
<script type="text/javascript">
showGoogleRefTree();
</script>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs
def:about_nav() ?>
<div class="wrap clearfix" id="body-content">
<div class="col-3" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav" class="scroll-pane">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<?cs
include:"../../../../frameworks/base/docs/html/about/about_toc.cs" ?>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs
def:dist_more_nav() ?>
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav" class="scroll-pane">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<?cs
include:"../../../../frameworks/base/docs/html/distribute/more/more_toc.cs" ?>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
:
<?cs /def ?>
<?cs # The default side navigation for the reference docs ?><?cs
def:default_left_nav() ?>
<?cs if:reference.gcm || reference.gms ?>
<?cs call:google_nav() ?>
<?cs else ?>
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<div id="api-nav-header">
<div id="api-level-toggle">
<label for="apiLevelCheckbox" class="disabled">API level: </label>
<div class="select-wrapper">
<select id="apiLevelSelector">
<!-- option elements added by buildApiLevelSelector() -->
</select>
</div>
</div><!-- end toggle -->
<div id="api-nav-title">Android APIs</div>
</div><!-- end nav header -->
<script>
var SINCE_DATA = [ <?cs
each:since = since ?>'<?cs
var:since.name ?>'<?cs
if:!last(since) ?>, <?cs /if ?><?cs
/each
?> ];
buildApiLevelSelector();
</script>
<div id="swapper">
<div id="nav-panels">
<div id="resize-packages-nav">
<div id="packages-nav" class="scroll-pane">
<ul>
<?cs call:package_link_list(docs.packages) ?>
</ul><br/>
</div> <!-- end packages-nav -->
</div> <!-- end resize-packages -->
<div id="classes-nav" class="scroll-pane">
<?cs
if:subcount(class.package) ?>
<ul>
<?cs call:list("Interfaces", class.package.interfaces) ?>
<?cs call:list("Classes", class.package.classes) ?>
<?cs call:list("Enums", class.package.enums) ?>
<?cs call:list("Exceptions", class.package.exceptions) ?>
<?cs call:list("Errors", class.package.errors) ?>
</ul><?cs
elif:subcount(package) ?>
<ul>
<?cs call:class_link_list("Interfaces", package.interfaces) ?>
<?cs call:class_link_list("Classes", package.classes) ?>
<?cs call:class_link_list("Enums", package.enums) ?>
<?cs call:class_link_list("Exceptions", package.exceptions) ?>
<?cs call:class_link_list("Errors", package.errors) ?>
</ul><?cs
else ?>
<p style="padding:10px">Select a package to view its members</p><?cs
/if ?><br/>
</div><!-- end classes -->
</div><!-- end nav-panels -->
<div id="nav-tree" style="display:none" class="scroll-pane">
<div id="tree-list"></div>
</div><!-- end nav-tree -->
</div><!-- end swapper -->
<div id="nav-swap">
<a class="fullscreen">fullscreen</a>
<a href='#' onclick='swapNav();return false;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>
</div>
</div> <!-- end devdoc-nav -->
</div> <!-- end side-nav -->
<script type="text/javascript">
// init fullscreen based on user pref
var fullscreen = readCookie("fullscreen");
if (fullscreen != 0) {
if (fullscreen == "false") {
toggleFullscreen(false);
} else {
toggleFullscreen(true);
}
}
// init nav version for mobile
if (isMobile) {
swapNav(); // tree view should be used on mobile
$('#nav-swap').hide();
} else {
chooseDefaultNav();
if ($("#nav-tree").is(':visible')) {
init_default_navtree("<?cs var:toroot ?>");
}
}
// scroll the selected page into view
$(document).ready(function() {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
});
</script>
<?cs /if ?>
<?cs
/def ?>
<?cs
def:custom_left_nav() ?><?cs
if:fullpage ?><?cs
call:fullpage() ?><?cs
elif:guide ?><?cs
call:guide_nav() ?><?cs
elif:design ?><?cs
call:design_nav() ?><?cs
elif:training ?><?cs
call:training_nav() ?><?cs
elif:tools ?><?cs
call:tools_nav() ?><?cs
elif:google ?><?cs
call:google_nav() ?><?cs
elif:more ?><?cs
call:dist_more_nav() ?><?cs
elif:distribute ?><?cs
call:distribute_nav() ?><?cs
elif:about ?><?cs
call:about_nav() ?><?cs
else ?><?cs
call:default_left_nav() ?> <?cs
/if ?><?cs
/def ?>
<?cs # appears at the bottom of every page ?><?cs
def:custom_cc_copyright() ?>
Except as noted, this content is
licensed under <a href="http://creativecommons.org/licenses/by/2.5/">
Creative Commons Attribution 2.5</a>. For details and
restrictions, see the <a href="<?cs var:toroot ?>license.html">Content
License</a>.<?cs
/def ?>
<?cs
def:custom_copyright() ?>
Except as noted, this content is licensed under <a
href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>.
For details and restrictions, see the <a href="<?cs var:toroot ?>license.html">
Content License</a>.<?cs
/def ?>
<?cs
def:custom_footerlinks() ?>
<p>
<a href="<?cs var:toroot ?>source/index.html">About Android</a> |
<a href="<?cs var:toroot ?>source/community.html">Community</a> |
<a href="<?cs var:toroot ?>legal.html">Legal</a> |
</p><?cs
/def ?>
<?cs # appears on the right side of the blue bar at the bottom off every page ?><?cs
def:custom_buildinfo() ?><?cs
if:!google && !reference.gms && !reference.gcm?>
Android <?cs var:sdk.version ?> r<?cs var:sdk.rel.id ?> — <?cs
/if ?>
<script src="<?cs var:toroot ?>timestamp.js" type="text/javascript"></script>
<script>document.write(BUILD_TIMESTAMP)</script>
<?cs /def ?>
<?cs #------------------- s.a.c specific templating ---------------------------?>
<?cs
def:sac_left_nav() ?>
<?cs if:devices ?>
<?cs call:devices_nav() ?>
<?cs elif:compatibility ?>
<?cs call:compatibility_nav() ?>
<?cs elif:source ?>
<?cs call:source_nav() ?>
<?cs elif:security ?>
<?cs call:security_nav() ?>
<?cs elif:reference ?>
<?cs call:default_left_nav() ?>
<?cs /if ?>
<?cs /def ?>
<?cs
def:devices_nav() ?>
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav" class="scroll-pane">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<?cs
include:"../../../../docs/source.android.com/src/devices/devices_toc.cs" ?>
</div>
<script type="text/javascript">
showTradefedRefTree();
</script>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs
def:compatibility_nav() ?>
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav" class="scroll-pane">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<?cs
include:"../../../../docs/source.android.com/src/compatibility/compatibility_toc.cs" ?>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs
def:source_nav() ?>
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav" class="scroll-pane">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<?cs
include:"../../../../docs/source.android.com/src/source/source_toc.cs" ?>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
<?cs
def:security_nav() ?>
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav" class="scroll-pane">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<?cs
include:"../../../../docs/source.android.com/src/security/security_toc.cs" ?>
</div>
</div> <!-- end side-nav -->
<script>
$(document).ready(function() {
scrollIntoView("devdoc-nav");
});
</script>
<?cs /def ?>
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.Xml.XPath;
using System.Data;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
namespace fyiReporting.Data
{
/// <summary>
/// Summary description for iTunesDataReader.
/// </summary>
public class iTunesDataReader : IDataReader
{
iTunesConnection _xconn;
iTunesCommand _xcmd;
System.Data.CommandBehavior _behavior;
// xpath
XPathDocument _xpd; // the document
XPathNavigator _xpn; // the navigator
XPathNodeIterator _xpni; // the main iterator
XmlNamespaceManager _nsmgr; // name space manager
ListDictionary _NameSpaces; // names spaces used in xml document
// column information
object[] _Data; // data values of the columns
static readonly string[] _Names = new string[] {
"Track_ID",
"Name",
"Artist",
"Composer",
"Album",
"Album Artist",
"Genre",
"Category",
"Kind",
"Size",
"Total_Time",
"Track_Number",
"Year",
"Date_Modified",
"Date_Added",
"Beats_Per_Minute",
"Bit_Rate",
"Sample_Rate",
"Comments",
"Skip_Count",
"Skip_Date",
"Artwork_Count",
"Persistent_ID",
"Track_Type",
"Location",
"File_Folder_Count",
"Library_Folder_Count",
"Has_Video",
"Movie",
"Play_Count",
"Play_Date",
"Play_Date_UTC",
"Disc_Number",
"Disc_Count",
"Compilation",
"Track_Count"
};
// types of all the columns
static readonly Type _dttype = DateTime.MinValue.GetType(); // work variable for getting the type
static readonly Type _stype = "".GetType();
static readonly Type _btype = true.GetType();
static readonly Type _itype = int.MaxValue.GetType();
static readonly Type _ltype = long.MaxValue.GetType();
static readonly Type _dtype = Double.MinValue.GetType();
static readonly Type[] _Types = new Type[]
{
/* "Track_ID" */ _itype,
/* Name */ _stype,
/* Artist */ _stype,
/* Composer */ _stype,
/* Album */ _stype,
/* Album Artist */ _stype,
/* Genre */ _stype,
/* Category */ _stype,
/* Kind */ _stype,
/* Size */ _itype,
/* Total_Time */ _itype,
/* Track_Number */ _itype,
/* Year */ _itype,
/* Date_Modified */ _dttype,
/* Date_Added */ _dttype,
/* Beats_Per_Minute */ _itype,
/* Bit_Rate */ _itype,
/* Sample_Rate */ _itype,
/* Comments */ _stype,
/* Skip_Count */ _itype,
/* Skip_Date */ _dttype,
/* Artwork_Count */ _itype,
/* Persistent_ID */ _stype,
/* Track_Type */ _stype,
/* Location */ _stype,
/* File_Folder_Count */ _itype,
/* Library_Folder_Count */ _itype,
/* Has_Video */ _btype,
/* Movie */ _btype,
/* Play_Count */ _itype,
/* Play_Date */ _ltype, /* Play_Date will overflow an integer */
/* Play_Date_UTC */ _dttype,
/* Disc_Number */ _itype,
/* Disc_Count */ _itype,
/* Compilation */ _btype,
/* Track_Count */ _itype
};
public iTunesDataReader(System.Data.CommandBehavior behavior, iTunesConnection conn, iTunesCommand cmd)
{
_xconn = conn;
_xcmd = cmd;
_behavior = behavior;
_Data = new object[_Names.Length]; // allocate enough room for data
if (behavior == CommandBehavior.SchemaOnly)
return;
// create an iterator to the selected rows
_xpd = new XPathDocument(_xconn.File);
_xpn = _xpd.CreateNavigator();
_xpni = _xpn.Select("/plist/dict"); // select the rows
_NameSpaces = new ListDictionary();
// Now determine the actual structure of the row depending on the command
switch (_xcmd.Table)
{
case "Tracks":
default:
_xpni = GetTracksColumns();
break;
}
if (_NameSpaces.Count > 0)
{
_nsmgr = new XmlNamespaceManager(new NameTable());
foreach (string nsprefix in _NameSpaces.Keys)
{
_nsmgr.AddNamespace(nsprefix, _NameSpaces[nsprefix] as string); // setup namespaces
}
}
else
_nsmgr = null;
}
XPathNodeIterator GetTracksColumns()
{
/* this routine figures out based on first row in file; the problem is not
* all rows contain all the fields. Now fields are hard coded.
XPathNodeIterator ti = PositionToTracks();
while (ti.MoveNext())
{
if (ti.Current.Name != "key")
continue;
if (AddName(ti.Current.Value)) // when duplicate we've gone too far
break;
ti.MoveNext();
Type t;
switch (ti.Current.Name)
{
case "integer":
t = long.MaxValue.GetType();
break;
case "string":
t = string.Empty.GetType();
break;
case "real":
t = Double.MaxValue.GetType();
break;
case "true":
case "false":
t = true.GetType();
break;
case "date":
t = DateTime.MaxValue.GetType();
break;
default:
t = string.Empty.GetType();
break;
}
_Types.Add(t);
}
_Names.TrimExcess(); // no longer need extra space
*/
return PositionToTracks(); // return iterator to first row
}
XPathNodeIterator PositionToTracks()
{
//go to the first row to get info
XPathNodeIterator temp_xpni = _xpni.Clone(); // temporary iterator for determining columns
temp_xpni.MoveNext();
XPathNodeIterator ni = temp_xpni.Current.Select("*");
while (ni.MoveNext())
{
if (ni.Current.Name != "key")
continue;
if (ni.Current.Value == "Tracks")
{
ni.MoveNext();
if (ni.Current.Name != "dict") // next item should be "dict"
break;
string sel = "dict/*";
XPathNodeIterator ti = ni.Current.Select(sel);
return ti;
}
}
return null;
}
// adds name to array; return true when duplicate
//bool AddName(string name)
//{
// string wname = name.Replace(' ', '_');
// if (_Names.ContainsKey(wname))
// return true;
// _Names.Add(wname, _Names.Count);
// return false;
//}
#region IDataReader Members
public int RecordsAffected
{
get
{
return 0;
}
}
public bool IsClosed
{
get
{
return _xconn.IsOpen;
}
}
public bool NextResult()
{
return false;
}
public void Close()
{
_xpd = null;
_xpn = null;
_xpni = null;
_Data = null;
}
public bool Read()
{
if (_xpni == null)
return false;
XPathNodeIterator ti = _xpni;
Hashtable ht = new Hashtable(_Names.Length);
// clear out previous values; previous row might have values this row doesn't
for (int i = 0; i < _Data.Length; i++)
_Data[i] = null;
XPathNodeIterator save_ti = ti.Clone();
bool rc = false;
while (ti.MoveNext())
{
if (ti.Current.Name != "key")
continue;
string name = ti.Current.Value.Replace(' ', '_');
// we only know we're on the next row when a column repeats
if (ht.Contains(name))
{
break;
}
ht.Add(name, name);
int ix;
try
{
ix = this.GetOrdinal(name);
rc = true; // we know we got at least one column value
}
catch // this isn't a know column; skip it
{
ti.MoveNext();
save_ti = ti.Clone();
continue; // but keep trying
}
ti.MoveNext();
save_ti = ti.Clone();
try
{
switch (ti.Current.Name)
{
case "integer":
if (_Names[ix] == "Play_Date") // will overflow a long
_Data[ix] = ti.Current.ValueAsLong;
else
_Data[ix] = ti.Current.ValueAsInt;
break;
case "string":
_Data[ix] = ti.Current.Value;
break;
case "real":
_Data[ix] = ti.Current.ValueAsDouble;
break;
case "true":
_Data[ix] = true;
break;
case "false":
_Data[ix] = false;
break;
case "date":
_Data[ix] = ti.Current.ValueAsDateTime;
break;
default:
_Data[ix] = ti.Current.Value;
break;
}
}
catch { _Data[ix] = null; }
}
_xpni = save_ti;
return rc;
}
public int Depth
{
get
{
// TODO: Add XmlDataReader.Depth getter implementation
return 0;
}
}
public DataTable GetSchemaTable()
{
// TODO: Add XmlDataReader.GetSchemaTable implementation
return null;
}
#endregion
#region IDisposable Members
public void Dispose()
{
this.Close();
}
#endregion
#region IDataRecord Members
public int GetInt32(int i)
{
return Convert.ToInt32(_Data[i]);
}
public object this[string name]
{
get
{
int ci = this.GetOrdinal(name);
return _Data[ci];
}
}
object System.Data.IDataRecord.this[int i]
{
get
{
return _Data[i];
}
}
public object GetValue(int i)
{
return _Data[i];
}
public bool IsDBNull(int i)
{
return _Data[i] == null;
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException("GetBytes not implemented.");
}
public byte GetByte(int i)
{
return Convert.ToByte(_Data[i]);
}
public Type GetFieldType(int i)
{
return _Types[i];
}
public decimal GetDecimal(int i)
{
return Convert.ToDecimal(_Data[i]);
}
public int GetValues(object[] values)
{
int i;
for (i=0; i < values.Length; i++)
{
values[i] = i >= _Data.Length? System.DBNull.Value: _Data[i];
}
return Math.Min(values.Length, _Data.Length);
}
public string GetName(int i)
{
return _Names[i];
}
public int FieldCount
{
get
{
return _Data.Length;
}
}
public long GetInt64(int i)
{
return Convert.ToInt64(_Data[i]);
}
public double GetDouble(int i)
{
return Convert.ToDouble(_Data[i]);
}
public bool GetBoolean(int i)
{
return Convert.ToBoolean(_Data[i]);
}
public Guid GetGuid(int i)
{
throw new NotImplementedException("GetGuid not implemented.");
}
public DateTime GetDateTime(int i)
{
return Convert.ToDateTime(_Data[i]);
}
public int GetOrdinal(string name)
{
// do case sensitive lookup
int ci = 0;
foreach (string cname in _Names)
{
if (cname == name)
return ci;
ci++;
}
// do case insensitive lookup
ci=0;
foreach (string cname in _Names)
{
if (string.Compare(cname, name, true) == 0)
return ci;
ci++;
}
throw new ArgumentException(string.Format("Column '{0}' not known.", name));
}
public string GetDataTypeName(int i)
{
Type t = _Types[i] as Type;
return t.ToString();
}
public float GetFloat(int i)
{
return Convert.ToSingle(_Data[i]);
}
public IDataReader GetData(int i)
{
throw new NotImplementedException("GetData not implemented.");
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException("GetChars not implemented.");
}
public string GetString(int i)
{
return Convert.ToString(_Data[i]);
}
public char GetChar(int i)
{
return Convert.ToChar(_Data[i]);
}
public short GetInt16(int i)
{
return Convert.ToInt16(_Data[i]);
}
#endregion
}
}
| |
using UnityEngine;
using UnityEditor;
using Behave.Runtime;
using Behave.Assets;
using Behave.Editor;
using System.IO;
public class BehaveMenu : ScriptableObject
{
[MenuItem ("Help/Behave documentation &%?")]
public static void Documentation ()
{
Behave.Editor.Resources.Documentation ();
}
[MenuItem ("Assets/Behave/Edit library &%e")]
public static void EditLibrary ()
{
EditLibraryAsset ((BehaveAsset)Selection.activeObject);
}
[MenuItem ("Assets/Behave/Edit library &%e", true)]
public static bool ValidateEditLibrary ()
{
return Selection.activeObject is BehaveAsset;
}
[MenuItem ("Assets/Behave/Build library debug &%b")]
public static void Compile ()
{
Compile (true);
}
[MenuItem ("Assets/Behave/Build library debug &%b", true)]
public static bool ValidateCompile ()
{
return Selection.activeObject is BehaveAsset;
}
[MenuItem ("Assets/Behave/Build library release #&%b")]
public static void CompileRelease ()
{
Compile (false);
}
[MenuItem ("Assets/Behave/Build library release #&%b", true)]
public static bool ValidateCompileRelease ()
{
return Selection.activeObject is BehaveAsset;
}
static void Compile (bool debug)
{
BehaveAsset asset = Selection.activeObject as BehaveAsset;
Compiler.Compile (asset, debug);
}
[MenuItem ("Assets/Create/Behave library")]
public static void Create ()
{
BehaveAsset asset;
string name = "NewBehaveLibrary";
int nameIdx = 0;
while (System.IO.File.Exists (
Application.dataPath + "/" + name + nameIdx + ".asset"
))
{
nameIdx++;
}
asset = new BehaveAsset ();
asset.Data = (new Library ()).GetData ();
AssetDatabase.CreateAsset (asset, "Assets/" + name + nameIdx + ".asset");
Selection.activeObject = asset;
EditorUtility.FocusProjectWindow ();
EditLibrary ();
}
[MenuItem ("Assets/Behave/Create/Collection")]
public static void CreateCollection ()
{
Behave.Editor.Editor.Instance.CreateCollection();
}
[MenuItem ("Assets/Behave/Create/Collection", true)]
public static bool ValidateCreateCollection()
{
return Behave.Editor.Editor.Instance != null && Behave.Editor.Editor.Instance.ValidateCreateCollection ();
}
[MenuItem ("Assets/Behave/Create/Tree")]
public static void CreateTree ()
{
Behave.Editor.Editor.Instance.CreateTree ();
}
[MenuItem ("Assets/Behave/Create/Tree", true)]
public static bool ValidateCreateTree ()
{
return Behave.Editor.Editor.Instance != null && Behave.Editor.Editor.Instance.ValidateCreateTree ();
}
[MenuItem ("CONTEXT/Behave/Form new tree")]
public static void FormNewTree ()
{
Behave.Editor.Editor.Instance.FormNewTree ();
}
[MenuItem ("CONTEXT/Behave/Form new tree", true)]
public static bool ValidateFormNewTree ()
{
return Behave.Editor.Editor.Instance.ValidateFormNewTree ();
}
[MenuItem ("CONTEXT/Behave/Purge sub-tree")]
public static void PurgeSubTree ()
{
Behave.Editor.Editor.Instance.PurgeSubTree ();
}
[MenuItem ("CONTEXT/Behave/Purge sub-tree", true)]
public static bool ValidatePurgeSubTree ()
{
return Behave.Editor.Editor.Instance.ValidatePurgeSubTree ();
}
[MenuItem ("Window/Behave debugger")]
public static void ShowDebugger ()
{
if (BehaveDebugWindow.Instance == null)
{
Debug.LogError ("Failed to set up Behave debugger window");
return;
}
Behave.Editor.DebugWindow.Instance.Show ();
Behave.Editor.DebugWindow.Instance.Focus ();
Behave.Editor.DebugWindow.Instance.Repaint ();
}
[MenuItem ("Window/Behave browser")]
public static void ShowBrowser ()
{
if (BehaveBrowser.Instance == null)
{
Debug.LogError ("Failed to set up Behave browser");
return;
}
Behave.Editor.Browser.Instance.Show ();
Behave.Editor.Browser.Instance.Focus ();
Behave.Editor.Browser.Instance.Repaint ();
}
[MenuItem ("Window/Behave tree editor")]
public static void ShowTreeEditor ()
{
if (BehaveTreeEditor.Instance == null)
{
Debug.LogError ("Failed to set up Behave tree editor");
return;
}
Behave.Editor.TreeEditor.Instance.Show ();
Behave.Editor.TreeEditor.Instance.Focus ();
Behave.Editor.TreeEditor.Instance.Repaint ();
}
[MenuItem ("Help/About Behave...")]
public static void About ()
{
BehaveAbout.Instance.ShowUtility ();
}
public static Behave.Editor.Editor EditorInstance
{
get
{
if (Behave.Editor.Editor.Instance == null)
{
BehaveEditor behaveEditor = new BehaveEditor ();
Behave.Editor.Editor.Init (behaveEditor);
behaveEditor.Init ();
}
return Behave.Editor.Editor.Instance;
}
}
public static void EditLibraryAsset (BehaveAsset asset)
{
EditorInstance.Asset = asset;
Selection.activeObject = asset;
ShowTreeEditor ();
ShowBrowser ();
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.Framework.Scenes
{
public partial class Scene
{
/// <summary>
/// Send chat to listeners.
/// </summary>
/// <param name='message'></param>
/// <param name='type'>/param>
/// <param name='channel'></param>
/// <param name='fromPos'></param>
/// <param name='fromName'></param>
/// <param name='fromID'></param>
/// <param name='targetID'></param>
/// <param name='fromAgent'></param>
/// <param name='broadcast'></param>
protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
UUID fromID, UUID targetID, bool fromAgent, bool broadcast)
{
OSChatMessage args = new OSChatMessage();
args.Message = Utils.BytesToString(message);
args.Channel = channel;
args.Type = type;
args.Position = fromPos;
args.SenderUUID = fromID;
args.Scene = this;
if (fromAgent)
{
ScenePresence user = GetScenePresence(fromID);
if (user != null)
args.Sender = user.ControllingClient;
}
else
{
SceneObjectPart obj = GetSceneObjectPart(fromID);
args.SenderObject = obj;
}
args.From = fromName;
args.TargetUUID = targetID;
// m_log.DebugFormat(
// "[SCENE]: Sending message {0} on channel {1}, type {2} from {3}, broadcast {4}",
// args.Message.Replace("\n", "\\n"), args.Channel, args.Type, fromName, broadcast);
if (broadcast)
EventManager.TriggerOnChatBroadcast(this, args);
else
EventManager.TriggerOnChatFromWorld(this, args);
}
protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
UUID fromID, bool fromAgent, bool broadcast)
{
SimChat(message, type, channel, fromPos, fromName, fromID, UUID.Zero, fromAgent, broadcast);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="type"></param>
/// <param name="fromPos"></param>
/// <param name="fromName"></param>
/// <param name="fromAgentID"></param>
public void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
UUID fromID, bool fromAgent)
{
SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, false);
}
public void SimChat(string message, ChatTypeEnum type, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent)
{
SimChat(Utils.StringToBytes(message), type, 0, fromPos, fromName, fromID, fromAgent);
}
public void SimChat(string message, string fromName)
{
SimChat(message, ChatTypeEnum.Broadcast, Vector3.Zero, fromName, UUID.Zero, false);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="type"></param>
/// <param name="fromPos"></param>
/// <param name="fromName"></param>
/// <param name="fromAgentID"></param>
public void SimChatBroadcast(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
UUID fromID, bool fromAgent)
{
SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, true);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="type"></param>
/// <param name="fromPos"></param>
/// <param name="fromName"></param>
/// <param name="fromAgentID"></param>
/// <param name="targetID"></param>
public void SimChatToAgent(UUID targetID, byte[] message, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent)
{
SimChat(message, ChatTypeEnum.Say, 0, fromPos, fromName, fromID, targetID, fromAgent, false);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="type"></param>
/// <param name="channel"></param>
/// <param name="fromPos"></param>
/// <param name="fromName"></param>
/// <param name="fromAgentID"></param>
/// <param name="targetID"></param>
public void SimChatToAgent(UUID targetID, byte[] message, int channel, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent)
{
SimChat(message, ChatTypeEnum.Region, channel, fromPos, fromName, fromID, targetID, fromAgent, false);
}
/// <summary>
/// Invoked when the client requests a prim.
/// </summary>
/// <param name="primLocalID"></param>
/// <param name="remoteClient"></param>
public void RequestPrim(uint primLocalID, IClientAPI remoteClient)
{
SceneObjectGroup sog = GetGroupByPrim(primLocalID);
if (sog != null)
sog.SendFullUpdateToClient(remoteClient);
}
/// <summary>
/// Invoked when the client selects a prim.
/// </summary>
/// <param name="primLocalID"></param>
/// <param name="remoteClient"></param>
public void SelectPrim(uint primLocalID, IClientAPI remoteClient)
{
SceneObjectPart part = GetSceneObjectPart(primLocalID);
if (null == part)
return;
if (part.IsRoot)
{
SceneObjectGroup sog = part.ParentGroup;
sog.SendPropertiesToClient(remoteClient);
sog.IsSelected = true;
// A prim is only tainted if it's allowed to be edited by the person clicking it.
if (Permissions.CanEditObject(sog.UUID, remoteClient.AgentId)
|| Permissions.CanMoveObject(sog.UUID, remoteClient.AgentId))
{
EventManager.TriggerParcelPrimCountTainted();
}
}
else
{
part.SendPropertiesToClient(remoteClient);
}
}
/// <summary>
/// Handle the update of an object's user group.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="groupID"></param>
/// <param name="objectLocalID"></param>
/// <param name="Garbage"></param>
private void HandleObjectGroupUpdate(
IClientAPI remoteClient, UUID groupID, uint objectLocalID, UUID Garbage)
{
if (m_groupsModule == null)
return;
// XXX: Might be better to get rid of this special casing and have GetMembershipData return something
// reasonable for a UUID.Zero group.
if (groupID != UUID.Zero)
{
GroupMembershipData gmd = m_groupsModule.GetMembershipData(groupID, remoteClient.AgentId);
if (gmd == null)
{
// m_log.WarnFormat(
// "[GROUPS]: User {0} is not a member of group {1} so they can't update {2} to this group",
// remoteClient.Name, GroupID, objectLocalID);
return;
}
}
SceneObjectGroup so = ((Scene)remoteClient.Scene).GetGroupByPrim(objectLocalID);
if (so != null)
{
if (so.OwnerID == remoteClient.AgentId)
{
so.SetGroup(groupID, remoteClient);
}
}
}
/// <summary>
/// Handle the deselection of a prim from the client.
/// </summary>
/// <param name="primLocalID"></param>
/// <param name="remoteClient"></param>
public void DeselectPrim(uint primLocalID, IClientAPI remoteClient)
{
SceneObjectPart part = GetSceneObjectPart(primLocalID);
if (part == null)
return;
// A deselect packet contains all the local prims being deselected. However, since selection is still
// group based we only want the root prim to trigger a full update - otherwise on objects with many prims
// we end up sending many duplicate ObjectUpdates
if (part.ParentGroup.RootPart.LocalId != part.LocalId)
return;
// This is wrong, wrong, wrong. Selection should not be
// handled by group, but by prim. Legacy cruft.
// TODO: Make selection flagging per prim!
//
part.ParentGroup.IsSelected = false;
part.ParentGroup.ScheduleGroupForFullUpdate();
// If it's not an attachment, and we are allowed to move it,
// then we might have done so. If we moved across a parcel
// boundary, we will need to recount prims on the parcels.
// For attachments, that makes no sense.
//
if (!part.ParentGroup.IsAttachment)
{
if (Permissions.CanEditObject(
part.UUID, remoteClient.AgentId)
|| Permissions.CanMoveObject(
part.UUID, remoteClient.AgentId))
EventManager.TriggerParcelPrimCountTainted();
}
}
public virtual void ProcessMoneyTransferRequest(UUID source, UUID destination, int amount,
int transactiontype, string description)
{
EventManager.MoneyTransferArgs args = new EventManager.MoneyTransferArgs(source, destination, amount,
transactiontype, description);
EventManager.TriggerMoneyTransfer(this, args);
}
public virtual void ProcessParcelBuy(UUID agentId, UUID groupId, bool final, bool groupOwned,
bool removeContribution, int parcelLocalID, int parcelArea, int parcelPrice, bool authenticated)
{
EventManager.LandBuyArgs args = new EventManager.LandBuyArgs(agentId, groupId, final, groupOwned,
removeContribution, parcelLocalID, parcelArea,
parcelPrice, authenticated);
// First, allow all validators a stab at it
m_eventManager.TriggerValidateLandBuy(this, args);
// Then, check validation and transfer
m_eventManager.TriggerLandBuy(this, args);
}
public virtual void ProcessObjectGrab(uint localID, Vector3 offsetPos, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs)
{
SceneObjectPart part = GetSceneObjectPart(localID);
if (part == null)
return;
SceneObjectGroup obj = part.ParentGroup;
SurfaceTouchEventArgs surfaceArg = null;
if (surfaceArgs != null && surfaceArgs.Count > 0)
surfaceArg = surfaceArgs[0];
// Currently only grab/touch for the single prim
// the client handles rez correctly
obj.ObjectGrabHandler(localID, offsetPos, remoteClient);
// If the touched prim handles touches, deliver it
// If not, deliver to root prim
if ((part.ScriptEvents & scriptEvents.touch_start) != 0)
EventManager.TriggerObjectGrab(part.LocalId, 0, part.OffsetPosition, remoteClient, surfaceArg);
// Deliver to the root prim if the touched prim doesn't handle touches
// or if we're meant to pass on touches anyway. Don't send to root prim
// if prim touched is the root prim as we just did it
if (((part.ScriptEvents & scriptEvents.touch_start) == 0) ||
(part.PassTouches && (part.LocalId != obj.RootPart.LocalId)))
{
EventManager.TriggerObjectGrab(obj.RootPart.LocalId, part.LocalId, part.OffsetPosition, remoteClient, surfaceArg);
}
}
public virtual void ProcessObjectGrabUpdate(
UUID objectID, Vector3 offset, Vector3 pos, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs)
{
SceneObjectPart part = GetSceneObjectPart(objectID);
if (part == null)
return;
SceneObjectGroup obj = part.ParentGroup;
SurfaceTouchEventArgs surfaceArg = null;
if (surfaceArgs != null && surfaceArgs.Count > 0)
surfaceArg = surfaceArgs[0];
// If the touched prim handles touches, deliver it
// If not, deliver to root prim
if ((part.ScriptEvents & scriptEvents.touch) != 0)
EventManager.TriggerObjectGrabbing(part.LocalId, 0, part.OffsetPosition, remoteClient, surfaceArg);
// Deliver to the root prim if the touched prim doesn't handle touches
// or if we're meant to pass on touches anyway. Don't send to root prim
// if prim touched is the root prim as we just did it
if (((part.ScriptEvents & scriptEvents.touch) == 0) ||
(part.PassTouches && (part.LocalId != obj.RootPart.LocalId)))
{
EventManager.TriggerObjectGrabbing(obj.RootPart.LocalId, part.LocalId, part.OffsetPosition, remoteClient, surfaceArg);
}
}
public virtual void ProcessObjectDeGrab(uint localID, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs)
{
SceneObjectPart part = GetSceneObjectPart(localID);
if (part == null)
return;
SceneObjectGroup obj = part.ParentGroup;
SurfaceTouchEventArgs surfaceArg = null;
if (surfaceArgs != null && surfaceArgs.Count > 0)
surfaceArg = surfaceArgs[0];
// If the touched prim handles touches, deliver it
// If not, deliver to root prim
if ((part.ScriptEvents & scriptEvents.touch_end) != 0)
EventManager.TriggerObjectDeGrab(part.LocalId, 0, remoteClient, surfaceArg);
else
EventManager.TriggerObjectDeGrab(obj.RootPart.LocalId, part.LocalId, remoteClient, surfaceArg);
}
public void ProcessScriptReset(IClientAPI remoteClient, UUID objectID,
UUID itemID)
{
SceneObjectPart part=GetSceneObjectPart(objectID);
if (part == null)
return;
if (Permissions.CanResetScript(objectID, itemID, remoteClient.AgentId))
{
EventManager.TriggerScriptReset(part.LocalId, itemID);
}
}
void ProcessViewerEffect(IClientAPI remoteClient, List<ViewerEffectEventHandlerArg> args)
{
// TODO: don't create new blocks if recycling an old packet
bool discardableEffects = true;
ViewerEffectPacket.EffectBlock[] effectBlockArray = new ViewerEffectPacket.EffectBlock[args.Count];
for (int i = 0; i < args.Count; i++)
{
ViewerEffectPacket.EffectBlock effect = new ViewerEffectPacket.EffectBlock();
effect.AgentID = args[i].AgentID;
effect.Color = args[i].Color;
effect.Duration = args[i].Duration;
effect.ID = args[i].ID;
effect.Type = args[i].Type;
effect.TypeData = args[i].TypeData;
effectBlockArray[i] = effect;
if ((EffectType)effect.Type != EffectType.LookAt && (EffectType)effect.Type != EffectType.Beam)
discardableEffects = false;
//m_log.DebugFormat("[YYY]: VE {0} {1} {2}", effect.AgentID, effect.Duration, (EffectType)effect.Type);
}
ForEachScenePresence(sp =>
{
if (sp.ControllingClient.AgentId != remoteClient.AgentId)
{
if (!discardableEffects ||
(discardableEffects && ShouldSendDiscardableEffect(remoteClient, sp)))
{
//m_log.DebugFormat("[YYY]: Sending to {0}", sp.UUID);
sp.ControllingClient.SendViewerEffect(effectBlockArray);
}
//else
// m_log.DebugFormat("[YYY]: Not sending to {0}", sp.UUID);
}
});
}
private bool ShouldSendDiscardableEffect(IClientAPI thisClient, ScenePresence other)
{
return Vector3.Distance(other.CameraPosition, thisClient.SceneAgent.AbsolutePosition) < 10;
}
/// <summary>
/// Tell the client about the various child items and folders contained in the requested folder.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
/// <param name="ownerID"></param>
/// <param name="fetchFolders"></param>
/// <param name="fetchItems"></param>
/// <param name="sortOrder"></param>
public void HandleFetchInventoryDescendents(IClientAPI remoteClient, UUID folderID, UUID ownerID,
bool fetchFolders, bool fetchItems, int sortOrder)
{
// m_log.DebugFormat(
// "[USER INVENTORY]: HandleFetchInventoryDescendents() for {0}, folder={1}, fetchFolders={2}, fetchItems={3}, sortOrder={4}",
// remoteClient.Name, folderID, fetchFolders, fetchItems, sortOrder);
if (folderID == UUID.Zero)
return;
// FIXME MAYBE: We're not handling sortOrder!
// TODO: This code for looking in the folder for the library should be folded somewhere else
// so that this class doesn't have to know the details (and so that multiple libraries, etc.
// can be handled transparently).
InventoryFolderImpl fold = null;
if (LibraryService != null && LibraryService.LibraryRootFolder != null)
{
if ((fold = LibraryService.LibraryRootFolder.FindFolder(folderID)) != null)
{
remoteClient.SendInventoryFolderDetails(
fold.Owner, folderID, fold.RequestListOfItems(),
fold.RequestListOfFolders(), fold.Version, fetchFolders, fetchItems);
return;
}
}
// We're going to send the reply async, because there may be
// an enormous quantity of packets -- basically the entire inventory!
// We don't want to block the client thread while all that is happening.
SendInventoryDelegate d = SendInventoryAsync;
d.BeginInvoke(remoteClient, folderID, ownerID, fetchFolders, fetchItems, sortOrder, SendInventoryComplete, d);
}
delegate void SendInventoryDelegate(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder);
void SendInventoryAsync(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder)
{
try
{
SendInventoryUpdate(remoteClient, new InventoryFolderBase(folderID), fetchFolders, fetchItems);
}
catch (Exception e)
{
m_log.Error(
string.Format(
"[AGENT INVENTORY]: Error in SendInventoryAsync() for {0} with folder ID {1}. Exception ", e));
}
}
void SendInventoryComplete(IAsyncResult iar)
{
SendInventoryDelegate d = (SendInventoryDelegate)iar.AsyncState;
d.EndInvoke(iar);
}
/// <summary>
/// Handle an inventory folder creation request from the client.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
/// <param name="folderType"></param>
/// <param name="folderName"></param>
/// <param name="parentID"></param>
public void HandleCreateInventoryFolder(IClientAPI remoteClient, UUID folderID, ushort folderType,
string folderName, UUID parentID)
{
InventoryFolderBase folder = new InventoryFolderBase(folderID, folderName, remoteClient.AgentId, (short)folderType, parentID, 1);
if (!InventoryService.AddFolder(folder))
{
m_log.WarnFormat(
"[AGENT INVENTORY]: Failed to create folder for user {0} {1}",
remoteClient.Name, remoteClient.AgentId);
}
}
/// <summary>
/// Handle a client request to update the inventory folder
/// </summary>
///
/// FIXME: We call add new inventory folder because in the data layer, we happen to use an SQL REPLACE
/// so this will work to rename an existing folder. Needless to say, to rely on this is very confusing,
/// and needs to be changed.
///
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
/// <param name="type"></param>
/// <param name="name"></param>
/// <param name="parentID"></param>
public void HandleUpdateInventoryFolder(IClientAPI remoteClient, UUID folderID, ushort type, string name,
UUID parentID)
{
// m_log.DebugFormat(
// "[AGENT INVENTORY]: Updating inventory folder {0} {1} for {2} {3}", folderID, name, remoteClient.Name, remoteClient.AgentId);
InventoryFolderBase folder = new InventoryFolderBase(folderID, remoteClient.AgentId);
folder = InventoryService.GetFolder(folder);
if (folder != null)
{
folder.Name = name;
folder.Type = (short)type;
folder.ParentID = parentID;
if (!InventoryService.UpdateFolder(folder))
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Failed to update folder for user {0} {1}",
remoteClient.Name, remoteClient.AgentId);
}
}
}
public void HandleMoveInventoryFolder(IClientAPI remoteClient, UUID folderID, UUID parentID)
{
InventoryFolderBase folder = new InventoryFolderBase(folderID, remoteClient.AgentId);
folder = InventoryService.GetFolder(folder);
if (folder != null)
{
folder.ParentID = parentID;
if (!InventoryService.MoveFolder(folder))
m_log.WarnFormat("[AGENT INVENTORY]: could not move folder {0}", folderID);
else
m_log.DebugFormat("[AGENT INVENTORY]: folder {0} moved to parent {1}", folderID, parentID);
}
else
{
m_log.WarnFormat("[AGENT INVENTORY]: request to move folder {0} but folder not found", folderID);
}
}
delegate void PurgeFolderDelegate(UUID userID, UUID folder);
/// <summary>
/// This should delete all the items and folders in the given directory.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
public void HandlePurgeInventoryDescendents(IClientAPI remoteClient, UUID folderID)
{
PurgeFolderDelegate d = PurgeFolderAsync;
try
{
d.BeginInvoke(remoteClient.AgentId, folderID, PurgeFolderCompleted, d);
}
catch (Exception e)
{
m_log.WarnFormat("[AGENT INVENTORY]: Exception on purge folder for user {0}: {1}", remoteClient.AgentId, e.Message);
}
}
private void PurgeFolderAsync(UUID userID, UUID folderID)
{
InventoryFolderBase folder = new InventoryFolderBase(folderID, userID);
if (InventoryService.PurgeFolder(folder))
m_log.DebugFormat("[AGENT INVENTORY]: folder {0} purged successfully", folderID);
else
m_log.WarnFormat("[AGENT INVENTORY]: could not purge folder {0}", folderID);
}
private void PurgeFolderCompleted(IAsyncResult iar)
{
PurgeFolderDelegate d = (PurgeFolderDelegate)iar.AsyncState;
d.EndInvoke(iar);
}
}
}
| |
// 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.Linq;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs.Asn1;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using Internal.Cryptography;
namespace System.Security.Cryptography.Pkcs
{
public sealed class Rfc3161TimestampToken
{
private SignedCms _parsedDocument;
private SignerInfo _signerInfo;
private EssCertId? _essCertId;
private EssCertIdV2? _essCertIdV2;
public Rfc3161TimestampTokenInfo TokenInfo { get; private set; }
private Rfc3161TimestampToken()
{
}
/// <summary>
/// Get a SignedCms representation of the RFC3161 Timestamp Token.
/// </summary>
/// <returns>The SignedCms representation of the RFC3161 Timestamp Token.</returns>
/// <remarks>
/// Successive calls to this method return the same object.
/// The SignedCms class is mutable, but changes to that object are not reflected in the
/// <see cref="Rfc3161TimestampToken"/> object which produced it.
/// The value from calling <see cref="SignedCms.Encode"/> can be interpreted again as an
/// <see cref="Rfc3161TimestampToken"/> via another call to <see cref="TryDecode"/>.
/// </remarks>
public SignedCms AsSignedCms() => _parsedDocument;
private X509Certificate2 GetSignerCertificate(X509Certificate2Collection extraCandidates)
{
Debug.Assert(_signerInfo != null, "_signerInfo != null");
X509Certificate2 signerCert = _signerInfo.Certificate;
if (signerCert != null)
{
if (CheckCertificate(signerCert, _signerInfo, in _essCertId, in _essCertIdV2, TokenInfo))
{
return signerCert;
}
// SignedCms will not try another certificate in this state, so just fail.
return null;
}
if (extraCandidates == null || extraCandidates.Count == 0)
{
return null;
}
foreach (X509Certificate2 candidate in extraCandidates)
{
if (CheckCertificate(candidate, _signerInfo, in _essCertId, in _essCertIdV2, TokenInfo))
{
return candidate;
}
}
return null;
}
public bool VerifySignatureForData(
ReadOnlySpan<byte> data,
out X509Certificate2 signerCertificate,
X509Certificate2Collection extraCandidates = null)
{
signerCertificate = null;
X509Certificate2 cert = GetSignerCertificate(extraCandidates);
if (cert == null)
{
return false;
}
bool ret = VerifyData(data);
if (ret)
{
signerCertificate = cert;
}
return ret;
}
public bool VerifySignatureForHash(
ReadOnlySpan<byte> hash,
HashAlgorithmName hashAlgorithm,
out X509Certificate2 signerCertificate,
X509Certificate2Collection extraCandidates = null)
{
signerCertificate = null;
X509Certificate2 cert = GetSignerCertificate(extraCandidates);
if (cert == null)
{
return false;
}
bool ret = VerifyHash(hash, PkcsHelpers.GetOidFromHashAlgorithm(hashAlgorithm));
if (ret)
{
signerCertificate = cert;
}
return ret;
}
public bool VerifySignatureForHash(
ReadOnlySpan<byte> hash,
Oid hashAlgorithmId,
out X509Certificate2 signerCertificate,
X509Certificate2Collection extraCandidates = null)
{
if (hashAlgorithmId == null)
{
throw new ArgumentNullException(nameof(hashAlgorithmId));
}
signerCertificate = null;
X509Certificate2 cert = GetSignerCertificate(extraCandidates);
if (cert == null)
{
return false;
}
bool ret = VerifyHash(hash, hashAlgorithmId.Value);
if (ret)
{
// REVIEW: Should this return the cert, or new X509Certificate2(cert.RawData)?
// SignedCms.SignerInfos builds new objects each call, which makes
// ReferenceEquals(cms.SignerInfos[0].Certificate, cms.SignerInfos[0].Certificate) be false.
// So maybe it's weird to give back a cert we've copied from that?
signerCertificate = cert;
}
return ret;
}
public bool VerifySignatureForSignerInfo(
SignerInfo signerInfo,
out X509Certificate2 signerCertificate,
X509Certificate2Collection extraCandidates = null)
{
if (signerInfo == null)
{
throw new ArgumentNullException(nameof(signerInfo));
}
return VerifySignatureForData(
signerInfo.GetSignatureMemory().Span,
out signerCertificate,
extraCandidates);
}
internal bool VerifyHash(ReadOnlySpan<byte> hash, string hashAlgorithmId)
{
return
hash.SequenceEqual(TokenInfo.GetMessageHash().Span) &&
hashAlgorithmId == TokenInfo.HashAlgorithmId.Value;
}
private bool VerifyData(ReadOnlySpan<byte> data)
{
Oid hashAlgorithmId = TokenInfo.HashAlgorithmId;
HashAlgorithmName hashAlgorithmName = PkcsHelpers.GetDigestAlgorithm(hashAlgorithmId);
using (IncrementalHash hasher = IncrementalHash.CreateHash(hashAlgorithmName))
{
hasher.AppendData(data);
// SHA-2-512 is the biggest hash we currently know about.
Span<byte> stackSpan = stackalloc byte[512 / 8];
if (hasher.TryGetHashAndReset(stackSpan, out int bytesWritten))
{
return VerifyHash(stackSpan.Slice(0, bytesWritten), hashAlgorithmId.Value);
}
// Something we understood, but is bigger than 512-bit.
// Allocate at runtime, trip in a debug build so we can re-evaluate this.
Debug.Fail(
$"TryGetHashAndReset did not fit in {stackSpan.Length} for hash {hashAlgorithmId.Value}");
return VerifyHash(hasher.GetHashAndReset(), hashAlgorithmId.Value);
}
}
private static bool CheckCertificate(
X509Certificate2 tsaCertificate,
SignerInfo signer,
in EssCertId? certId,
in EssCertIdV2? certId2,
Rfc3161TimestampTokenInfo tokenInfo)
{
Debug.Assert(tsaCertificate != null);
Debug.Assert(signer != null);
Debug.Assert(tokenInfo != null);
// certId and certId2 are allowed to be null, they get checked in CertMatchesIds.
if (!CertMatchesIds(tsaCertificate, certId, certId2))
{
return false;
}
// Nothing in RFC3161 actually mentions checking the certificate's validity
// against the TSTInfo timestamp value, but it seems sensible.
//
// Accuracy is ignored here, for better replicability in user code.
if (tsaCertificate.NotAfter < tokenInfo.Timestamp ||
tsaCertificate.NotBefore > tokenInfo.Timestamp)
{
return false;
}
// https://tools.ietf.org/html/rfc3161#section-2.3
//
// The TSA MUST sign each time-stamp message with a key reserved
// specifically for that purpose. A TSA MAY have distinct private keys,
// e.g., to accommodate different policies, different algorithms,
// different private key sizes or to increase the performance. The
// corresponding certificate MUST contain only one instance of the
// extended key usage field extension as defined in [RFC2459] Section
// 4.2.1.13 with KeyPurposeID having value:
//
// id-kp-timeStamping. This extension MUST be critical.
using (var ekuExts = tsaCertificate.Extensions.OfType<X509EnhancedKeyUsageExtension>().GetEnumerator())
{
if (!ekuExts.MoveNext())
{
return false;
}
X509EnhancedKeyUsageExtension ekuExt = ekuExts.Current;
if (!ekuExt.Critical)
{
return false;
}
bool hasPurpose = false;
foreach (Oid oid in ekuExt.EnhancedKeyUsages)
{
if (oid.Value == Oids.TimeStampingPurpose)
{
hasPurpose = true;
break;
}
}
if (!hasPurpose)
{
return false;
}
if (ekuExts.MoveNext())
{
return false;
}
}
try
{
signer.CheckSignature(new X509Certificate2Collection(tsaCertificate), true);
return true;
}
catch (CryptographicException)
{
return false;
}
}
public static bool TryDecode(ReadOnlyMemory<byte> source, out Rfc3161TimestampToken token, out int bytesConsumed)
{
bytesConsumed = 0;
token = null;
try
{
AsnReader reader = new AsnReader(source, AsnEncodingRules.BER);
int bytesActuallyRead = reader.PeekEncodedValue().Length;
ContentInfoAsn.Decode(
reader,
out ContentInfoAsn contentInfo);
// https://tools.ietf.org/html/rfc3161#section-2.4.2
//
// A TimeStampToken is as follows. It is defined as a ContentInfo
// ([CMS]) and SHALL encapsulate a signed data content type.
//
// TimeStampToken::= ContentInfo
// --contentType is id-signedData([CMS])
// --content is SignedData ([CMS])
if (contentInfo.ContentType != Oids.Pkcs7Signed)
{
return false;
}
SignedCms cms = new SignedCms();
cms.Decode(source);
// The fields of type EncapsulatedContentInfo of the SignedData
// construct have the following meanings:
//
// eContentType is an object identifier that uniquely specifies the
// content type. For a time-stamp token it is defined as:
//
// id-ct-TSTInfo OBJECT IDENTIFIER ::= { iso(1) member-body(2)
// us(840) rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) ct(1) 4}
//
// eContent is the content itself, carried as an octet string.
// The eContent SHALL be the DER-encoded value of TSTInfo.
if (cms.ContentInfo.ContentType.Value != Oids.TstInfo)
{
return false;
}
// RFC3161:
// The time-stamp token MUST NOT contain any signatures other than the
// signature of the TSA. The certificate identifier (ESSCertID) of the
// TSA certificate MUST be included as a signerInfo attribute inside a
// SigningCertificate attribute.
// RFC5816 says that ESSCertIDv2 should be allowed instead.
SignerInfoCollection signerInfos = cms.SignerInfos;
if (signerInfos.Count != 1)
{
return false;
}
SignerInfo signer = signerInfos[0];
EssCertId? certId;
EssCertIdV2? certId2;
if (!TryGetCertIds(signer, out certId, out certId2))
{
return false;
}
X509Certificate2 signerCert = signer.Certificate;
if (signerCert == null &&
signer.SignerIdentifier.Type == SubjectIdentifierType.IssuerAndSerialNumber)
{
// If the cert wasn't provided, but the identifier was IssuerAndSerialNumber,
// and the ESSCertId(V2) has specified an issuerSerial value, ensure it's a match.
X509IssuerSerial issuerSerial = (X509IssuerSerial)signer.SignerIdentifier.Value;
if (certId.HasValue && certId.Value.IssuerSerial != null)
{
if (!IssuerAndSerialMatch(
certId.Value.IssuerSerial.Value,
issuerSerial.IssuerName,
issuerSerial.SerialNumber))
{
return false;
}
}
if (certId2.HasValue && certId2.Value.IssuerSerial != null)
{
if (!IssuerAndSerialMatch(
certId2.Value.IssuerSerial.Value,
issuerSerial.IssuerName,
issuerSerial.SerialNumber))
{
return false;
}
}
}
Rfc3161TimestampTokenInfo tokenInfo;
if (Rfc3161TimestampTokenInfo.TryDecode(cms.ContentInfo.Content, out tokenInfo, out _))
{
if (signerCert != null &&
!CheckCertificate(signerCert, signer, in certId, in certId2, tokenInfo))
{
return false;
}
token = new Rfc3161TimestampToken
{
_parsedDocument = cms,
_signerInfo = signer,
_essCertId = certId,
_essCertIdV2 = certId2,
TokenInfo = tokenInfo,
};
bytesConsumed = bytesActuallyRead;
return true;
}
}
catch (CryptographicException)
{
}
return false;
}
private static bool IssuerAndSerialMatch(
CadesIssuerSerial issuerSerial,
string issuerDirectoryName,
string serialNumber)
{
GeneralNameAsn[] issuerNames = issuerSerial.Issuer;
if (issuerNames == null || issuerNames.Length != 1)
{
return false;
}
GeneralNameAsn requiredName = issuerNames[0];
if (requiredName.DirectoryName == null)
{
return false;
}
if (issuerDirectoryName != new X500DistinguishedName(requiredName.DirectoryName.Value.ToArray()).Name)
{
return false;
}
return serialNumber == issuerSerial.SerialNumber.Span.ToBigEndianHex();
}
private static bool IssuerAndSerialMatch(
CadesIssuerSerial issuerSerial,
ReadOnlySpan<byte> issuerDirectoryName,
ReadOnlySpan<byte> serialNumber)
{
GeneralNameAsn[] issuerNames = issuerSerial.Issuer;
if (issuerNames == null || issuerNames.Length != 1)
{
return false;
}
GeneralNameAsn requiredName = issuerNames[0];
if (requiredName.DirectoryName == null)
{
return false;
}
if (!requiredName.DirectoryName.Value.Span.SequenceEqual(issuerDirectoryName))
{
return false;
}
return serialNumber.SequenceEqual(issuerSerial.SerialNumber.Span);
}
private static bool CertMatchesIds(X509Certificate2 signerCert, in EssCertId? certId, in EssCertIdV2? certId2)
{
Debug.Assert(signerCert != null);
Debug.Assert(certId.HasValue || certId2.HasValue);
byte[] serialNumber = null;
if (certId.HasValue)
{
Span<byte> thumbprint = stackalloc byte[20];
if (!signerCert.TryGetCertHash(HashAlgorithmName.SHA1, thumbprint, out int written) ||
written != thumbprint.Length ||
!thumbprint.SequenceEqual(certId.Value.Hash.Span))
{
return false;
}
if (certId.Value.IssuerSerial.HasValue)
{
serialNumber = signerCert.GetSerialNumber();
Array.Reverse(serialNumber);
if (!IssuerAndSerialMatch(
certId.Value.IssuerSerial.Value,
signerCert.IssuerName.RawData,
serialNumber))
{
return false;
}
}
}
if (certId2.HasValue)
{
HashAlgorithmName alg;
// SHA-2-512 is the biggest we know about.
Span<byte> thumbprint = stackalloc byte[512 / 8];
try
{
alg = PkcsHelpers.GetDigestAlgorithm(certId2.Value.HashAlgorithm.Algorithm);
if (signerCert.TryGetCertHash(alg, thumbprint, out int written))
{
thumbprint = thumbprint.Slice(0, written);
}
else
{
Debug.Fail(
$"TryGetCertHash did not fit in {thumbprint.Length} for hash {certId2.Value.HashAlgorithm.Algorithm.Value}");
thumbprint = signerCert.GetCertHash(alg);
}
}
catch (CryptographicException)
{
return false;
}
if (!thumbprint.SequenceEqual(certId2.Value.Hash.Span))
{
return false;
}
if (certId2.Value.IssuerSerial.HasValue)
{
if (serialNumber == null)
{
serialNumber = signerCert.GetSerialNumber();
Array.Reverse(serialNumber);
}
if (!IssuerAndSerialMatch(
certId2.Value.IssuerSerial.Value,
signerCert.IssuerName.RawData,
serialNumber))
{
return false;
}
}
}
return true;
}
private static bool TryGetCertIds(SignerInfo signer, out EssCertId? certId, out EssCertIdV2? certId2)
{
// RFC 5035 says that SigningCertificateV2 (contains ESSCertIDv2) is a signed
// attribute, with OID 1.2.840.113549.1.9.16.2.47, and that it must not be multiply defined.
// RFC 2634 says that SigningCertificate (contains ESSCertID) is a signed attribute,
// with OID 1.2.840.113549.1.9.16.2.12, and that it must not be multiply defined.
certId = null;
certId2 = null;
foreach (CryptographicAttributeObject attrSet in signer.SignedAttributes)
{
string setOid = attrSet.Oid?.Value;
if (setOid != null &&
setOid != Oids.SigningCertificate &&
setOid != Oids.SigningCertificateV2)
{
continue;
}
foreach (AsnEncodedData attr in attrSet.Values)
{
string attrOid = attr.Oid?.Value;
if (attrOid == Oids.SigningCertificate)
{
if (certId != null)
{
return false;
}
try
{
SigningCertificateAsn signingCert = SigningCertificateAsn.Decode(
attr.RawData,
AsnEncodingRules.BER);
if (signingCert.Certs.Length < 1)
{
return false;
}
// The first one is the signing cert, the rest constrain the chain.
certId = signingCert.Certs[0];
}
catch (CryptographicException)
{
return false;
}
}
if (attrOid == Oids.SigningCertificateV2)
{
if (certId2 != null)
{
return false;
}
try
{
SigningCertificateV2Asn signingCert = SigningCertificateV2Asn.Decode(
attr.RawData,
AsnEncodingRules.BER);
if (signingCert.Certs.Length < 1)
{
return false;
}
// The first one is the signing cert, the rest constrain the chain.
certId2 = signingCert.Certs[0];
}
catch (CryptographicException)
{
return false;
}
}
}
}
return certId2 != null || certId != null;
}
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="ColumnCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------
// <summary>
// </summary>
// ---------------------------------------------------------------------
namespace Microsoft.Database.Isam
{
using System;
using System.Collections;
using System.Globalization;
using Microsoft.Isam.Esent.Interop;
/// <summary>
/// Contains the columns defined in the table.
/// </summary>
public class ColumnCollection : DictionaryBase, IEnumerable
{
/// <summary>
/// The database
/// </summary>
private readonly IsamDatabase database;
/// <summary>
/// The table name
/// </summary>
private readonly string tableName;
/// <summary>
/// The cached column definition
/// </summary>
private string cachedColumnDefinition = null;
/// <summary>
/// The column definition
/// </summary>
private ColumnDefinition columnDefinition = null;
/// <summary>
/// The column update identifier
/// </summary>
private long columnUpdateID = 0;
/// <summary>
/// Whether the collection is read-only.
/// </summary>
private bool readOnly = false;
/// <summary>
/// Initializes a new instance of the <see cref="ColumnCollection"/> class.
/// </summary>
public ColumnCollection()
{
this.database = null;
}
/// <summary>
/// Initializes a new instance of the <see cref="ColumnCollection"/> class.
/// </summary>
/// <param name="database">The database.</param>
/// <param name="tableName">Name of the table.</param>
internal ColumnCollection(IsamDatabase database, string tableName)
{
this.database = database;
this.tableName = tableName;
this.readOnly = true;
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.IDictionary" /> object has a fixed size.
/// </summary>
/// <returns>true if the <see cref="T:System.Collections.IDictionary" /> object has a fixed size; otherwise, false.</returns>
public bool IsFixedSize
{
get
{
return this.readOnly;
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.IDictionary" /> object is read-only.
/// </summary>
/// <returns>true if the <see cref="T:System.Collections.IDictionary" /> object is read-only; otherwise, false.</returns>
public bool IsReadOnly
{
get
{
return this.readOnly;
}
}
/// <summary>
/// Gets the names.
/// </summary>
/// <value>
/// The names.
/// </value>
/// <exception cref="System.InvalidOperationException">the names of the columns in this column collection cannot be enumerated in this manner when accessing the table definition of an existing table</exception>
public ICollection Names
{
get
{
if (this.database != null)
{
// CONSIDER: should we provide an ICollection of our column names to avoid this wart?
throw new InvalidOperationException(
"the names of the columns in this column collection cannot be enumerated in this manner when accessing the table definition of an existing table");
}
else
{
return this.Dictionary.Keys;
}
}
}
/// <summary>
/// Sets a value indicating whether [read only].
/// </summary>
/// <value>
/// <c>true</c> if [read only]; otherwise, <c>false</c>.
/// </value>
internal bool ReadOnly
{
set
{
this.readOnly = value;
}
}
/// <summary>
/// Fetches the Column Definition for the specified column name.
/// </summary>
/// <value>
/// The <see cref="ColumnDefinition"/> for the specifed column name.
/// </value>
/// <param name="columnName">Name of the column.</param>
/// <returns>The <see cref="ColumnDefinition"/> for the specified column name.</returns>
public ColumnDefinition this[string columnName]
{
get
{
if (this.database != null)
{
lock (this.database.IsamSession)
{
if (this.cachedColumnDefinition != columnName.ToLower(CultureInfo.InvariantCulture)
|| this.columnUpdateID != DatabaseCommon.SchemaUpdateID)
{
JET_COLUMNBASE columnBase;
Api.JetGetColumnInfo(
this.database.IsamSession.Sesid,
this.database.Dbid,
this.tableName,
columnName,
out columnBase);
this.columnDefinition = ColumnDefinition.Load(this.database, this.tableName, columnBase);
this.cachedColumnDefinition = columnName.ToLower(CultureInfo.InvariantCulture);
this.columnUpdateID = DatabaseCommon.SchemaUpdateID;
}
return this.columnDefinition;
}
}
else
{
return (ColumnDefinition)this.Dictionary[columnName.ToLower(CultureInfo.InvariantCulture)];
}
}
}
/// <summary>
/// Fetches the Column Definition for the specified columnid.
/// </summary>
/// <value>
/// The <see cref="ColumnDefinition"/> for the specifed column identifier
/// </value>
/// <param name="columnid">The columnid.</param>
/// <returns>The <see cref="ColumnDefinition"/> for the specified column identifier.</returns>
public ColumnDefinition this[Columnid columnid]
{
get
{
if (this.database != null)
{
lock (this.database.IsamSession)
{
if (this.cachedColumnDefinition != columnid.Name.ToLower(CultureInfo.InvariantCulture)
|| this.columnUpdateID != DatabaseCommon.SchemaUpdateID)
{
JET_COLUMNBASE columnBase;
Api.JetGetColumnInfo(
this.database.IsamSession.Sesid,
this.database.Dbid,
this.tableName,
columnid.Name,
out columnBase);
this.columnDefinition = ColumnDefinition.Load(this.database, this.tableName, columnBase);
this.cachedColumnDefinition = columnid.Name.ToLower(CultureInfo.InvariantCulture);
this.columnUpdateID = DatabaseCommon.SchemaUpdateID;
}
return this.columnDefinition;
}
}
else
{
return (ColumnDefinition)this.Dictionary[columnid.Name.ToLower(CultureInfo.InvariantCulture)];
}
}
}
/// <summary>
/// Fetches an enumerator containing all the columns in this table.
/// </summary>
/// <returns>An enumerator containing all the columns in this table.</returns>
/// <remarks>
/// This is the type safe version that may not work in other CLR
/// languages.
/// </remarks>
public new ColumnEnumerator GetEnumerator()
{
if (this.database != null)
{
return new ColumnEnumerator(this.database, this.tableName);
}
else
{
return new ColumnEnumerator(Dictionary.GetEnumerator());
}
}
/// <summary>
/// Adds the specified column definition.
/// </summary>
/// <param name="columnDefinition">The column definition.</param>
public void Add(ColumnDefinition columnDefinition)
{
Dictionary.Add(columnDefinition.Name.ToLower(CultureInfo.InvariantCulture), columnDefinition);
}
/// <summary>
/// Determines if the table contains a column with the given name
/// </summary>
/// <param name="columnName">Name of the column.</param>
/// <returns>Whether the specified column exists in the collection.</returns>
public bool Contains(string columnName)
{
if (this.database != null)
{
lock (this.database.IsamSession)
{
bool exists = false;
try
{
JET_COLUMNBASE columnBase;
Api.JetGetColumnInfo(
this.database.IsamSession.Sesid,
this.database.Dbid,
this.tableName,
columnName,
out columnBase);
exists = true;
}
catch (EsentColumnNotFoundException)
{
}
return exists;
}
}
else
{
return Dictionary.Contains(columnName.ToLower(CultureInfo.InvariantCulture));
}
}
/// <summary>
/// Determines if the table contains a column with the given columnid
/// </summary>
/// <param name="columnid">The columnid.</param>
/// <returns>Whether the specified column exists in the collection.</returns>
public bool Contains(Columnid columnid)
{
if (this.database != null)
{
lock (this.database.IsamSession)
{
bool exists = false;
try
{
JET_COLUMNBASE columnBase;
Api.JetGetColumnInfo(
this.database.IsamSession.Sesid,
this.database.Dbid,
this.tableName,
columnid.Name,
out columnBase);
exists = true;
}
catch (EsentColumnNotFoundException)
{
}
return exists;
}
}
else
{
return Dictionary.Contains(columnid.Name.ToLower(CultureInfo.InvariantCulture));
}
}
/// <summary>
/// Removes the specified column name.
/// </summary>
/// <param name="columnName">Name of the column.</param>
public void Remove(string columnName)
{
Dictionary.Remove(columnName.ToLower(CultureInfo.InvariantCulture));
}
/// <summary>
/// Removes the specified columnid.
/// </summary>
/// <param name="columnid">The columnid.</param>
public void Remove(Columnid columnid)
{
Dictionary.Remove(columnid.Name.ToLower(CultureInfo.InvariantCulture));
}
/// <summary>
/// Fetches an enumerator containing all the columns in this table
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.
/// </returns>
/// <remarks>
/// This is the standard version that will work with other CLR
/// languages.
/// </remarks>
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)this.GetEnumerator();
}
/// <summary>
/// Performs additional custom processes before clearing the contents of the <see cref="T:System.Collections.DictionaryBase" /> instance.
/// </summary>
protected override void OnClear()
{
this.CheckReadOnly();
}
/// <summary>
/// Performs additional custom processes before inserting a new element into the <see cref="T:System.Collections.DictionaryBase" /> instance.
/// </summary>
/// <param name="key">The key of the element to insert.</param>
/// <param name="value">The value of the element to insert.</param>
protected override void OnInsert(object key, object value)
{
this.CheckReadOnly();
}
/// <summary>
/// Performs additional custom processes before removing an element from the <see cref="T:System.Collections.DictionaryBase" /> instance.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <param name="value">The value of the element to remove.</param>
protected override void OnRemove(object key, object value)
{
this.CheckReadOnly();
}
/// <summary>
/// Performs additional custom processes before setting a value in the <see cref="T:System.Collections.DictionaryBase" /> instance.
/// </summary>
/// <param name="key">The key of the element to locate.</param>
/// <param name="oldValue">The old value of the element associated with <paramref name="key" />.</param>
/// <param name="newValue">The new value of the element associated with <paramref name="key" />.</param>
protected override void OnSet(object key, object oldValue, object newValue)
{
this.CheckReadOnly();
}
/// <summary>
/// Performs additional custom processes when validating the element with the specified key and value.
/// </summary>
/// <param name="key">The key of the element to validate.</param>
/// <param name="value">The value of the element to validate.</param>
/// <exception cref="System.ArgumentException">
/// key must be of type System.String;key
/// or
/// value must be of type ColumnDefinition;value
/// or
/// key must match value.Name;key
/// </exception>
protected override void OnValidate(object key, object value)
{
if (!(key is string))
{
throw new ArgumentException("key must be of type System.String", "key");
}
if (!(value is ColumnDefinition))
{
throw new ArgumentException("value must be of type ColumnDefinition", "value");
}
if (((string)key).ToLower(CultureInfo.InvariantCulture) != ((ColumnDefinition)value).Name.ToLower(CultureInfo.InvariantCulture))
{
throw new ArgumentException("key must match value.Name", "key");
}
}
/// <summary>
/// Checks the read only.
/// </summary>
/// <exception cref="System.NotSupportedException">this index collection cannot be changed</exception>
private void CheckReadOnly()
{
if (this.readOnly)
{
throw new NotSupportedException("this index collection cannot be changed");
}
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Array.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.
using System.Collections;
using Dot42;
using Dot42.Internal;
using Java.Util;
namespace System
{
/// <summary>
/// Base class for array.
/// This will always map to java/lang/Object because there is no special base class for java array's.
/// </summary>
[Dot42.DexImport("java/lang/Object", IgnoreFromJava = true, Priority = 1)]
public abstract class Array : IEnumerable, ICollection, IList
{
/// <summary>
/// Gets the number of elements in this array.
/// </summary>
public int Length
{
[DexNative]
get { return 0; }
}
/// <summary>
/// Gets the value of the array at the given index.
/// </summary>
public object GetValue(int index)
{
return Java.Lang.Reflect.Array.Get(this, index);
}
public object GetValue(int index1, int index2)
{
var a = (Array) Java.Lang.Reflect.Array.Get(this, index1);
return Java.Lang.Reflect.Array.Get(a, index2);
}
public object GetValue(int[] indices)
{
int i;
var a = this;
for (i = 0; i < indices.Length - 1; ++i)
{
a = (Array) Java.Lang.Reflect.Array.Get(a, indices[i]);
}
return Java.Lang.Reflect.Array.Get(a, indices[i]);
}
/// <summary>
/// Sets the value of the array at the given index.
/// </summary>
public void SetValue(object value, int index)
{
Java.Lang.Reflect.Array.Set(this, index, value);
}
public void SetValue(object value, int index1, int index2)
{
var a = (Array)Java.Lang.Reflect.Array.Get(this, index1);
Java.Lang.Reflect.Array.Set(a, index2, value);
}
/// <summary>
/// Sets the value of the array at the given indices.
/// </summary>
public void SetValue(object value, int[] indices)
{
int i = 0;
var a = this;
for (; i < indices.Length - 1; ++ i)
{
a = (Array) Java.Lang.Reflect.Array.Get(a, indices[i]);
}
Java.Lang.Reflect.Array.Set(a, indices[i], value);
}
/// <summary>
/// Set a range of element in the given array starting at the given index to 0 or null.
/// </summary>
public static void Clear(Array source, int index, int length)
{
var end = index + length;
if (source is sbyte[]) Arrays.Fill((sbyte[]) source, index, end, 0);
else if (source is bool[]) Arrays.Fill((bool[])source, index, end, false);
else if (source is char[]) Arrays.Fill((char[])source, index, end, '\0');
else if (source is short[]) Arrays.Fill((short[])source, index, end, 0);
else if (source is int[]) Arrays.Fill((int[])source, index, end, 0);
else if (source is long[]) Arrays.Fill((long[])source, index, end, 0L);
else if (source is float[]) Arrays.Fill((float[])source, index, end, 0.0F);
else if (source is double[]) Arrays.Fill((double[])source, index, end, 0.0);
else Arrays.Fill((object[])source, index, end, null);
}
/// <summary>
/// Copy a range of elements from the front of the source array to the front of the destination array.
/// </summary>
public static void Copy(Array source, Array destination, int length)
{
Java.Lang.System.Arraycopy(source, 0, destination, 0, length);
}
/// <summary>
/// Copy a range of elements from the front of the source array to the front of the destination array.
/// </summary>
/// <remarks>
/// The length should fit inside an int, otherwise an ArgumentOutOfRangeException will be thrown.
/// </remarks>
public static void Copy(Array source, Array destination, long length)
{
if (length > int.MaxValue) throw new ArgumentOutOfRangeException("length", "Dot42 support up to " + int.MaxValue);
Java.Lang.System.Arraycopy(source, 0, destination, 0, (int)length);
}
/// <summary>
/// Copy a range of elements from the specified index of the source array to the specified index of the destination array.
/// </summary>
public static void Copy(Array source, int sourceIndex, Array destination, int destinationIndex, int length)
{
Java.Lang.System.Arraycopy(source, sourceIndex, destination, destinationIndex, length);
}
/// <summary>
/// Copy a range of elements from the specified index of the source array to the specified index of the destination array.
/// </summary>
/// <remarks>
/// The sourceIndex, destinationIndex and length should fit inside an int, otherwise an ArgumentOutOfRangeException will be thrown.
/// </remarks>
public static void Copy(Array source, long sourceIndex, Array destination, long destinationIndex, long length)
{
if (sourceIndex > int.MaxValue) throw new ArgumentOutOfRangeException("sourceIndex", "Dot42 support up to " + int.MaxValue);
if (destinationIndex > int.MaxValue) throw new ArgumentOutOfRangeException("destinationIndex", "Dot42 support up to " + int.MaxValue);
if (length > int.MaxValue) throw new ArgumentOutOfRangeException("length", "Dot42 support up to " + int.MaxValue);
Java.Lang.System.Arraycopy(source, (int)sourceIndex, destination, (int)destinationIndex, (int)length);
}
/// <summary>
/// Search for the first occurrence of the given value in the given array.
/// </summary>
public static int IndexOf(Array array, object value)
{
var type = array.GetType();
if (type == typeof(sbyte[]))
{
var val = (sbyte)value;
var arr = (sbyte[])array;
int len = arr.Length;
for (int i = 0; i < len; ++i)
if (arr[i] == val) return i;
return -1;
}
if (type == typeof(char[]))
{
var val = (char)value;
var arr = (char[])array;
int len = arr.Length;
for (int i = 0; i < len; ++i)
if (arr[i] == val) return i;
return -1;
}
if (type == typeof(short[]))
{
var val = (short)value;
var arr = (short[])array;
int len = arr.Length;
for (int i = 0; i < len; ++i)
if (arr[i] == val) return i;
return -1;
}
if (type == typeof(int[]))
{
var val = (int)value;
var arr = (int[]) array;
int len = arr.Length;
for (int i = 0; i < len; ++i)
if (arr[i] == val) return i;
return -1;
}
if (type == typeof(long[]))
{
var val = (long)value;
var arr = (long[])array;
int len = arr.Length;
for (int i = 0; i < len; ++i)
if (arr[i] == val) return i;
return -1;
}
if (type == typeof(float[]))
{
var val = (float)value;
var arr = (float[])array;
int len = arr.Length;
for (int i = 0; i < len; ++i)
if (arr[i] == val) return i;
return -1;
}
if (type == typeof(double[]))
{
var val = (double)value;
var arr = (double[])array;
int len = arr.Length;
for (int i = 0; i < len; ++i)
if (arr[i] == val) return i;
return -1;
}
if (type == typeof(bool[]))
{
var val = (bool)value;
var arr = (bool[])array;
int len = arr.Length;
for (int i = 0; i < len; ++i)
if (arr[i] == val) return i;
return -1;
}
{
var arr = (object[])array;
int len = arr.Length;
for (int i = 0; i < len; ++i)
{
if (Equals(arr[i], value))
return i;
}
return -1;
}
}
/// <summary>
/// Gets an enumerator to enumerate over all elements of this array.
/// </summary>
public IEnumerator GetEnumerator()
{
return CompilerHelper.AsEnumerable(this).GetEnumerator();
}
/// <summary>
/// Gets the number of elements in this collection.
/// </summary>
int ICollection.Count
{
get { return Java.Lang.Reflect.Array.GetLength(this); }
}
public bool IsSynchronized { get { return false; } }
public object SyncRoot { get { return this; } }
/// <summary>
/// Copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index.
/// </summary>
public void CopyTo(Array array, int index)
{
Java.Lang.System.Arraycopy(this, 0, array, index, Length);
}
public void CopyTo(Array array, long index)
{
if (index > int.MaxValue) throw new NotSupportedException();
Java.Lang.System.Arraycopy(this, 0, array, (int)index, Length);
}
public bool IsFixedSize { get { return true; } }
public bool IsReadOnly { get { return false; } }
public object this[int index]
{
get { return GetValue(index); }
set { SetValue(value, index); }
}
public int Add(object element)
{
throw new NotSupportedException();
}
public void Clear()
{
Clear(this, 0, Length);
}
public bool Contains(object element)
{
return (IndexOf(this, element) >= 0);
}
public int IndexOf(object element)
{
return IndexOf(this, element);
}
public void Insert(int index, object element)
{
throw new NotSupportedException();
}
public void Remove(object element)
{
throw new NotSupportedException();
}
public void RemoveAt(int index)
{
throw new NotSupportedException();
}
public static void Reverse(int[] array)
{
var length = array.Length;
for (int i = 0; i < length / 2; i++)
{
int temp = array[i];
array[i] = array[length - i - 1];
array[length - i - 1] = temp;
}
}
public static void Reverse(byte[] array)
{
var length = array.Length;
for (int i = 0; i < length / 2; i++)
{
byte temp = array[i];
array[i] = array[length - i - 1];
array[length - i - 1] = temp;
}
}
public static void Reverse(sbyte[] array)
{
var length = array.Length;
for (int i = 0; i < length / 2; i++)
{
sbyte temp = array[i];
array[i] = array[length - i - 1];
array[length - i - 1] = temp;
}
}
public static void Reverse(bool[] array)
{
var length = array.Length;
for (int i = 0; i < length / 2; i++)
{
bool temp = array[i];
array[i] = array[length - i - 1];
array[length - i - 1] = temp;
}
}
public static void Reverse(char[] array)
{
var length = array.Length;
for (int i = 0; i < length / 2; i++)
{
char temp = array[i];
array[i] = array[length - i - 1];
array[length - i - 1] = temp;
}
}
public static void Reverse(short[] array)
{
var length = array.Length;
for (int i = 0; i < length / 2; i++)
{
short temp = array[i];
array[i] = array[length - i - 1];
array[length - i - 1] = temp;
}
}
public static void Reverse(ushort[] array)
{
var length = array.Length;
for (int i = 0; i < length / 2; i++)
{
ushort temp = array[i];
array[i] = array[length - i - 1];
array[length - i - 1] = temp;
}
}
public static void Reverse(long[] array)
{
var length = array.Length;
for (int i = 0; i < length / 2; i++)
{
long temp = array[i];
array[i] = array[length - i - 1];
array[length - i - 1] = temp;
}
}
public static void Reverse(ulong[] array)
{
var length = array.Length;
for (int i = 0; i < length / 2; i++)
{
ulong temp = array[i];
array[i] = array[length - i - 1];
array[length - i - 1] = temp;
}
}
public static void Reverse(float[] array)
{
var length = array.Length;
for (int i = 0; i < length / 2; i++)
{
float temp = array[i];
array[i] = array[length - i - 1];
array[length - i - 1] = temp;
}
}
public static void Reverse(double[] array)
{
var length = array.Length;
for (int i = 0; i < length / 2; i++)
{
double temp = array[i];
array[i] = array[length - i - 1];
array[length - i - 1] = temp;
}
}
public static void Reverse(object[] array)
{
var length = array.Length;
for (int i = 0; i < length / 2; i++)
{
object temp = array[i];
array[i] = array[length - i - 1];
array[length - i - 1] = temp;
}
}
/// <summary>
/// Sort the elements in the entire array.
/// </summary>
public void Sort()
{
Sort((IComparer)null);
}
/// <summary>
/// Sort the elements in the entire array.
/// </summary>
public void Sort(IComparer comparer)
{
comparer = comparer ?? Comparer.Default;
Java.Util.Arrays.Sort((object[])this, comparer);
}
/// <summary>
/// Sort the elements in the entire array.
/// </summary>
private void Sort(int index, int length, IComparer comparer)
{
comparer = comparer ?? Comparer.Default;
Java.Util.Arrays.Sort((object[])this, index, index + length, comparer);
}
/// <summary>
/// Sort the elements in the entire array.
/// </summary>
public static void Sort(Array array)
{
Sort(array, null);
}
/// <summary>
/// Sort the elements in the entire array.
/// </summary>
public static void Sort(Array array, IComparer comparer)
{
if (array == null) throw new ArgumentNullException("array");
array.Sort(comparer);
}
/// <summary>
/// Sort the elements in the entire array.
/// </summary>
public static void Sort(Array array, int index, int length, IComparer comparer)
{
if (array == null) throw new ArgumentNullException("array");
array.Sort(index, length, comparer);
}
/// <summary>
/// Clones the current array
/// </summary>
/// <returns></returns>
public Array Clone()
{
var sbyteArr = this as sbyte[];
if (sbyteArr != null) return Arrays.CopyOf(sbyteArr, Length);
var byteArr = this as byte[];
if (byteArr != null) return Arrays.CopyOf(byteArr, Length);
var boolArr = this as bool[];
if (boolArr != null) return Arrays.CopyOf(boolArr, Length);
var charArr = this as char[];
if (charArr != null) return Arrays.CopyOf(charArr, Length);
var shortArr = this as short[];
if (shortArr != null) return Arrays.CopyOf(shortArr, Length);
var intArr = this as int[];
if (intArr != null) return Arrays.CopyOf(intArr, Length);
var longArr = this as long[];
if (longArr != null) return Arrays.CopyOf(longArr, Length);
var floatArr = this as float[];
if (floatArr != null) return Arrays.CopyOf(floatArr, Length);
var doubleArr = this as double[];
if (doubleArr != null) return Arrays.CopyOf(doubleArr, Length);
return Arrays.CopyOf((object[])this, Length);
}
/// <summary>
/// Changes the number of elements of a one-dimensional array to the specified new size.
/// </summary>
public static void Resize<T>(ref T[] array,int newSize)
{
Arrays.CopyOf<T>(array, newSize);
}
/// <summary>
/// Get the number of elements in the specified dimension of the Array.
/// </summary>
public int GetLength(int dimension)
{
if (dimension == 0) return Length;
if (dimension >= 1)
{
var array = GetValue(0) as Array;
if (array != null) return array.GetLength(dimension-1);
}
throw new NotImplementedException("System.Array.GetLength");
}
// <summary>
// Tries to reconstruct the array rank.
// </summary>
public int Rank
{
get
{
int rank = 1;
var type = this.GetType();
while ((type = type.JavaGetComponentType()).IsArray)
rank += 1;
return rank;
}
}
public int GetLowerBound(int dimension)
{
return 0;
}
public int GetUpperBound(int dimension)
{
return GetLength(dimension) - 1;
}
public static Array CreateInstance(Type type, int length)
{
return (Array)Java.Lang.Reflect.Array.NewInstance(type, length);
}
/// <summary>
/// multidimensional arrays are not really supported.
/// </summary>
public static Array CreateInstance(Type type, int[] lengths)
{
return (Array)Java.Lang.Reflect.Array.NewInstance(type, lengths);
}
}
}
| |
//----------------------------------------------------------------------
// Copyright (c) Microsoft Open Technologies, Inc.
// All Rights Reserved
// Apache License 2.0
//
// 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;
#if !SILVERLIGHT
using System.Collections.Concurrent;
#endif
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace Microsoft.IdentityModel.Clients.ActiveDirectory
{
/// <summary>
/// Notification for certain token cache interactions during token acquisition.
/// </summary>
/// <param name="args"></param>
public delegate void TokenCacheNotification(TokenCacheNotificationArgs args);
/// <summary>
/// Token cache class used by <see cref="AuthenticationContext"/> to store access and refresh tokens.
/// </summary>
#if ADAL_NET
public class TokenCache
#else
public sealed partial class TokenCache
#endif
{
internal delegate Task<AuthenticationResult> RefreshAccessTokenAsync(AuthenticationResult result, string resource, ClientKey clientKey, CallState callState);
private const int SchemaVersion = 2;
private const string Delimiter = ":::";
private const string LocalSettingsContainerName = "ActiveDirectoryAuthenticationLibrary";
internal readonly IDictionary<TokenCacheKey, AuthenticationResult> tokenCacheDictionary;
// We do not want to return near expiry tokens, this is why we use this hard coded setting to refresh tokens which are close to expiration.
private const int ExpirationMarginInMinutes = 5;
private volatile bool hasStateChanged = false;
static TokenCache()
{
DefaultShared = new TokenCache();
#if !ADAL_NET
DefaultShared.BeforeAccess = DefaultTokenCache_BeforeAccess;
DefaultShared.AfterAccess = DefaultTokenCache_AfterAccess;
DefaultTokenCache_BeforeAccess(null);
#endif
}
/// <summary>
/// Default constructor.
/// </summary>
public TokenCache()
{
this.tokenCacheDictionary = new ConcurrentDictionary<TokenCacheKey, AuthenticationResult>();
}
/// <summary>
/// Constructor receiving state of the cache
/// </summary>
public TokenCache([ReadOnlyArray] byte[] state)
: this()
{
this.Deserialize(state);
}
/// <summary>
/// Static token cache shared by all instances of AuthenticationContext which do not explicitly pass a cache instance during construction.
/// </summary>
public static TokenCache DefaultShared { get; private set; }
/// <summary>
/// Notification method called before any library method accesses the cache.
/// </summary>
public TokenCacheNotification BeforeAccess { get; set; }
/// <summary>
/// Notification method called before any library method writes to the cache. This notification can be used to reload
/// the cache state from a row in database and lock that row. That database row can then be unlocked in <see cref="AfterAccess"/> notification.
/// </summary>
public TokenCacheNotification BeforeWrite { get; set; }
/// <summary>
/// Notification method called after any library method accesses the cache.
/// </summary>
public TokenCacheNotification AfterAccess { get; set; }
/// <summary>
/// Gets or sets the flag indicating whether cache state has changed. ADAL methods set this flag after any change. Caller application should reset
/// the flag after serializing and persisting the state of the cache.
/// </summary>
public bool HasStateChanged
{
get
{
return this.hasStateChanged;
}
set
{
this.hasStateChanged = value;
}
}
/// <summary>
/// Gets the nunmber of items in the cache.
/// </summary>
public int Count
{
get
{
return this.tokenCacheDictionary.Count;
}
}
/// <summary>
/// Serializes current state of the cache as a blob. Caller application can persist the blob and update the state of the cache later by
/// passing that blob back in constructor or by calling method Deserialize.
/// </summary>
/// <returns>Current state of the cache as a blob</returns>
public byte[] Serialize()
{
using (Stream stream = new MemoryStream())
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(SchemaVersion);
Logger.Information(null, "Serializing token cache with {0} items.", this.tokenCacheDictionary.Count);
writer.Write(this.tokenCacheDictionary.Count);
foreach (KeyValuePair<TokenCacheKey, AuthenticationResult> kvp in this.tokenCacheDictionary)
{
writer.Write(string.Format("{1}{0}{2}{0}{3}{0}{4}", Delimiter, kvp.Key.Authority, kvp.Key.Resource, kvp.Key.ClientId, (int)kvp.Key.TokenSubjectType));
writer.Write(kvp.Value.Serialize());
}
int length = (int)stream.Position;
stream.Position = 0;
BinaryReader reader = new BinaryReader(stream);
return reader.ReadBytes(length);
}
}
/// <summary>
/// Deserializes state of the cache. The state should be the blob received earlier by calling the method Serialize.
/// </summary>
/// <param name="state">State of the cache as a blob</param>
public void Deserialize([ReadOnlyArray] byte[] state)
{
if (state == null)
{
this.tokenCacheDictionary.Clear();
return;
}
using (Stream stream = new MemoryStream())
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(state);
writer.Flush();
stream.Position = 0;
BinaryReader reader = new BinaryReader(stream);
int schemaVersion = reader.ReadInt32();
if (schemaVersion != SchemaVersion)
{
Logger.Warning(null, "The version of the persistent state of the cache does not match the current schema, so skipping deserialization.");
return;
}
this.tokenCacheDictionary.Clear();
int count = reader.ReadInt32();
for (int n = 0; n < count; n++)
{
string keyString = reader.ReadString();
string[] kvpElements = keyString.Split(new[] { Delimiter }, StringSplitOptions.None);
AuthenticationResult result = AuthenticationResult.Deserialize(reader.ReadString());
TokenCacheKey key = new TokenCacheKey(kvpElements[0], kvpElements[1], kvpElements[2], (TokenSubjectType)int.Parse(kvpElements[3]), result.UserInfo);
this.tokenCacheDictionary.Add(key, result);
}
Logger.Information(null, "Deserialized {0} items to token cache.", count);
}
}
/// <summary>
/// Reads a copy of the list of all items in the cache.
/// </summary>
/// <returns>The items in the cache</returns>
#if ADAL_NET
public virtual IEnumerable<TokenCacheItem> ReadItems()
#else
public IEnumerable<TokenCacheItem> ReadItems()
#endif
{
TokenCacheNotificationArgs args = new TokenCacheNotificationArgs { TokenCache = this };
this.OnBeforeAccess(args);
List<TokenCacheItem> items = new List<TokenCacheItem>();
foreach (KeyValuePair<TokenCacheKey, AuthenticationResult> kvp in this.tokenCacheDictionary)
{
items.Add(new TokenCacheItem(kvp.Key, kvp.Value));
}
this.OnAfterAccess(args);
return items;
}
/// <summary>
/// Deletes an item from the cache.
/// </summary>
/// <param name="item">The item to delete from the cache</param>
#if ADAL_NET
public virtual void DeleteItem(TokenCacheItem item)
#else
public void DeleteItem(TokenCacheItem item)
#endif
{
if (item == null)
{
throw new ArgumentNullException("item");
}
TokenCacheNotificationArgs args = new TokenCacheNotificationArgs
{
TokenCache = this,
Resource = item.Resource,
ClientId = item.ClientId,
UniqueId = item.UniqueId,
DisplayableId = item.DisplayableId
};
this.OnBeforeAccess(args);
this.OnBeforeWrite(args);
TokenCacheKey toRemoveKey = this.tokenCacheDictionary.Keys.FirstOrDefault(item.Match);
if (toRemoveKey != null)
{
this.tokenCacheDictionary.Remove(toRemoveKey);
}
this.HasStateChanged = true;
this.OnAfterAccess(args);
}
/// <summary>
/// Clears the cache by deleting all the items. Note that if the cache is the default shared cache, clearing it would
/// impact all the instances of <see cref="AuthenticationContext"/> which share that cache.
/// </summary>
#if ADAL_NET
public virtual void Clear()
#else
public void Clear()
#endif
{
TokenCacheNotificationArgs args = new TokenCacheNotificationArgs { TokenCache = this };
this.OnBeforeAccess(args);
this.OnBeforeWrite(args);
this.tokenCacheDictionary.Clear();
this.HasStateChanged = true;
this.OnAfterAccess(args);
}
internal void OnAfterAccess(TokenCacheNotificationArgs args)
{
if (AfterAccess != null)
{
AfterAccess(args);
}
}
internal void OnBeforeAccess(TokenCacheNotificationArgs args)
{
if (BeforeAccess != null)
{
BeforeAccess(args);
}
}
internal void OnBeforeWrite(TokenCacheNotificationArgs args)
{
if (BeforeWrite != null)
{
BeforeWrite(args);
}
}
internal AuthenticationResult LoadFromCache(string authority, string resource, string clientId, TokenSubjectType subjectType, string uniqueId, string displayableId, CallState callState)
{
Logger.Verbose(callState, "Looking up cache for a token...");
AuthenticationResult result = null;
KeyValuePair<TokenCacheKey, AuthenticationResult>? kvp = this.LoadSingleItemFromCache(authority, resource, clientId, subjectType, uniqueId, displayableId, callState);
if (kvp.HasValue)
{
TokenCacheKey cacheKey = kvp.Value.Key;
result = kvp.Value.Value;
bool tokenNearExpiry = (result.ExpiresOn <= DateTime.UtcNow + TimeSpan.FromMinutes(ExpirationMarginInMinutes));
if (tokenNearExpiry)
{
result.AccessToken = null;
Logger.Verbose(callState, "An expired or near expiry token was found in the cache");
}
else if (!cacheKey.ResourceEquals(resource))
{
Logger.Verbose(callState,
string.Format("Multi resource refresh token for resource '{0}' will be used to acquire token for '{1}'", cacheKey.Resource, resource));
var newResult = new AuthenticationResult(null, null, result.RefreshToken, DateTimeOffset.MinValue);
newResult.UpdateTenantAndUserInfo(result.TenantId, result.IdToken, result.UserInfo);
result = newResult;
}
else
{
Logger.Verbose(callState, string.Format("{0} minutes left until token in cache expires", (result.ExpiresOn - DateTime.UtcNow).TotalMinutes));
}
if (result.AccessToken == null && result.RefreshToken == null)
{
this.tokenCacheDictionary.Remove(cacheKey);
Logger.Information(callState, "An old item was removed from the cache");
this.HasStateChanged = true;
result = null;
}
if (result != null)
{
Logger.Information(callState, "A matching item (access token or refresh token or both) was found in the cache");
}
}
else
{
Logger.Information(callState, "No matching token was found in the cache");
}
return result;
}
internal void StoreToCache(AuthenticationResult result, string authority, string resource, string clientId, TokenSubjectType subjectType, CallState callState)
{
Logger.Verbose(callState, "Storing token in the cache...");
string uniqueId = (result.UserInfo != null) ? result.UserInfo.UniqueId : null;
string displayableId = (result.UserInfo != null) ? result.UserInfo.DisplayableId : null;
this.OnBeforeWrite(new TokenCacheNotificationArgs
{
Resource = resource,
ClientId = clientId,
UniqueId = uniqueId,
DisplayableId = displayableId
});
TokenCacheKey tokenCacheKey = new TokenCacheKey(authority, resource, clientId, subjectType, result.UserInfo);
this.tokenCacheDictionary[tokenCacheKey] = result;
Logger.Verbose(callState, "An item was stored in the cache");
this.UpdateCachedMrrtRefreshTokens(result, authority, clientId, subjectType);
this.HasStateChanged = true;
}
private void UpdateCachedMrrtRefreshTokens(AuthenticationResult result, string authority, string clientId, TokenSubjectType subjectType)
{
if (result.UserInfo != null && result.IsMultipleResourceRefreshToken)
{
List<KeyValuePair<TokenCacheKey, AuthenticationResult>> mrrtItems =
this.QueryCache(authority, clientId, subjectType, result.UserInfo.UniqueId, result.UserInfo.DisplayableId).Where(p => p.Value.IsMultipleResourceRefreshToken).ToList();
foreach (KeyValuePair<TokenCacheKey, AuthenticationResult> mrrtItem in mrrtItems)
{
mrrtItem.Value.RefreshToken = result.RefreshToken;
}
}
}
private KeyValuePair<TokenCacheKey, AuthenticationResult>? LoadSingleItemFromCache(string authority, string resource, string clientId, TokenSubjectType subjectType, string uniqueId, string displayableId, CallState callState)
{
// First identify all potential tokens.
List<KeyValuePair<TokenCacheKey, AuthenticationResult>> items = this.QueryCache(authority, clientId, subjectType, uniqueId, displayableId);
List<KeyValuePair<TokenCacheKey, AuthenticationResult>> resourceSpecificItems =
items.Where(p => p.Key.ResourceEquals(resource)).ToList();
int resourceValuesCount = resourceSpecificItems.Count();
KeyValuePair<TokenCacheKey, AuthenticationResult>? returnValue = null;
if (resourceValuesCount == 1)
{
Logger.Information(callState, "An item matching the requested resource was found in the cache");
returnValue = resourceSpecificItems.First();
}
else if (resourceValuesCount == 0)
{
// There are no resource specific tokens. Choose any of the MRRT tokens if there are any.
List<KeyValuePair<TokenCacheKey, AuthenticationResult>> mrrtItems =
items.Where(p => p.Value.IsMultipleResourceRefreshToken).ToList();
if (mrrtItems.Any())
{
returnValue = mrrtItems.First();
Logger.Information(callState, "A Multi Resource Refresh Token for a different resource was found which can be used");
}
}
else
{
throw new AdalException(AdalError.MultipleTokensMatched);
}
return returnValue;
}
/// <summary>
/// Queries all values in the cache that meet the passed in values, plus the
/// authority value that this AuthorizationContext was created with. In every case passing
/// null results in a wildcard evaluation.
/// </summary>
private List<KeyValuePair<TokenCacheKey, AuthenticationResult>> QueryCache(string authority, string clientId, TokenSubjectType subjectType, string uniqueId, string displayableId)
{
return this.tokenCacheDictionary.Where(
p =>
p.Key.Authority == authority
&& (string.IsNullOrWhiteSpace(clientId) || p.Key.ClientIdEquals(clientId))
&& (string.IsNullOrWhiteSpace(uniqueId) || p.Key.UniqueId == uniqueId)
&& (string.IsNullOrWhiteSpace(displayableId) || p.Key.DisplayableIdEquals(displayableId))
&& p.Key.TokenSubjectType == subjectType).ToList();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Provides some basic access to some environment
** functionality.
**
**
============================================================*/
namespace System
{
using System.Buffers;
using System.IO;
using System.Security;
using System.Resources;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Configuration.Assemblies;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Diagnostics;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
public enum EnvironmentVariableTarget
{
Process = 0,
User = 1,
Machine = 2,
}
internal static partial class Environment
{
// Assume the following constants include the terminating '\0' - use <, not <=
private const int MaxEnvVariableValueLength = 32767; // maximum length for environment variable name and value
// System environment variables are stored in the registry, and have
// a size restriction that is separate from both normal environment
// variables and registry value name lengths, according to MSDN.
// MSDN doesn't detail whether the name is limited to 1024, or whether
// that includes the contents of the environment variable.
private const int MaxSystemEnvVariableLength = 1024;
private const int MaxUserEnvVariableLength = 255;
private const int MaxMachineNameLength = 256;
// Looks up the resource string value for key.
//
// if you change this method's signature then you must change the code that calls it
// in excep.cpp and probably you will have to visit mscorlib.h to add the new signature
// as well as metasig.h to create the new signature type
internal static String GetResourceStringLocal(String key)
{
return SR.GetResourceString(key);
}
/*==================================TickCount===================================
**Action: Gets the number of ticks since the system was started.
**Returns: The number of ticks since the system was started.
**Arguments: None
**Exceptions: None
==============================================================================*/
public static extern int TickCount
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
// Terminates this process with the given exit code.
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void _Exit(int exitCode);
public static void Exit(int exitCode)
{
_Exit(exitCode);
}
public static extern int ExitCode
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
set;
}
// Note: The CLR's Watson bucketization code looks at the caller of the FCALL method
// to assign blame for crashes. Don't mess with this, such as by making it call
// another managed helper method, unless you consult with some CLR Watson experts.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void FailFast(String message);
// This overload of FailFast will allow you to specify the exception object
// whose bucket details *could* be used when undergoing the failfast process.
// To be specific:
//
// 1) When invoked from within a managed EH clause (fault/finally/catch),
// if the exception object is preallocated, the runtime will try to find its buckets
// and use them. If the exception object is not preallocated, it will use the bucket
// details contained in the object (if any).
//
// 2) When invoked from outside the managed EH clauses (fault/finally/catch),
// if the exception object is preallocated, the runtime will use the callsite's
// IP for bucketing. If the exception object is not preallocated, it will use the bucket
// details contained in the object (if any).
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void FailFast(String message, Exception exception);
public static String ExpandEnvironmentVariables(String name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
{
return name;
}
int currentSize = 100;
StringBuilder blob = new StringBuilder(currentSize); // A somewhat reasonable default size
#if PLATFORM_UNIX // Win32Native.ExpandEnvironmentStrings isn't available
int lastPos = 0, pos;
while (lastPos < name.Length && (pos = name.IndexOf('%', lastPos + 1)) >= 0)
{
if (name[lastPos] == '%')
{
string key = name.Substring(lastPos + 1, pos - lastPos - 1);
string value = Environment.GetEnvironmentVariable(key);
if (value != null)
{
blob.Append(value);
lastPos = pos + 1;
continue;
}
}
blob.Append(name.Substring(lastPos, pos - lastPos));
lastPos = pos;
}
blob.Append(name.Substring(lastPos));
#else
int size;
blob.Length = 0;
size = Win32Native.ExpandEnvironmentStrings(name, blob, currentSize);
if (size == 0)
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
while (size > currentSize)
{
currentSize = size;
blob.Capacity = currentSize;
blob.Length = 0;
size = Win32Native.ExpandEnvironmentStrings(name, blob, currentSize);
if (size == 0)
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
#endif // PLATFORM_UNIX
return blob.ToString();
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern Int32 GetProcessorCount();
public static int ProcessorCount
{
get
{
return GetProcessorCount();
}
}
/*==============================GetCommandLineArgs==============================
**Action: Gets the command line and splits it appropriately to deal with whitespace,
** quotes, and escape characters.
**Returns: A string array containing your command line arguments.
**Arguments: None
**Exceptions: None.
==============================================================================*/
public static String[] GetCommandLineArgs()
{
/*
* There are multiple entry points to a hosted app.
* The host could use ::ExecuteAssembly() or ::CreateDelegate option
* ::ExecuteAssembly() -> In this particular case, the runtime invokes the main
method based on the arguments set by the host, and we return those arguments
*
* ::CreateDelegate() -> In this particular case, the host is asked to create a
* delegate based on the appDomain, assembly and methodDesc passed to it.
* which the caller uses to invoke the method. In this particular case we do not have
* any information on what arguments would be passed to the delegate.
* So our best bet is to simply use the commandLine that was used to invoke the process.
* in case it is present.
*/
if (s_CommandLineArgs != null)
return (string[])s_CommandLineArgs.Clone();
return GetCommandLineArgsNative();
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern String[] GetCommandLineArgsNative();
private static string[] s_CommandLineArgs = null;
private static void SetCommandLineArgs(string[] cmdLineArgs)
{
s_CommandLineArgs = cmdLineArgs;
}
private unsafe static char[] GetEnvironmentCharArray()
{
char[] block = null;
RuntimeHelpers.PrepareConstrainedRegions();
char* pStrings = null;
try
{
pStrings = Win32Native.GetEnvironmentStrings();
if (pStrings == null)
{
throw new OutOfMemoryException();
}
// Format for GetEnvironmentStrings is:
// [=HiddenVar=value\0]* [Variable=value\0]* \0
// See the description of Environment Blocks in MSDN's
// CreateProcess page (null-terminated array of null-terminated strings).
// Search for terminating \0\0 (two unicode \0's).
char* p = pStrings;
while (!(*p == '\0' && *(p + 1) == '\0'))
p++;
int len = (int)(p - pStrings + 1);
block = new char[len];
fixed (char* pBlock = block)
string.wstrcpy(pBlock, pStrings, len);
}
finally
{
if (pStrings != null)
Win32Native.FreeEnvironmentStrings(pStrings);
}
return block;
}
/*===================================NewLine====================================
**Action: A property which returns the appropriate newline string for the given
** platform.
**Returns: \r\n on Win32.
**Arguments: None.
**Exceptions: None.
==============================================================================*/
public static String NewLine
{
get
{
#if PLATFORM_WINDOWS
return "\r\n";
#else
return "\n";
#endif // PLATFORM_WINDOWS
}
}
/*===================================Version====================================
**Action: Returns the COM+ version struct, describing the build number.
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
public static Version Version
{
get
{
// Previously this represented the File version of mscorlib.dll. Many other libraries in the framework and outside took dependencies on the first three parts of this version
// remaining constant throughout 4.x. From 4.0 to 4.5.2 this was fine since the file version only incremented the last part.Starting with 4.6 we switched to a file versioning
// scheme that matched the product version. In order to preserve compatibility with existing libraries, this needs to be hard-coded.
return new Version(4, 0, 30319, 42000);
}
}
#if !FEATURE_PAL
private static Lazy<bool> s_IsWindows8OrAbove = new Lazy<bool>(() =>
{
ulong conditionMask = Win32Native.VerSetConditionMask(0, Win32Native.VER_MAJORVERSION, Win32Native.VER_GREATER_EQUAL);
conditionMask = Win32Native.VerSetConditionMask(conditionMask, Win32Native.VER_MINORVERSION, Win32Native.VER_GREATER_EQUAL);
conditionMask = Win32Native.VerSetConditionMask(conditionMask, Win32Native.VER_SERVICEPACKMAJOR, Win32Native.VER_GREATER_EQUAL);
conditionMask = Win32Native.VerSetConditionMask(conditionMask, Win32Native.VER_SERVICEPACKMINOR, Win32Native.VER_GREATER_EQUAL);
// Windows 8 version is 6.2
var version = new Win32Native.OSVERSIONINFOEX { MajorVersion = 6, MinorVersion = 2, ServicePackMajor = 0, ServicePackMinor = 0 };
return Win32Native.VerifyVersionInfoW(version,
Win32Native.VER_MAJORVERSION | Win32Native.VER_MINORVERSION | Win32Native.VER_SERVICEPACKMAJOR | Win32Native.VER_SERVICEPACKMINOR,
conditionMask);
});
internal static bool IsWindows8OrAbove => s_IsWindows8OrAbove.Value;
#endif
#if FEATURE_COMINTEROP
// Does the current version of Windows have Windows Runtime suppport?
private static Lazy<bool> s_IsWinRTSupported = new Lazy<bool>(() =>
{
return WinRTSupported();
});
internal static bool IsWinRTSupported => s_IsWinRTSupported.Value;
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool WinRTSupported();
#endif // FEATURE_COMINTEROP
/*==================================StackTrace==================================
**Action:
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
public static String StackTrace
{
[MethodImpl(MethodImplOptions.NoInlining)] // Prevent inlining from affecting where the stacktrace starts
get
{
return Internal.Runtime.Augments.EnvironmentAugments.StackTrace;
}
}
internal static String GetStackTrace(Exception e, bool needFileInfo)
{
// Note: Setting needFileInfo to true will start up COM and set our
// apartment state. Try to not call this when passing "true"
// before the EE's ExecuteMainMethod has had a chance to set up the
// apartment state. --
StackTrace st;
if (e == null)
st = new StackTrace(needFileInfo);
else
st = new StackTrace(e, needFileInfo);
// Do no include a trailing newline for backwards compatibility
return st.ToString(System.Diagnostics.StackTrace.TraceFormat.Normal);
}
public static extern bool HasShutdownStarted
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
internal static bool UserInteractive
{
get
{
return true;
}
}
public static int CurrentManagedThreadId
{
get
{
return Thread.CurrentThread.ManagedThreadId;
}
}
internal static extern int CurrentProcessorNumber
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
// The upper bits of t_executionIdCache are the executionId. The lower bits of
// the t_executionIdCache are counting down to get it periodically refreshed.
// TODO: Consider flushing the executionIdCache on Wait operations or similar
// actions that are likely to result in changing the executing core
[ThreadStatic]
private static int t_executionIdCache;
private const int ExecutionIdCacheShift = 16;
private const int ExecutionIdCacheCountDownMask = (1 << ExecutionIdCacheShift) - 1;
private const int ExecutionIdRefreshRate = 5000;
private static int RefreshExecutionId()
{
int executionId = CurrentProcessorNumber;
// On Unix, CurrentProcessorNumber is implemented in terms of sched_getcpu, which
// doesn't exist on all platforms. On those it doesn't exist on, GetCurrentProcessorNumber
// returns -1. As a fallback in that case and to spread the threads across the buckets
// by default, we use the current managed thread ID as a proxy.
if (executionId < 0) executionId = Environment.CurrentManagedThreadId;
Debug.Assert(ExecutionIdRefreshRate <= ExecutionIdCacheCountDownMask);
// Mask with Int32.MaxValue to ensure the execution Id is not negative
t_executionIdCache = ((executionId << ExecutionIdCacheShift) & Int32.MaxValue) | ExecutionIdRefreshRate;
return executionId;
}
// Cached processor number used as a hint for which per-core stack to access. It is periodically
// refreshed to trail the actual thread core affinity.
internal static int CurrentExecutionId
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
int executionIdCache = t_executionIdCache--;
if ((executionIdCache & ExecutionIdCacheCountDownMask) == 0)
return RefreshExecutionId();
return (executionIdCache >> ExecutionIdCacheShift);
}
}
public static string GetEnvironmentVariable(string variable)
{
if (variable == null)
{
throw new ArgumentNullException(nameof(variable));
}
// separated from the EnvironmentVariableTarget overload to help with tree shaking in common case
return GetEnvironmentVariableCore(variable);
}
internal static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target)
{
if (variable == null)
{
throw new ArgumentNullException(nameof(variable));
}
ValidateTarget(target);
return GetEnvironmentVariableCore(variable, target);
}
public static void SetEnvironmentVariable(string variable, string value)
{
ValidateVariableAndValue(variable, ref value);
// separated from the EnvironmentVariableTarget overload to help with tree shaking in common case
SetEnvironmentVariableCore(variable, value);
}
internal static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target)
{
ValidateVariableAndValue(variable, ref value);
ValidateTarget(target);
SetEnvironmentVariableCore(variable, value, target);
}
private static void ValidateVariableAndValue(string variable, ref string value)
{
const int MaxEnvVariableValueLength = 32767;
if (variable == null)
{
throw new ArgumentNullException(nameof(variable));
}
if (variable.Length == 0)
{
throw new ArgumentException(SR.Argument_StringZeroLength, nameof(variable));
}
if (variable[0] == '\0')
{
throw new ArgumentException(SR.Argument_StringFirstCharIsZero, nameof(variable));
}
if (variable.Length >= MaxEnvVariableValueLength)
{
throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(variable));
}
if (variable.IndexOf('=') != -1)
{
throw new ArgumentException(SR.Argument_IllegalEnvVarName, nameof(variable));
}
if (string.IsNullOrEmpty(value) || value[0] == '\0')
{
// Explicitly null out value if it's empty
value = null;
}
else if (value.Length >= MaxEnvVariableValueLength)
{
throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(value));
}
}
private static void ValidateTarget(EnvironmentVariableTarget target)
{
if (target != EnvironmentVariableTarget.Process &&
target != EnvironmentVariableTarget.Machine &&
target != EnvironmentVariableTarget.User)
{
throw new ArgumentOutOfRangeException(nameof(target), target, SR.Format(SR.Arg_EnumIllegalVal, target));
}
}
private static string GetEnvironmentVariableCore(string variable)
{
Span<char> buffer = stackalloc char[128]; // A somewhat reasonable default size
return GetEnvironmentVariableCoreHelper(variable, buffer);
}
private static string GetEnvironmentVariableCoreHelper(string variable, Span<char> buffer)
{
int requiredSize = Win32Native.GetEnvironmentVariable(variable, buffer);
if (requiredSize == 0 && Marshal.GetLastWin32Error() == Win32Native.ERROR_ENVVAR_NOT_FOUND)
{
return null;
}
if (requiredSize > buffer.Length)
{
char[] chars = ArrayPool<char>.Shared.Rent(requiredSize);
try
{
return GetEnvironmentVariableCoreHelper(variable, chars);
}
finally
{
ArrayPool<char>.Shared.Return(chars);
}
}
return new string(buffer.Slice(0, requiredSize));
}
private static string GetEnvironmentVariableCore(string variable, EnvironmentVariableTarget target)
{
if (target == EnvironmentVariableTarget.Process)
return GetEnvironmentVariableCore(variable);
#if FEATURE_WIN32_REGISTRY
if (AppDomain.IsAppXModel())
#endif
{
return null;
}
#if FEATURE_WIN32_REGISTRY
RegistryKey baseKey;
string keyName;
if (target == EnvironmentVariableTarget.Machine)
{
baseKey = Registry.LocalMachine;
keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
}
else if (target == EnvironmentVariableTarget.User)
{
baseKey = Registry.CurrentUser;
keyName = "Environment";
}
else
{
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)target));
}
using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false))
{
return environmentKey?.GetValue(variable) as string;
}
#endif
}
internal static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariables()
{
// Format for GetEnvironmentStrings is:
// (=HiddenVar=value\0 | Variable=value\0)* \0
// See the description of Environment Blocks in MSDN's
// CreateProcess page (null-terminated array of null-terminated strings).
// Note the =HiddenVar's aren't always at the beginning.
// Copy strings out, parsing into pairs and inserting into the table.
// The first few environment variable entries start with an '='.
// The current working directory of every drive (except for those drives
// you haven't cd'ed into in your DOS window) are stored in the
// environment block (as =C:=pwd) and the program's exit code is
// as well (=ExitCode=00000000).
char[] block = GetEnvironmentCharArray();
for (int i = 0; i < block.Length; i++)
{
int startKey = i;
// Skip to key. On some old OS, the environment block can be corrupted.
// Some will not have '=', so we need to check for '\0'.
while (block[i] != '=' && block[i] != '\0')
i++;
if (block[i] == '\0')
continue;
// Skip over environment variables starting with '='
if (i - startKey == 0)
{
while (block[i] != 0)
i++;
continue;
}
string key = new string(block, startKey, i - startKey);
i++; // skip over '='
int startValue = i;
while (block[i] != 0)
i++; // Read to end of this entry
string value = new string(block, startValue, i - startValue); // skip over 0 handled by for loop's i++
yield return new KeyValuePair<string, string>(key, value);
}
}
internal static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariables(EnvironmentVariableTarget target)
{
if (target == EnvironmentVariableTarget.Process)
return EnumerateEnvironmentVariables();
return EnumerateEnvironmentVariablesFromRegistry(target);
}
internal static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariablesFromRegistry(EnvironmentVariableTarget target)
{
#if FEATURE_WIN32_REGISTRY
if (AppDomain.IsAppXModel())
#endif
{
// Without registry support we have nothing to return
ValidateTarget(target);
yield break;
}
#if FEATURE_WIN32_REGISTRY
RegistryKey baseKey;
string keyName;
if (target == EnvironmentVariableTarget.Machine)
{
baseKey = Registry.LocalMachine;
keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
}
else if (target == EnvironmentVariableTarget.User)
{
baseKey = Registry.CurrentUser;
keyName = @"Environment";
}
else
{
throw new ArgumentOutOfRangeException(nameof(target), target, SR.Format(SR.Arg_EnumIllegalVal, target));
}
using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false))
{
if (environmentKey != null)
{
foreach (string name in environmentKey.GetValueNames())
{
string value = environmentKey.GetValue(name, "").ToString();
yield return new KeyValuePair<string, string>(name, value);
}
}
}
#endif // FEATURE_WIN32_REGISTRY
}
private static void SetEnvironmentVariableCore(string variable, string value)
{
// explicitly null out value if is the empty string.
if (string.IsNullOrEmpty(value) || value[0] == '\0')
value = null;
if (!Win32Native.SetEnvironmentVariable(variable, value))
{
int errorCode = Marshal.GetLastWin32Error();
switch (errorCode)
{
case Win32Native.ERROR_ENVVAR_NOT_FOUND:
// Allow user to try to clear a environment variable
return;
case Win32Native.ERROR_FILENAME_EXCED_RANGE:
// The error message from Win32 is "The filename or extension is too long",
// which is not accurate.
throw new ArgumentException(SR.Format(SR.Argument_LongEnvVarValue));
default:
throw new ArgumentException(Interop.Kernel32.GetMessage(errorCode));
}
}
}
private static void SetEnvironmentVariableCore(string variable, string value, EnvironmentVariableTarget target)
{
if (target == EnvironmentVariableTarget.Process)
{
SetEnvironmentVariableCore(variable, value);
return;
}
#if FEATURE_WIN32_REGISTRY
if (AppDomain.IsAppXModel())
#endif
{
// other targets ignored
return;
}
#if FEATURE_WIN32_REGISTRY
// explicitly null out value if is the empty string.
if (string.IsNullOrEmpty(value) || value[0] == '\0')
value = null;
RegistryKey baseKey;
string keyName;
if (target == EnvironmentVariableTarget.Machine)
{
baseKey = Registry.LocalMachine;
keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
}
else if (target == EnvironmentVariableTarget.User)
{
// User-wide environment variables stored in the registry are limited to 255 chars for the environment variable name.
const int MaxUserEnvVariableLength = 255;
if (variable.Length >= MaxUserEnvVariableLength)
{
throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(variable));
}
baseKey = Registry.CurrentUser;
keyName = "Environment";
}
else
{
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)target));
}
using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: true))
{
if (environmentKey != null)
{
if (value == null)
{
environmentKey.DeleteValue(variable, throwOnMissingValue: false);
}
else
{
environmentKey.SetValue(variable, value);
}
}
}
// send a WM_SETTINGCHANGE message to all windows
IntPtr r = Interop.User32.SendMessageTimeout(new IntPtr(Interop.User32.HWND_BROADCAST),
Interop.User32.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero);
Debug.Assert(r != IntPtr.Zero, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error());
#endif // FEATURE_WIN32_REGISTRY
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex001.complex001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex001.complex001;
// <Title>Derived generic types</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public class MyClass<T>
where T : List<object>
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<List<object>> mc = new MyClass<List<dynamic>>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex002.complex002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex002.complex002;
// <Title>Derived generic types</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public class MyClass<T>
where T : List<object>
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<List<dynamic>> mc = new MyClass<List<dynamic>>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex008.complex008
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex008.complex008;
// <Title>Generic constraints</Title>
// <Description> Trying to pass in int and dynamic as type parameters used to give an error saying that there is no boxing conversion from int to dynamic
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public class M
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int rez = M1<int, dynamic>();
rez += M2<int, dynamic>();
int i = 4;
dynamic d = 4;
// Simple call let Runtime decide d's type which is 'int' instead of 'object'
rez += M3(i, d);
return rez > 0 ? 1 : 0;
}
public static int M3<T, S>(T t, S s) where T : S
{
// if (typeof(T) != typeof(int) || typeof(S) != typeof(object)) return 1;
if (typeof(T) != typeof(int) || typeof(S) != typeof(int))
return 1;
return 0;
}
public static int M2<T, S>() where T : struct, S
{
if (typeof(T) != typeof(int) || typeof(S) != typeof(object))
return 1;
return 0;
}
public static int M1<T, S>() where T : S
{
if (typeof(T) != typeof(int) || typeof(S) != typeof(object))
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex009.complex009
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex009.complex009;
// <Title>Derived generic types</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic c = new C();
c.NakedGen1<GenDerClass<int>, GenBaseClass<int>>();
c.NakedGen1<GenDerClass<Struct>, GenBaseClass<Struct>>();
return 0;
}
}
public class C
{
public void NakedGen1<T, U>() where T : U
{
}
}
public struct Struct
{
}
public class GenBaseClass<T>
{
}
public class GenDerClass<T> : GenBaseClass<T>
{
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex010.complex010
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex010.complex010;
// <Title>Derived generic types</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Base<T>
{
public virtual void Foo<G>() where G : T, new()
{
}
}
public class DerivedNullableOfInt : Base<int?>
{
public override void Foo<G>()
{
dynamic d = new G();
d = 4;
d.ToString();
Program.Status = 1;
}
}
public class Program
{
public static int Status = 0;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic d = new DerivedNullableOfInt();
d.Foo<int?>();
if (Program.Status == 1)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex011.complex011
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex011.complex011;
// <Title>Derived generic types</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Base<T>
{
public virtual IEnumerable<G> Foo<G>() where G : T, new()
{
return null;
}
}
public class DerivedNullableOfInt : Base<int?>
{
public override IEnumerable<G> Foo<G>()
{
yield return new G();
}
}
public class Program
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic d = new DerivedNullableOfInt();
var x = d.Foo<int?>();
return x != null ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex012.complex012
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex012.complex012;
// <Title>Derived generic types</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Base<T>
{
public virtual int Foo<G>() where G : T, new()
{
return -1;
}
}
public class DerivedNullableOfInt : Base<int?>
{
public override int Foo<G>()
{
int i = 3;
Func<G, int> f = x => i;
return f(new G());
}
}
public class Program
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic d = new DerivedNullableOfInt();
var x = d.Foo<int?>();
if (x != null)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple001.simple001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple001.simple001;
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class MyClass<T>
where T : class
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<object> mc = new MyClass<dynamic>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple002.simple002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple002.simple002;
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class MyClass<T>
where T : class
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<dynamic> mc = new MyClass<object>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple006.simple006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple006.simple006;
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class MyClass<T>
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<object> mc = new MyClass<dynamic>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple008.simple008
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple008.simple008;
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class MyClass<T, U>
where T : U
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<dynamic, object> mc = new MyClass<dynamic, object>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple009.simple009
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple009.simple009;
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class MyClass<T>
where T : class
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<dynamic> mc = new MyClass<dynamic>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple012.simple012
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple012.simple012;
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class MyClass<T, U>
where T : U
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<object, object> mc = new MyClass<dynamic, dynamic>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple013.simple013
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple013.simple013;
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class MyClass<T, U>
where T : U
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<dynamic, object> mc = new MyClass<object, dynamic>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple015.simple015
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple015.simple015;
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class MyClass<T>
where T : new()
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<dynamic> mc = new MyClass<dynamic>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple016.simple016
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple016.simple016;
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class MyClass<T>
where T : new()
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<object> mc = new MyClass<dynamic>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple018.simple018
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple018.simple018;
// <Title>Generic constraints</Title>
// <Description></Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic x = new Test();
x.Bar<string, dynamic>();
var y = new Test();
y.Bar<string, dynamic>(); // used to be error CS0311:
// The type 'string' cannot be used as type parameter 'T' in the generic type or method 'A.Foo<T,S>()'.
// There is no implicit reference conversion from 'string' to '::dynamic'.
return 0;
}
public void Bar<T, S>() where T : S
{
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple019.simple019
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple019.simple019;
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class B
{
public static int Status = 1;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic x = new B();
x.Foo<int>();
return B.Status;
}
public void Foo<T, S>() where T : S
{
B.Status = 1;
}
public void Foo<T>()
{
B.Status = 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple020.simple020
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple020.simple020;
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class B
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic x = new B();
try
{
x.Foo(); // Unexpected NullReferenceException
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "B.Foo<T>()"))
return 0;
}
return 1;
}
public void Foo<T>()
{
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple021.simple021
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple021.simple021;
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class B
{
public static int Status = 1;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic x = new B();
x.Foo<int, int>();
return B.Status;
}
public void Foo<T, S>() where T : S // The constraint is important part
{
B.Status = 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple022.simple022
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple022.simple022;
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class B
{
public static int Status = 1;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic x = new B();
try
{
x.Foo<int>(); // Unexpected NullReferenceException
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArity, e.Message, "B.Foo<T,S>()", ErrorVerifier.GetErrorElement(ErrorElementId.SK_METHOD), "2"))
B.Status = 0;
}
return B.Status;
}
public void Foo<T, S>() where T : S
{
B.Status = 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference001.typeinference001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference001.typeinference001;
// <Title>Generic Type Inference</Title>
// <Description> Runtime type inference succeeds in cases where it should fail
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class C
{
public static void M<T>(T x, T y)
{
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
string x = "string";
dynamic y = 7;
try
{
C.M(x, y);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "C.M<T>(T, T)"))
return 0;
}
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference002.typeinference002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference002.typeinference002;
// <Title>Generic Type Inference</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class A
{
public void M<T>(T x, T y)
{
}
}
public class TestClass
{
[Fact]
public void RunTest()
{
Test.DynamicCSharpRunTest();
}
}
public struct Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var vv = new A();
dynamic vd = new A();
int ret = 0;
// dyn (null) & string -> string
dynamic dynPara = null;
string str = "QC";
try
{
vv.M(dynPara, str);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("1)" + ex);
ret++; // Fail
}
try
{
vd.M(dynPara, str);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("2)" + ex);
ret++; // Fail
}
// dyn (null) & class
dynPara = null;
var a = new A();
try
{
vv.M(dynPara, a);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("3)" + ex);
ret++; // Fail
}
try
{
vd.M(a, dynPara);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("4)" + ex);
ret++; // Fail
}
// dyn (class), dyn (null)
dynPara = new A();
dynamic dynP2 = null;
try
{
vv.M(dynPara, dynP2);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("5)" + ex);
ret++; // Fail
}
try
{
vd.M(dynP2, dynPara);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("6)" + ex);
ret++; // Fail
}
return 0 == ret ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference003.typeinference003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference003.typeinference003;
// <Title>Generic Type Inference</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public struct S
{
public void M<T>(T x, T y)
{
}
}
public struct Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var vv = new S();
dynamic vd = new S();
int ret = 6;
// dyn (int), string (null)
dynamic dynPara = 100;
string str = null;
try
{
vv.M(str, dynPara);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "S.M<T>(T, T)"))
ret--; // Pass
}
try
{
vd.M(dynPara, str);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "S.M<T>(T, T)"))
ret--; // Pass
}
// dyn (null), int -\-> int?
dynPara = null;
int n = 0;
try
{
vv.M(dynPara, n);
System.Console.WriteLine("3) no ex");
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "S.M<int>(int, int)"))
ret--; // Pass
}
try
{
vd.M(n, dynPara);
System.Console.WriteLine("4) no ex");
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "S.M<int>(int, int)"))
ret--; // Pass
}
// dyn->struct, dyn->null
dynPara = new Test();
dynamic dynP2 = null;
try
{
vv.M(dynPara, dynP2);
System.Console.WriteLine("5) no ex");
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "S.M<Test>(Test, Test)"))
ret--; // Pass
}
try
{
vd.M(dynPara, dynP2);
System.Console.WriteLine("6) no ex");
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "S.M<Test>(Test, Test)"))
ret--; // Pass
}
return 0 == ret ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference004.typeinference004
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference004.typeinference004;
// <Title>Generic Type Inference</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public void M<T>(T x, T y, T z)
{
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var obj = new Test();
dynamic dobj = new Test();
int ret = 0;
// -> object
dynamic d = 11;
string str = "string";
object o = null;
try
{
obj.M(d, str, o);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("1)" + ex);
ret++; // Fail
}
try
{
dobj.M(o, d, str);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("2)" + ex);
ret++; // Fail
}
// -> int?
d = null;
int n1 = 111111;
int? n2 = 11;
try
{
obj.M(n1, d, n2);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("3)" + ex);
ret++; // Fail
}
try
{
dobj.M(n1, n2, d);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("4)" + ex);
ret++; // Fail
}
// -> long
d = 0;
var v = -50000000000; // long
byte b = 1;
try
{
obj.M(d, v, b);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("5)" + ex);
ret++; // Fail
}
try
{
dobj.M(b, d, v);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("6)" + ex);
ret++; // Fail
}
// ->
d = null;
dynamic d2 = 0;
long? sb = null; // failed for (s)byte, (u)short, etc.
try
{
obj.M<long?>(d, sb, d2);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("7)" + ex);
ret++; // Fail
}
try
{
dobj.M<long?>(sb, d2, d);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("8)" + ex);
ret++; // Fail
}
return 0 == ret ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference005.typeinference005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference005.typeinference005;
// <Title>Generic Type Inference</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public struct Test
{
public void M<T>(T x, T y, T z)
{
}
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var vv = new Test();
dynamic vd = new Test();
int ret = 6;
string x = "string";
int? y = null;
dynamic z = 7;
try
{
vv.M(x, y, z);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "Test.M<T>(T, T, T)"))
ret--; // Pass
}
try
{
vd.M(x, z, y);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "Test.M<T>(T, T, T)"))
ret--; // Pass
}
Test? o1 = null;
char ch = '\0';
z = "";
try
{
vv.M(z, o1, ch);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "Test.M<T>(T, T, T)"))
ret--; // Pass
}
try
{
vd.M(ch, z, o1);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "Test.M<T>(T, T, T)"))
ret--; // Pass
}
dynamic z2 = 100;
z = null;
try
{
vv.M(z2, ch, z);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Test.M<int>(int, int, int)"))
ret--; // Pass
}
try
{
vd.M(z, z2, ch);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Test.M<int>(int, int, int)"))
ret--; // Pass
}
return 0 == ret ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference006.typeinference006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference006.typeinference006;
// <Title>Generic Type Inference</Title>
// <Description> We used to give compiler errors in these cases
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class A
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int rez = 0;
dynamic x = 1;
rez += Bar1(1, x);
rez += Bar1((dynamic)1, x);
dynamic d = new List<List<int>>();
rez += Bar2(d, 1);
rez += Bar2(d, (dynamic)1);
var l = new List<List<int>>();
rez += Bar2(l, x);
rez += Bar3(1, x, x);
rez += Bar3(1, 1, x);
var cls = new C<int>();
rez += cls.Foo(1, x);
rez += cls.Foo(x, 1);
rez += Bar4(x, 1);
rez += Bar4(1, x);
return rez;
}
public static int Bar1<T, S>(T x, S y) where T : IComparable<S>
{
return 0;
}
public static int Bar2<T, S>(T t, S s) where T : IList<List<S>>
{
return 0;
}
public static int Bar3<T, U, V>(T t, U u, V v) where T : U where U : IComparable<V>
{
return 0;
}
public static int Bar4<T, U>(T t, IComparable<U> u) where T : IComparable<U>
{
return 0;
}
}
public class C<T>
{
public int Foo<U>(T t, U u) where U : IComparable<T>
{
return 0;
}
}
// </Code>
}
| |
/*
* 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>
/// VM Protection Policy
/// First published in XenServer 5.6 FP1.
/// </summary>
public partial class VMPP : XenObject<VMPP>
{
public VMPP()
{
}
public VMPP(string uuid,
string name_label,
string name_description,
bool is_policy_enabled,
vmpp_backup_type backup_type,
long backup_retention_value,
vmpp_backup_frequency backup_frequency,
Dictionary<string, string> backup_schedule,
bool is_backup_running,
DateTime backup_last_run_time,
vmpp_archive_target_type archive_target_type,
Dictionary<string, string> archive_target_config,
vmpp_archive_frequency archive_frequency,
Dictionary<string, string> archive_schedule,
bool is_archive_running,
DateTime archive_last_run_time,
List<XenRef<VM>> VMs,
bool is_alarm_enabled,
Dictionary<string, string> alarm_config,
string[] recent_alerts)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.is_policy_enabled = is_policy_enabled;
this.backup_type = backup_type;
this.backup_retention_value = backup_retention_value;
this.backup_frequency = backup_frequency;
this.backup_schedule = backup_schedule;
this.is_backup_running = is_backup_running;
this.backup_last_run_time = backup_last_run_time;
this.archive_target_type = archive_target_type;
this.archive_target_config = archive_target_config;
this.archive_frequency = archive_frequency;
this.archive_schedule = archive_schedule;
this.is_archive_running = is_archive_running;
this.archive_last_run_time = archive_last_run_time;
this.VMs = VMs;
this.is_alarm_enabled = is_alarm_enabled;
this.alarm_config = alarm_config;
this.recent_alerts = recent_alerts;
}
/// <summary>
/// Creates a new VMPP from a Proxy_VMPP.
/// </summary>
/// <param name="proxy"></param>
public VMPP(Proxy_VMPP proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(VMPP update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
is_policy_enabled = update.is_policy_enabled;
backup_type = update.backup_type;
backup_retention_value = update.backup_retention_value;
backup_frequency = update.backup_frequency;
backup_schedule = update.backup_schedule;
is_backup_running = update.is_backup_running;
backup_last_run_time = update.backup_last_run_time;
archive_target_type = update.archive_target_type;
archive_target_config = update.archive_target_config;
archive_frequency = update.archive_frequency;
archive_schedule = update.archive_schedule;
is_archive_running = update.is_archive_running;
archive_last_run_time = update.archive_last_run_time;
VMs = update.VMs;
is_alarm_enabled = update.is_alarm_enabled;
alarm_config = update.alarm_config;
recent_alerts = update.recent_alerts;
}
internal void UpdateFromProxy(Proxy_VMPP proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
name_label = proxy.name_label == null ? null : (string)proxy.name_label;
name_description = proxy.name_description == null ? null : (string)proxy.name_description;
is_policy_enabled = (bool)proxy.is_policy_enabled;
backup_type = proxy.backup_type == null ? (vmpp_backup_type) 0 : (vmpp_backup_type)Helper.EnumParseDefault(typeof(vmpp_backup_type), (string)proxy.backup_type);
backup_retention_value = proxy.backup_retention_value == null ? 0 : long.Parse((string)proxy.backup_retention_value);
backup_frequency = proxy.backup_frequency == null ? (vmpp_backup_frequency) 0 : (vmpp_backup_frequency)Helper.EnumParseDefault(typeof(vmpp_backup_frequency), (string)proxy.backup_frequency);
backup_schedule = proxy.backup_schedule == null ? null : Maps.convert_from_proxy_string_string(proxy.backup_schedule);
is_backup_running = (bool)proxy.is_backup_running;
backup_last_run_time = proxy.backup_last_run_time;
archive_target_type = proxy.archive_target_type == null ? (vmpp_archive_target_type) 0 : (vmpp_archive_target_type)Helper.EnumParseDefault(typeof(vmpp_archive_target_type), (string)proxy.archive_target_type);
archive_target_config = proxy.archive_target_config == null ? null : Maps.convert_from_proxy_string_string(proxy.archive_target_config);
archive_frequency = proxy.archive_frequency == null ? (vmpp_archive_frequency) 0 : (vmpp_archive_frequency)Helper.EnumParseDefault(typeof(vmpp_archive_frequency), (string)proxy.archive_frequency);
archive_schedule = proxy.archive_schedule == null ? null : Maps.convert_from_proxy_string_string(proxy.archive_schedule);
is_archive_running = (bool)proxy.is_archive_running;
archive_last_run_time = proxy.archive_last_run_time;
VMs = proxy.VMs == null ? null : XenRef<VM>.Create(proxy.VMs);
is_alarm_enabled = (bool)proxy.is_alarm_enabled;
alarm_config = proxy.alarm_config == null ? null : Maps.convert_from_proxy_string_string(proxy.alarm_config);
recent_alerts = proxy.recent_alerts == null ? new string[] {} : (string [])proxy.recent_alerts;
}
public Proxy_VMPP ToProxy()
{
Proxy_VMPP result_ = new Proxy_VMPP();
result_.uuid = (uuid != null) ? uuid : "";
result_.name_label = (name_label != null) ? name_label : "";
result_.name_description = (name_description != null) ? name_description : "";
result_.is_policy_enabled = is_policy_enabled;
result_.backup_type = vmpp_backup_type_helper.ToString(backup_type);
result_.backup_retention_value = backup_retention_value.ToString();
result_.backup_frequency = vmpp_backup_frequency_helper.ToString(backup_frequency);
result_.backup_schedule = Maps.convert_to_proxy_string_string(backup_schedule);
result_.is_backup_running = is_backup_running;
result_.backup_last_run_time = backup_last_run_time;
result_.archive_target_type = vmpp_archive_target_type_helper.ToString(archive_target_type);
result_.archive_target_config = Maps.convert_to_proxy_string_string(archive_target_config);
result_.archive_frequency = vmpp_archive_frequency_helper.ToString(archive_frequency);
result_.archive_schedule = Maps.convert_to_proxy_string_string(archive_schedule);
result_.is_archive_running = is_archive_running;
result_.archive_last_run_time = archive_last_run_time;
result_.VMs = (VMs != null) ? Helper.RefListToStringArray(VMs) : new string[] {};
result_.is_alarm_enabled = is_alarm_enabled;
result_.alarm_config = Maps.convert_to_proxy_string_string(alarm_config);
result_.recent_alerts = recent_alerts;
return result_;
}
/// <summary>
/// Creates a new VMPP from a Hashtable.
/// </summary>
/// <param name="table"></param>
public VMPP(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
name_label = Marshalling.ParseString(table, "name_label");
name_description = Marshalling.ParseString(table, "name_description");
is_policy_enabled = Marshalling.ParseBool(table, "is_policy_enabled");
backup_type = (vmpp_backup_type)Helper.EnumParseDefault(typeof(vmpp_backup_type), Marshalling.ParseString(table, "backup_type"));
backup_retention_value = Marshalling.ParseLong(table, "backup_retention_value");
backup_frequency = (vmpp_backup_frequency)Helper.EnumParseDefault(typeof(vmpp_backup_frequency), Marshalling.ParseString(table, "backup_frequency"));
backup_schedule = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "backup_schedule"));
is_backup_running = Marshalling.ParseBool(table, "is_backup_running");
backup_last_run_time = Marshalling.ParseDateTime(table, "backup_last_run_time");
archive_target_type = (vmpp_archive_target_type)Helper.EnumParseDefault(typeof(vmpp_archive_target_type), Marshalling.ParseString(table, "archive_target_type"));
archive_target_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "archive_target_config"));
archive_frequency = (vmpp_archive_frequency)Helper.EnumParseDefault(typeof(vmpp_archive_frequency), Marshalling.ParseString(table, "archive_frequency"));
archive_schedule = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "archive_schedule"));
is_archive_running = Marshalling.ParseBool(table, "is_archive_running");
archive_last_run_time = Marshalling.ParseDateTime(table, "archive_last_run_time");
VMs = Marshalling.ParseSetRef<VM>(table, "VMs");
is_alarm_enabled = Marshalling.ParseBool(table, "is_alarm_enabled");
alarm_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "alarm_config"));
recent_alerts = Marshalling.ParseStringArray(table, "recent_alerts");
}
public bool DeepEquals(VMPP other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._is_policy_enabled, other._is_policy_enabled) &&
Helper.AreEqual2(this._backup_type, other._backup_type) &&
Helper.AreEqual2(this._backup_retention_value, other._backup_retention_value) &&
Helper.AreEqual2(this._backup_frequency, other._backup_frequency) &&
Helper.AreEqual2(this._backup_schedule, other._backup_schedule) &&
Helper.AreEqual2(this._is_backup_running, other._is_backup_running) &&
Helper.AreEqual2(this._backup_last_run_time, other._backup_last_run_time) &&
Helper.AreEqual2(this._archive_target_type, other._archive_target_type) &&
Helper.AreEqual2(this._archive_target_config, other._archive_target_config) &&
Helper.AreEqual2(this._archive_frequency, other._archive_frequency) &&
Helper.AreEqual2(this._archive_schedule, other._archive_schedule) &&
Helper.AreEqual2(this._is_archive_running, other._is_archive_running) &&
Helper.AreEqual2(this._archive_last_run_time, other._archive_last_run_time) &&
Helper.AreEqual2(this._VMs, other._VMs) &&
Helper.AreEqual2(this._is_alarm_enabled, other._is_alarm_enabled) &&
Helper.AreEqual2(this._alarm_config, other._alarm_config) &&
Helper.AreEqual2(this._recent_alerts, other._recent_alerts);
}
public override string SaveChanges(Session session, string opaqueRef, VMPP server)
{
if (opaqueRef == null)
{
Proxy_VMPP p = this.ToProxy();
return session.proxy.vmpp_create(session.uuid, p).parse();
}
else
{
if (!Helper.AreEqual2(_name_label, server._name_label))
{
VMPP.set_name_label(session, opaqueRef, _name_label);
}
if (!Helper.AreEqual2(_name_description, server._name_description))
{
VMPP.set_name_description(session, opaqueRef, _name_description);
}
if (!Helper.AreEqual2(_is_policy_enabled, server._is_policy_enabled))
{
VMPP.set_is_policy_enabled(session, opaqueRef, _is_policy_enabled);
}
if (!Helper.AreEqual2(_backup_type, server._backup_type))
{
VMPP.set_backup_type(session, opaqueRef, _backup_type);
}
if (!Helper.AreEqual2(_backup_retention_value, server._backup_retention_value))
{
VMPP.set_backup_retention_value(session, opaqueRef, _backup_retention_value);
}
if (!Helper.AreEqual2(_backup_frequency, server._backup_frequency))
{
VMPP.set_backup_frequency(session, opaqueRef, _backup_frequency);
}
if (!Helper.AreEqual2(_backup_schedule, server._backup_schedule))
{
VMPP.set_backup_schedule(session, opaqueRef, _backup_schedule);
}
if (!Helper.AreEqual2(_archive_target_type, server._archive_target_type))
{
VMPP.set_archive_target_type(session, opaqueRef, _archive_target_type);
}
if (!Helper.AreEqual2(_archive_target_config, server._archive_target_config))
{
VMPP.set_archive_target_config(session, opaqueRef, _archive_target_config);
}
if (!Helper.AreEqual2(_archive_frequency, server._archive_frequency))
{
VMPP.set_archive_frequency(session, opaqueRef, _archive_frequency);
}
if (!Helper.AreEqual2(_archive_schedule, server._archive_schedule))
{
VMPP.set_archive_schedule(session, opaqueRef, _archive_schedule);
}
if (!Helper.AreEqual2(_is_alarm_enabled, server._is_alarm_enabled))
{
VMPP.set_is_alarm_enabled(session, opaqueRef, _is_alarm_enabled);
}
if (!Helper.AreEqual2(_alarm_config, server._alarm_config))
{
VMPP.set_alarm_config(session, opaqueRef, _alarm_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static VMPP get_record(Session session, string _vmpp)
{
return new VMPP((Proxy_VMPP)session.proxy.vmpp_get_record(session.uuid, (_vmpp != null) ? _vmpp : "").parse());
}
/// <summary>
/// Get a reference to the VMPP instance with the specified UUID.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VMPP> get_by_uuid(Session session, string _uuid)
{
return XenRef<VMPP>.Create(session.proxy.vmpp_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Create a new VMPP instance, and return its handle.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<VMPP> create(Session session, VMPP _record)
{
return XenRef<VMPP>.Create(session.proxy.vmpp_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new VMPP instance, and return its handle.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, VMPP _record)
{
return XenRef<Task>.Create(session.proxy.async_vmpp_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified VMPP instance.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static void destroy(Session session, string _vmpp)
{
session.proxy.vmpp_destroy(session.uuid, (_vmpp != null) ? _vmpp : "").parse();
}
/// <summary>
/// Destroy the specified VMPP instance.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static XenRef<Task> async_destroy(Session session, string _vmpp)
{
return XenRef<Task>.Create(session.proxy.async_vmpp_destroy(session.uuid, (_vmpp != null) ? _vmpp : "").parse());
}
/// <summary>
/// Get all the VMPP instances with the given label.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<VMPP>> get_by_name_label(Session session, string _label)
{
return XenRef<VMPP>.Create(session.proxy.vmpp_get_by_name_label(session.uuid, (_label != null) ? _label : "").parse());
}
/// <summary>
/// Get the uuid field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static string get_uuid(Session session, string _vmpp)
{
return (string)session.proxy.vmpp_get_uuid(session.uuid, (_vmpp != null) ? _vmpp : "").parse();
}
/// <summary>
/// Get the name/label field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static string get_name_label(Session session, string _vmpp)
{
return (string)session.proxy.vmpp_get_name_label(session.uuid, (_vmpp != null) ? _vmpp : "").parse();
}
/// <summary>
/// Get the name/description field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static string get_name_description(Session session, string _vmpp)
{
return (string)session.proxy.vmpp_get_name_description(session.uuid, (_vmpp != null) ? _vmpp : "").parse();
}
/// <summary>
/// Get the is_policy_enabled field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static bool get_is_policy_enabled(Session session, string _vmpp)
{
return (bool)session.proxy.vmpp_get_is_policy_enabled(session.uuid, (_vmpp != null) ? _vmpp : "").parse();
}
/// <summary>
/// Get the backup_type field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static vmpp_backup_type get_backup_type(Session session, string _vmpp)
{
return (vmpp_backup_type)Helper.EnumParseDefault(typeof(vmpp_backup_type), (string)session.proxy.vmpp_get_backup_type(session.uuid, (_vmpp != null) ? _vmpp : "").parse());
}
/// <summary>
/// Get the backup_retention_value field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static long get_backup_retention_value(Session session, string _vmpp)
{
return long.Parse((string)session.proxy.vmpp_get_backup_retention_value(session.uuid, (_vmpp != null) ? _vmpp : "").parse());
}
/// <summary>
/// Get the backup_frequency field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static vmpp_backup_frequency get_backup_frequency(Session session, string _vmpp)
{
return (vmpp_backup_frequency)Helper.EnumParseDefault(typeof(vmpp_backup_frequency), (string)session.proxy.vmpp_get_backup_frequency(session.uuid, (_vmpp != null) ? _vmpp : "").parse());
}
/// <summary>
/// Get the backup_schedule field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static Dictionary<string, string> get_backup_schedule(Session session, string _vmpp)
{
return Maps.convert_from_proxy_string_string(session.proxy.vmpp_get_backup_schedule(session.uuid, (_vmpp != null) ? _vmpp : "").parse());
}
/// <summary>
/// Get the is_backup_running field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static bool get_is_backup_running(Session session, string _vmpp)
{
return (bool)session.proxy.vmpp_get_is_backup_running(session.uuid, (_vmpp != null) ? _vmpp : "").parse();
}
/// <summary>
/// Get the backup_last_run_time field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static DateTime get_backup_last_run_time(Session session, string _vmpp)
{
return session.proxy.vmpp_get_backup_last_run_time(session.uuid, (_vmpp != null) ? _vmpp : "").parse();
}
/// <summary>
/// Get the archive_target_type field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static vmpp_archive_target_type get_archive_target_type(Session session, string _vmpp)
{
return (vmpp_archive_target_type)Helper.EnumParseDefault(typeof(vmpp_archive_target_type), (string)session.proxy.vmpp_get_archive_target_type(session.uuid, (_vmpp != null) ? _vmpp : "").parse());
}
/// <summary>
/// Get the archive_target_config field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static Dictionary<string, string> get_archive_target_config(Session session, string _vmpp)
{
return Maps.convert_from_proxy_string_string(session.proxy.vmpp_get_archive_target_config(session.uuid, (_vmpp != null) ? _vmpp : "").parse());
}
/// <summary>
/// Get the archive_frequency field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static vmpp_archive_frequency get_archive_frequency(Session session, string _vmpp)
{
return (vmpp_archive_frequency)Helper.EnumParseDefault(typeof(vmpp_archive_frequency), (string)session.proxy.vmpp_get_archive_frequency(session.uuid, (_vmpp != null) ? _vmpp : "").parse());
}
/// <summary>
/// Get the archive_schedule field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static Dictionary<string, string> get_archive_schedule(Session session, string _vmpp)
{
return Maps.convert_from_proxy_string_string(session.proxy.vmpp_get_archive_schedule(session.uuid, (_vmpp != null) ? _vmpp : "").parse());
}
/// <summary>
/// Get the is_archive_running field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static bool get_is_archive_running(Session session, string _vmpp)
{
return (bool)session.proxy.vmpp_get_is_archive_running(session.uuid, (_vmpp != null) ? _vmpp : "").parse();
}
/// <summary>
/// Get the archive_last_run_time field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static DateTime get_archive_last_run_time(Session session, string _vmpp)
{
return session.proxy.vmpp_get_archive_last_run_time(session.uuid, (_vmpp != null) ? _vmpp : "").parse();
}
/// <summary>
/// Get the VMs field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static List<XenRef<VM>> get_VMs(Session session, string _vmpp)
{
return XenRef<VM>.Create(session.proxy.vmpp_get_vms(session.uuid, (_vmpp != null) ? _vmpp : "").parse());
}
/// <summary>
/// Get the is_alarm_enabled field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static bool get_is_alarm_enabled(Session session, string _vmpp)
{
return (bool)session.proxy.vmpp_get_is_alarm_enabled(session.uuid, (_vmpp != null) ? _vmpp : "").parse();
}
/// <summary>
/// Get the alarm_config field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static Dictionary<string, string> get_alarm_config(Session session, string _vmpp)
{
return Maps.convert_from_proxy_string_string(session.proxy.vmpp_get_alarm_config(session.uuid, (_vmpp != null) ? _vmpp : "").parse());
}
/// <summary>
/// Get the recent_alerts field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static string[] get_recent_alerts(Session session, string _vmpp)
{
return (string [])session.proxy.vmpp_get_recent_alerts(session.uuid, (_vmpp != null) ? _vmpp : "").parse();
}
/// <summary>
/// Set the name/label field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_label">New value to set</param>
public static void set_name_label(Session session, string _vmpp, string _label)
{
session.proxy.vmpp_set_name_label(session.uuid, (_vmpp != null) ? _vmpp : "", (_label != null) ? _label : "").parse();
}
/// <summary>
/// Set the name/description field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_description">New value to set</param>
public static void set_name_description(Session session, string _vmpp, string _description)
{
session.proxy.vmpp_set_name_description(session.uuid, (_vmpp != null) ? _vmpp : "", (_description != null) ? _description : "").parse();
}
/// <summary>
/// Set the is_policy_enabled field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_is_policy_enabled">New value to set</param>
public static void set_is_policy_enabled(Session session, string _vmpp, bool _is_policy_enabled)
{
session.proxy.vmpp_set_is_policy_enabled(session.uuid, (_vmpp != null) ? _vmpp : "", _is_policy_enabled).parse();
}
/// <summary>
/// Set the backup_type field of the given VMPP.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_backup_type">New value to set</param>
public static void set_backup_type(Session session, string _vmpp, vmpp_backup_type _backup_type)
{
session.proxy.vmpp_set_backup_type(session.uuid, (_vmpp != null) ? _vmpp : "", vmpp_backup_type_helper.ToString(_backup_type)).parse();
}
/// <summary>
/// This call executes the protection policy immediately
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
public static string protect_now(Session session, string _vmpp)
{
return (string)session.proxy.vmpp_protect_now(session.uuid, (_vmpp != null) ? _vmpp : "").parse();
}
/// <summary>
/// This call archives the snapshot provided as a parameter
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_snapshot">The snapshot to archive</param>
public static string archive_now(Session session, string _snapshot)
{
return (string)session.proxy.vmpp_archive_now(session.uuid, (_snapshot != null) ? _snapshot : "").parse();
}
/// <summary>
/// This call fetches a history of alerts for a given protection policy
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_hours_from_now">how many hours in the past the oldest record to fetch is</param>
public static string[] get_alerts(Session session, string _vmpp, long _hours_from_now)
{
return (string [])session.proxy.vmpp_get_alerts(session.uuid, (_vmpp != null) ? _vmpp : "", _hours_from_now.ToString()).parse();
}
/// <summary>
///
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_value">the value to set</param>
public static void set_backup_retention_value(Session session, string _vmpp, long _value)
{
session.proxy.vmpp_set_backup_retention_value(session.uuid, (_vmpp != null) ? _vmpp : "", _value.ToString()).parse();
}
/// <summary>
/// Set the value of the backup_frequency field
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_value">the backup frequency</param>
public static void set_backup_frequency(Session session, string _vmpp, vmpp_backup_frequency _value)
{
session.proxy.vmpp_set_backup_frequency(session.uuid, (_vmpp != null) ? _vmpp : "", vmpp_backup_frequency_helper.ToString(_value)).parse();
}
/// <summary>
///
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_value">the value to set</param>
public static void set_backup_schedule(Session session, string _vmpp, Dictionary<string, string> _value)
{
session.proxy.vmpp_set_backup_schedule(session.uuid, (_vmpp != null) ? _vmpp : "", Maps.convert_to_proxy_string_string(_value)).parse();
}
/// <summary>
/// Set the value of the archive_frequency field
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_value">the archive frequency</param>
public static void set_archive_frequency(Session session, string _vmpp, vmpp_archive_frequency _value)
{
session.proxy.vmpp_set_archive_frequency(session.uuid, (_vmpp != null) ? _vmpp : "", vmpp_archive_frequency_helper.ToString(_value)).parse();
}
/// <summary>
///
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_value">the value to set</param>
public static void set_archive_schedule(Session session, string _vmpp, Dictionary<string, string> _value)
{
session.proxy.vmpp_set_archive_schedule(session.uuid, (_vmpp != null) ? _vmpp : "", Maps.convert_to_proxy_string_string(_value)).parse();
}
/// <summary>
/// Set the value of the archive_target_config_type field
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_value">the archive target config type</param>
public static void set_archive_target_type(Session session, string _vmpp, vmpp_archive_target_type _value)
{
session.proxy.vmpp_set_archive_target_type(session.uuid, (_vmpp != null) ? _vmpp : "", vmpp_archive_target_type_helper.ToString(_value)).parse();
}
/// <summary>
///
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_value">the value to set</param>
public static void set_archive_target_config(Session session, string _vmpp, Dictionary<string, string> _value)
{
session.proxy.vmpp_set_archive_target_config(session.uuid, (_vmpp != null) ? _vmpp : "", Maps.convert_to_proxy_string_string(_value)).parse();
}
/// <summary>
/// Set the value of the is_alarm_enabled field
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_value">true if alarm is enabled for this policy</param>
public static void set_is_alarm_enabled(Session session, string _vmpp, bool _value)
{
session.proxy.vmpp_set_is_alarm_enabled(session.uuid, (_vmpp != null) ? _vmpp : "", _value).parse();
}
/// <summary>
///
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_value">the value to set</param>
public static void set_alarm_config(Session session, string _vmpp, Dictionary<string, string> _value)
{
session.proxy.vmpp_set_alarm_config(session.uuid, (_vmpp != null) ? _vmpp : "", Maps.convert_to_proxy_string_string(_value)).parse();
}
/// <summary>
///
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_key">the key to add</param>
/// <param name="_value">the value to add</param>
public static void add_to_backup_schedule(Session session, string _vmpp, string _key, string _value)
{
session.proxy.vmpp_add_to_backup_schedule(session.uuid, (_vmpp != null) ? _vmpp : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
///
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_key">the key to add</param>
/// <param name="_value">the value to add</param>
public static void add_to_archive_target_config(Session session, string _vmpp, string _key, string _value)
{
session.proxy.vmpp_add_to_archive_target_config(session.uuid, (_vmpp != null) ? _vmpp : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
///
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_key">the key to add</param>
/// <param name="_value">the value to add</param>
public static void add_to_archive_schedule(Session session, string _vmpp, string _key, string _value)
{
session.proxy.vmpp_add_to_archive_schedule(session.uuid, (_vmpp != null) ? _vmpp : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
///
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_key">the key to add</param>
/// <param name="_value">the value to add</param>
public static void add_to_alarm_config(Session session, string _vmpp, string _key, string _value)
{
session.proxy.vmpp_add_to_alarm_config(session.uuid, (_vmpp != null) ? _vmpp : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
///
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_key">the key to remove</param>
public static void remove_from_backup_schedule(Session session, string _vmpp, string _key)
{
session.proxy.vmpp_remove_from_backup_schedule(session.uuid, (_vmpp != null) ? _vmpp : "", (_key != null) ? _key : "").parse();
}
/// <summary>
///
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_key">the key to remove</param>
public static void remove_from_archive_target_config(Session session, string _vmpp, string _key)
{
session.proxy.vmpp_remove_from_archive_target_config(session.uuid, (_vmpp != null) ? _vmpp : "", (_key != null) ? _key : "").parse();
}
/// <summary>
///
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_key">the key to remove</param>
public static void remove_from_archive_schedule(Session session, string _vmpp, string _key)
{
session.proxy.vmpp_remove_from_archive_schedule(session.uuid, (_vmpp != null) ? _vmpp : "", (_key != null) ? _key : "").parse();
}
/// <summary>
///
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_key">the key to remove</param>
public static void remove_from_alarm_config(Session session, string _vmpp, string _key)
{
session.proxy.vmpp_remove_from_alarm_config(session.uuid, (_vmpp != null) ? _vmpp : "", (_key != null) ? _key : "").parse();
}
/// <summary>
///
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_value">the value to set</param>
public static void set_backup_last_run_time(Session session, string _vmpp, DateTime _value)
{
session.proxy.vmpp_set_backup_last_run_time(session.uuid, (_vmpp != null) ? _vmpp : "", _value).parse();
}
/// <summary>
///
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vmpp">The opaque_ref of the given vmpp</param>
/// <param name="_value">the value to set</param>
public static void set_archive_last_run_time(Session session, string _vmpp, DateTime _value)
{
session.proxy.vmpp_set_archive_last_run_time(session.uuid, (_vmpp != null) ? _vmpp : "", _value).parse();
}
/// <summary>
/// Return a list of all the VMPPs known to the system.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<VMPP>> get_all(Session session)
{
return XenRef<VMPP>.Create(session.proxy.vmpp_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the VMPP Records at once, in a single XML RPC call
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<VMPP>, VMPP> get_all_records(Session session)
{
return XenRef<VMPP>.Create<Proxy_VMPP>(session.proxy.vmpp_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>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label;
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description;
/// <summary>
/// enable or disable this policy
/// </summary>
public virtual bool is_policy_enabled
{
get { return _is_policy_enabled; }
set
{
if (!Helper.AreEqual(value, _is_policy_enabled))
{
_is_policy_enabled = value;
Changed = true;
NotifyPropertyChanged("is_policy_enabled");
}
}
}
private bool _is_policy_enabled;
/// <summary>
/// type of the backup sub-policy
/// </summary>
public virtual vmpp_backup_type backup_type
{
get { return _backup_type; }
set
{
if (!Helper.AreEqual(value, _backup_type))
{
_backup_type = value;
Changed = true;
NotifyPropertyChanged("backup_type");
}
}
}
private vmpp_backup_type _backup_type;
/// <summary>
/// maximum number of backups that should be stored at any time
/// </summary>
public virtual long backup_retention_value
{
get { return _backup_retention_value; }
set
{
if (!Helper.AreEqual(value, _backup_retention_value))
{
_backup_retention_value = value;
Changed = true;
NotifyPropertyChanged("backup_retention_value");
}
}
}
private long _backup_retention_value;
/// <summary>
/// frequency of the backup schedule
/// </summary>
public virtual vmpp_backup_frequency backup_frequency
{
get { return _backup_frequency; }
set
{
if (!Helper.AreEqual(value, _backup_frequency))
{
_backup_frequency = value;
Changed = true;
NotifyPropertyChanged("backup_frequency");
}
}
}
private vmpp_backup_frequency _backup_frequency;
/// <summary>
/// schedule of the backup containing 'hour', 'min', 'days'. Date/time-related information is in XenServer Local Timezone
/// </summary>
public virtual Dictionary<string, string> backup_schedule
{
get { return _backup_schedule; }
set
{
if (!Helper.AreEqual(value, _backup_schedule))
{
_backup_schedule = value;
Changed = true;
NotifyPropertyChanged("backup_schedule");
}
}
}
private Dictionary<string, string> _backup_schedule;
/// <summary>
/// true if this protection policy's backup is running
/// </summary>
public virtual bool is_backup_running
{
get { return _is_backup_running; }
set
{
if (!Helper.AreEqual(value, _is_backup_running))
{
_is_backup_running = value;
Changed = true;
NotifyPropertyChanged("is_backup_running");
}
}
}
private bool _is_backup_running;
/// <summary>
/// time of the last backup
/// </summary>
public virtual DateTime backup_last_run_time
{
get { return _backup_last_run_time; }
set
{
if (!Helper.AreEqual(value, _backup_last_run_time))
{
_backup_last_run_time = value;
Changed = true;
NotifyPropertyChanged("backup_last_run_time");
}
}
}
private DateTime _backup_last_run_time;
/// <summary>
/// type of the archive target config
/// </summary>
public virtual vmpp_archive_target_type archive_target_type
{
get { return _archive_target_type; }
set
{
if (!Helper.AreEqual(value, _archive_target_type))
{
_archive_target_type = value;
Changed = true;
NotifyPropertyChanged("archive_target_type");
}
}
}
private vmpp_archive_target_type _archive_target_type;
/// <summary>
/// configuration for the archive, including its 'location', 'username', 'password'
/// </summary>
public virtual Dictionary<string, string> archive_target_config
{
get { return _archive_target_config; }
set
{
if (!Helper.AreEqual(value, _archive_target_config))
{
_archive_target_config = value;
Changed = true;
NotifyPropertyChanged("archive_target_config");
}
}
}
private Dictionary<string, string> _archive_target_config;
/// <summary>
/// frequency of the archive schedule
/// </summary>
public virtual vmpp_archive_frequency archive_frequency
{
get { return _archive_frequency; }
set
{
if (!Helper.AreEqual(value, _archive_frequency))
{
_archive_frequency = value;
Changed = true;
NotifyPropertyChanged("archive_frequency");
}
}
}
private vmpp_archive_frequency _archive_frequency;
/// <summary>
/// schedule of the archive containing 'hour', 'min', 'days'. Date/time-related information is in XenServer Local Timezone
/// </summary>
public virtual Dictionary<string, string> archive_schedule
{
get { return _archive_schedule; }
set
{
if (!Helper.AreEqual(value, _archive_schedule))
{
_archive_schedule = value;
Changed = true;
NotifyPropertyChanged("archive_schedule");
}
}
}
private Dictionary<string, string> _archive_schedule;
/// <summary>
/// true if this protection policy's archive is running
/// </summary>
public virtual bool is_archive_running
{
get { return _is_archive_running; }
set
{
if (!Helper.AreEqual(value, _is_archive_running))
{
_is_archive_running = value;
Changed = true;
NotifyPropertyChanged("is_archive_running");
}
}
}
private bool _is_archive_running;
/// <summary>
/// time of the last archive
/// </summary>
public virtual DateTime archive_last_run_time
{
get { return _archive_last_run_time; }
set
{
if (!Helper.AreEqual(value, _archive_last_run_time))
{
_archive_last_run_time = value;
Changed = true;
NotifyPropertyChanged("archive_last_run_time");
}
}
}
private DateTime _archive_last_run_time;
/// <summary>
/// all VMs attached to this protection policy
/// </summary>
public virtual List<XenRef<VM>> VMs
{
get { return _VMs; }
set
{
if (!Helper.AreEqual(value, _VMs))
{
_VMs = value;
Changed = true;
NotifyPropertyChanged("VMs");
}
}
}
private List<XenRef<VM>> _VMs;
/// <summary>
/// true if alarm is enabled for this policy
/// </summary>
public virtual bool is_alarm_enabled
{
get { return _is_alarm_enabled; }
set
{
if (!Helper.AreEqual(value, _is_alarm_enabled))
{
_is_alarm_enabled = value;
Changed = true;
NotifyPropertyChanged("is_alarm_enabled");
}
}
}
private bool _is_alarm_enabled;
/// <summary>
/// configuration for the alarm
/// </summary>
public virtual Dictionary<string, string> alarm_config
{
get { return _alarm_config; }
set
{
if (!Helper.AreEqual(value, _alarm_config))
{
_alarm_config = value;
Changed = true;
NotifyPropertyChanged("alarm_config");
}
}
}
private Dictionary<string, string> _alarm_config;
/// <summary>
/// recent alerts
/// </summary>
public virtual string[] recent_alerts
{
get { return _recent_alerts; }
set
{
if (!Helper.AreEqual(value, _recent_alerts))
{
_recent_alerts = value;
Changed = true;
NotifyPropertyChanged("recent_alerts");
}
}
}
private string[] _recent_alerts;
}
}
| |
// The MIT License (MIT)
//
// CoreTweet - A .NET Twitter Library supporting Twitter API 1.1
// Copyright (c) 2013-2015 CoreTweet Development Team
//
// 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 CoreTweet.Core;
using Newtonsoft.Json;
namespace CoreTweet
{
/// <summary>
/// Represents the metadata and additional contextual information about content posted on Twitter.
/// </summary>
public class Entities : CoreBase
{
/// <summary>
/// Gets or sets the hashtags which have been parsed out of the Tweet text.
/// </summary>
[JsonProperty("hashtags")]
public HashtagEntity[] HashTags { get; set; }
/// <summary>
/// Gets or sets the media elements uploaded with the Tweet.
/// </summary>
[JsonProperty("media")]
public MediaEntity[] Media { get; set; }
/// <summary>
/// Gets or sets the URLs included in the text of a Tweet or within textual fields of a user object.
/// </summary>
[JsonProperty("urls")]
public UrlEntity[] Urls { get; set; }
/// <summary>
/// Gets or sets the other Twitter users mentioned in the text of the Tweet.
/// </summary>
[JsonProperty("user_mentions")]
public UserMentionEntity[] UserMentions { get; set; }
/// <summary>
/// Gets or sets the symbols which have been parsed out of the Tweet text.
/// </summary>
[JsonProperty("symbols")]
public CashtagEntity[] Symbols { get; set; }
}
/// <summary>
/// Represents an entity object in the content posted on Twitter. This is an <c>abstract</c> class.
/// </summary>
public abstract class Entity : CoreBase
{
/// <summary>
/// <para>Gets or sets an array of integers indicating the offsets within the Tweet text where the URL begins and ends.</para>
/// <para>The first integer represents the location of the first character of the URL in the Tweet text.</para>
/// <para>The second integer represents the location of the first non-URL character occurring after the URL (or the end of the string if the URL is the last part of the Tweet text).</para>
/// </summary>
[JsonProperty("indices")]
public int[] Indices { get; set; }
}
/// <summary>
/// Represents a symbol object that contains a symbol in the content posted on Twitter.
/// </summary>
public abstract class SymbolEntity : Entity
{
/// <summary>
/// Gets or sets the name of the hashtag, minus the leading '#' or '$' character.
/// </summary>
[JsonProperty("text")]
public string Text { get; set; }
}
/// <summary>
/// Represents a #hashtag object.
/// </summary>
public class HashtagEntity : SymbolEntity { }
/// <summary>
/// Represents a $cashtag object.
/// </summary>
public class CashtagEntity : SymbolEntity { }
/// <summary>
/// Represents a media object that contains the URLs, sizes and type of the media.
/// </summary>
public class MediaEntity : UrlEntity
{
/// <summary>
/// Gets or sets the ID of the media expressed as a 64-bit integer.
/// </summary>
[JsonProperty("id")]
public long Id { get; set; }
/// <summary>
/// Gets or sets the URL pointing directly to the uploaded media file.
/// </summary>
[JsonProperty("media_url")]
[JsonConverter(typeof(UriConverter))]
public Uri MediaUrl { get; set; }
/// <summary>
/// Gets or sets the URL pointing directly to the uploaded media file, for embedding on https pages.
/// </summary>
[JsonProperty("media_url_https")]
[JsonConverter(typeof(UriConverter))]
public Uri MediaUrlHttps { get; set; }
/// <summary>
/// Gets or sets the object showing available sizes for the media file.
/// </summary>
[JsonProperty("sizes")]
public MediaSizes Sizes { get; set; }
/// <summary>
/// <para>Gets or sets the ID points to the original Tweet.</para>
/// <para>(Only for Tweets containing media that was originally associated with a different tweet.)</para>
/// </summary>
[JsonProperty("source_status_id")]
public long? SourceStatusId { get; set; }
/// <summary>
/// Gets or sets the type of uploaded media.
/// </summary>
[JsonProperty("type")]
public string Type { get; set; }
/// <summary>
/// Gets or sets the information of the uploaded video or animated GIF.
/// </summary>
[JsonProperty("video_info")]
public VideoInfo VideoInfo { get; set; }
/// <summary>
/// Returns the ID of this instance.
/// </summary>
/// <returns>The ID of this instance.</returns>
public override string ToString()
{
return this.Id.ToString("D");
}
}
/// <summary>
/// Represents the size of the <see cref="CoreTweet.MediaSizes"/>.
/// </summary>
public class MediaSize : CoreBase
{
/// <summary>
/// Gets or sets the height in pixels of the size.
/// </summary>
[JsonProperty("h")]
public int Height { get; set; }
/// <summary>
/// <para>Gets or sets the resizing method used to obtain the size.</para>
/// <para>A value of fit means that the media was resized to fit one dimension, keeping its native aspect ratio.</para>
/// <para>A value of crop means that the media was cropped in order to fit a specific resolution.</para>
/// </summary>
[JsonProperty("resize")]
public string Resize { get; set; }
/// <summary>
/// Gets or sets the width in pixels of the size.
/// </summary>
[JsonProperty("w")]
public int Width { get; set; }
}
/// <summary>
/// Represents the variations of the media.
/// </summary>
public class MediaSizes : CoreBase
{
/// <summary>
/// Gets or sets the information for a large-sized version of the media.
/// </summary>
[JsonProperty("large")]
public MediaSize Large { get; set; }
/// <summary>
/// Gets or sets the information for a medium-sized version of the media.
/// </summary>
[JsonProperty("medium")]
public MediaSize Medium { get; set; }
/// <summary>
/// Gets or sets the information for a small-sized version of the media.
/// </summary>
[JsonProperty("small")]
public MediaSize Small { get; set; }
/// <summary>
/// Gets or sets the information for a thumbnail-sized version of the media.
/// </summary>
[JsonProperty("thumb")]
public MediaSize Thumb { get; set; }
}
/// <summary>
/// Represents a video_info object which is included by a video or animated GIF entity.
/// </summary>
public class VideoInfo : CoreBase
{
/// <summary>
/// Gets or sets the aspect ratio of the video,
/// as a simplified fraction of width and height in a 2-element array.
/// Typical values are [4, 3] or [16, 9]
/// </summary>
[JsonProperty("aspect_ratio")]
public int[] AspectRatio { get; set; }
/// <summary>
/// Gets or sets the length of the video, in milliseconds.
/// </summary>
[JsonProperty("duration_millis")]
public int? DurationMillis { get; set; }
/// <summary>
/// Gets or sets the different encodings/streams of the video.
/// </summary>
[JsonProperty("variants")]
public VideoVariant[] Variants { get; set; }
}
/// <summary>
/// Represents a variant of the video.
/// </summary>
public class VideoVariant : CoreBase
{
/// <summary>
/// Gets or sets the bitrate of this variant.
/// </summary>
[JsonProperty("bitrate")]
public int? Bitrate { get; set; }
/// <summary>
/// Gets or sets the MIME type of this variant.
/// </summary>
[JsonProperty("content_type")]
public string ContentType { get; set; }
/// <summary>
/// Gets or sets the URL of the video or playlist.
/// </summary>
[JsonProperty("url")]
[JsonConverter(typeof(UriConverter))]
public Uri Url { get; set; }
}
/// <summary>
/// Represents a URL object that contains the string for display and the raw URL.
/// </summary>
public class UrlEntity : Entity
{
/// <summary>
/// Gets or sets the URL to display on clients.
/// </summary>
[JsonProperty("display_url")]
public string DisplayUrl { get; set; }
/// <summary>
/// Gets or sets the expanded version of <see cref="CoreTweet.UrlEntity.DisplayUrl"/>.
/// </summary>
// Note that Twitter accepts invalid URLs, for example, "http://..com"
[JsonProperty("expanded_url")]
public string ExpandedUrl { get; set; }
/// <summary>
/// Gets or sets the wrapped URL, corresponding to the value embedded directly into the raw Tweet text, and the values for the indices parameter.
/// </summary>
[JsonProperty("url")]
[JsonConverter(typeof(UriConverter))]
public Uri Url { get; set; }
}
/// <summary>
/// Represents a mention object that contains the user information.
/// </summary>
public class UserMentionEntity : Entity
{
/// <summary>
/// Gets or sets the ID of the mentioned user.
/// </summary>
[JsonProperty("id")]
public long Id { get; set; }
/// <summary>
/// Gets or sets display name of the referenced user.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets screen name of the referenced user.
/// </summary>
[JsonProperty("screen_name")]
public string ScreenName { get; set; }
/// <summary>
/// Returns the ID of this instance.
/// </summary>
/// <returns>The ID of this instance.</returns>
public override string ToString()
{
return this.Id.ToString("D");
}
}
}
| |
using System;
using System.Globalization;
using System.Runtime.Serialization;
using NDatabase.Api;
using NDatabase.Cache;
using NDatabase.Exceptions;
using NDatabase.Meta;
using NDatabase.Meta.Introspector;
using NDatabase.Tool;
using NDatabase.Triggers;
namespace NDatabase.Core.Engine
{
/// <summary>
/// Class used to build instance from Meta Object representation.
/// </summary>
/// <remarks>
/// Class used to build instance from Meta Object representation. Layer 2 to Layer 1 conversion.
/// </remarks>
internal sealed class InstanceBuilder : IInstanceBuilder
{
private readonly IStorageEngine _engine;
private readonly IInternalTriggerManager _triggerManager;
public InstanceBuilder(IStorageEngine engine)
{
_triggerManager = engine.GetLocalTriggerManager();
_engine = engine;
}
#region IInstanceBuilder Members
public object BuildOneInstance(NonNativeObjectInfo objectInfo)
{
return BuildOneInstance(objectInfo, _engine.GetSession().GetCache());
}
public object BuildOneInstance(NonNativeObjectInfo objectInfo, IOdbCache cache)
{
// verify if the object is check to delete
if (objectInfo.IsDeletedObject())
throw new OdbRuntimeException(
NDatabaseError.ObjectIsMarkedAsDeletedForOid.AddParameter(objectInfo.GetOid()));
// Then check if object is in cache
var o = cache.GetObject(objectInfo.GetOid());
if (o != null)
return o;
try
{
o = FormatterServices.GetUninitializedObject(objectInfo.GetClassInfo().UnderlyingType);
}
catch (Exception e)
{
throw new OdbRuntimeException(
NDatabaseError.InstanciationError.AddParameter(objectInfo.GetClassInfo().FullClassName), e);
}
// This can happen if ODB can not create the instance from security reasons
if (o == null)
throw new OdbRuntimeException(
NDatabaseError.InstanciationError.AddParameter(objectInfo.GetClassInfo().FullClassName));
// Keep the initial hash code. In some cases, when the class redefines
// the hash code method
// Hash code can return wrong values when attributes are not set (when
// hash code depends on attribute values)
// Hash codes are used as the key of the map,
// So at the end of this method, if hash codes are different, object
// will be removed from the cache and inserted back
var hashCodeIsOk = true;
var initialHashCode = 0;
try
{
initialHashCode = o.GetHashCode();
}
catch
{
hashCodeIsOk = false;
}
// Adds this incomplete instance in the cache to manage cyclic reference
if (hashCodeIsOk)
cache.AddObject(objectInfo.GetOid(), o, objectInfo.GetHeader());
var classInfo = objectInfo.GetClassInfo();
var fields = ClassIntrospector.GetAllFieldsFrom(classInfo.UnderlyingType);
object value = null;
foreach (var fieldInfo in fields)
{
// Gets the id of this field
var attributeId = classInfo.GetAttributeId(fieldInfo.Name);
if (OdbConfiguration.IsLoggingEnabled())
DLogger.Debug(string.Concat("InstanceBuilder: ", "getting field with name ", fieldInfo.Name, ", attribute id is ",
attributeId.ToString()));
var abstractObjectInfo = objectInfo.GetAttributeValueFromId(attributeId);
// Check consistency
// ensureClassCompatibily(field,
// instanceInfo.getClassInfo().getAttributeinfo(i).getFullClassname());
if (abstractObjectInfo == null || (abstractObjectInfo.IsNull()))
continue;
if (abstractObjectInfo.IsNative())
{
if (abstractObjectInfo.IsAtomicNativeObject())
{
value = abstractObjectInfo.IsNull()
? null
: abstractObjectInfo.GetObject();
}
if (abstractObjectInfo.IsArrayObject())
value = BuildArrayInstance((ArrayObjectInfo) abstractObjectInfo);
if (abstractObjectInfo.IsEnumObject())
value = BuildEnumInstance((EnumNativeObjectInfo) abstractObjectInfo, fieldInfo.FieldType);
}
else
{
if (abstractObjectInfo.IsNonNativeObject())
{
if (abstractObjectInfo.IsDeletedObject())
{
if (OdbConfiguration.IsLoggingEnabled())
{
var warning =
NDatabaseError.AttributeReferencesADeletedObject.AddParameter(
objectInfo.GetClassInfo().FullClassName).AddParameter(
objectInfo.GetOid()).AddParameter(fieldInfo.Name);
DLogger.Warning("InstanceBuilder: " + warning);
}
value = null;
}
else
value = BuildOneInstance((NonNativeObjectInfo) abstractObjectInfo);
}
}
if (value == null)
continue;
if (OdbConfiguration.IsLoggingEnabled())
{
DLogger.Debug(String.Format("InstanceBuilder: Setting field {0}({1}) to {2} / {3}", fieldInfo.Name,
fieldInfo.GetType().FullName, value, value.GetType().FullName));
}
try
{
fieldInfo.SetValue(o, value);
}
catch (Exception e)
{
throw new OdbRuntimeException(
NDatabaseError.InstanceBuilderWrongObjectContainerType.AddParameter(
objectInfo.GetClassInfo().FullClassName).AddParameter(value.GetType().FullName)
.AddParameter(fieldInfo.GetType().FullName), e);
}
}
if (o.GetType() != objectInfo.GetClassInfo().UnderlyingType)
{
throw new OdbRuntimeException(
NDatabaseError.InstanceBuilderWrongObjectType.AddParameter(
objectInfo.GetClassInfo().FullClassName).AddParameter(o.GetType().FullName));
}
if (hashCodeIsOk || initialHashCode != o.GetHashCode())
{
// Bug (sf bug id=1875544 )detected by glsender
// This can happen when an object has redefined its own hashcode
// method and depends on the field values
// Then, we have to remove object from the cache and re-insert to
// correct map hash code
cache.RemoveObjectByOid(objectInfo.GetOid());
// re-Adds instance in the cache
cache.AddObject(objectInfo.GetOid(), o, objectInfo.GetHeader());
}
if (_triggerManager != null)
_triggerManager.ManageSelectTriggerAfter(objectInfo.GetClassInfo().UnderlyingType, o,
objectInfo.GetOid());
return o;
}
#endregion
private object BuildOneInstance(AbstractObjectInfo objectInfo)
{
if (objectInfo.IsNull())
return null;
var instance = objectInfo.GetType() == typeof (NonNativeObjectInfo)
? BuildOneInstance((NonNativeObjectInfo) objectInfo)
: BuildOneInstance((NativeObjectInfo) objectInfo);
return instance;
}
/// <summary>
/// Builds an instance of an enum
/// </summary>
private static object BuildEnumInstance(EnumNativeObjectInfo enoi, Type enumClass)
{
return Enum.Parse(enumClass, enoi.GetEnumValue(), false);
}
/// <summary>
/// Builds an instance of an array
/// </summary>
private object BuildArrayInstance(ArrayObjectInfo aoi)
{
// first check if array element type is native (int,short, for example)
var type = OdbType.GetFromName(aoi.GetRealArrayComponentClassName());
var arrayClazz = type.GetNativeClass();
object array = Array.CreateInstance(arrayClazz, aoi.GetArray().Length);
for (var i = 0; i < aoi.GetArrayLength(); i++)
{
var abstractObjectInfo = (AbstractObjectInfo) aoi.GetArray()[i];
if (abstractObjectInfo == null || abstractObjectInfo.IsDeletedObject() || abstractObjectInfo.IsNull())
continue;
var instance = BuildOneInstance(abstractObjectInfo);
((Array) array).SetValue(instance, i);
}
return array;
}
private object BuildOneInstance(NativeObjectInfo objectInfo)
{
if (objectInfo.IsAtomicNativeObject())
return BuildOneInstance((AtomicNativeObjectInfo) objectInfo);
if (objectInfo.IsArrayObject())
return BuildArrayInstance((ArrayObjectInfo) objectInfo);
if (objectInfo.IsNull())
return null;
throw new OdbRuntimeException(
NDatabaseError.InstanceBuilderNativeType.AddParameter(OdbType.GetNameFromId(objectInfo.GetOdbTypeId())));
}
private static object BuildOneInstance(AtomicNativeObjectInfo objectInfo)
{
var odbTypeId = objectInfo.GetOdbTypeId();
return CheckIfNull(objectInfo, odbTypeId);
}
private static object CheckIfNull(AbstractObjectInfo objectInfo, int odbTypeId)
{
return odbTypeId == OdbType.NullId ? null : CheckIfString(objectInfo, odbTypeId);
}
private static object CheckIfString(AbstractObjectInfo objectInfo, int odbTypeId)
{
return odbTypeId == OdbType.StringId ? objectInfo.GetObject() : CheckIfDate(objectInfo, odbTypeId);
}
private static object CheckIfDate(AbstractObjectInfo objectInfo, int odbTypeId)
{
return odbTypeId == OdbType.DateId ? objectInfo.GetObject() : CheckIfLong(objectInfo, odbTypeId);
}
private static object CheckIfLong(AbstractObjectInfo objectInfo, int odbTypeId)
{
if (odbTypeId == OdbType.LongId)
{
if (objectInfo.GetObject() is long)
return objectInfo.GetObject();
return Convert.ToInt64(objectInfo.GetObject().ToString());
}
if (odbTypeId == OdbType.ULongId)
{
if (objectInfo.GetObject() is ulong)
return objectInfo.GetObject();
return Convert.ToUInt64(objectInfo.GetObject().ToString());
}
return CheckIfInt(objectInfo, odbTypeId);
}
private static object CheckIfInt(AbstractObjectInfo objectInfo, int odbTypeId)
{
if (odbTypeId == OdbType.IntegerId)
{
if (objectInfo.GetObject() is int)
return objectInfo.GetObject();
return Convert.ToInt32(objectInfo.GetObject().ToString());
}
if (odbTypeId == OdbType.UIntegerId)
{
if (objectInfo.GetObject() is uint)
return objectInfo.GetObject();
return Convert.ToUInt32(objectInfo.GetObject().ToString());
}
return CheckIfBool(objectInfo, odbTypeId);
}
private static object CheckIfBool(AbstractObjectInfo objectInfo, int odbTypeId)
{
if (odbTypeId == OdbType.BooleanId)
{
if (objectInfo.GetObject() is bool)
return objectInfo.GetObject();
return Convert.ToBoolean(objectInfo.GetObject().ToString());
}
return CheckIfByte(objectInfo, odbTypeId);
}
private static object CheckIfByte(AbstractObjectInfo objectInfo, int odbTypeId)
{
if (odbTypeId == OdbType.ByteId)
{
if (objectInfo.GetObject() is byte)
return objectInfo.GetObject();
return Convert.ToByte(objectInfo.GetObject().ToString());
}
if (odbTypeId == OdbType.SByteId)
{
if (objectInfo.GetObject() is sbyte)
return objectInfo.GetObject();
return Convert.ToSByte(objectInfo.GetObject().ToString());
}
return CheckIfShort(objectInfo, odbTypeId);
}
private static object CheckIfShort(AbstractObjectInfo objectInfo, int odbTypeId)
{
if (odbTypeId == OdbType.ShortId)
{
if (objectInfo.GetObject() is short)
return objectInfo.GetObject();
return Convert.ToInt16(objectInfo.GetObject().ToString());
}
if (odbTypeId == OdbType.UShortId)
{
if (objectInfo.GetObject() is ushort)
return objectInfo.GetObject();
return Convert.ToUInt16(objectInfo.GetObject().ToString());
}
return CheckIfFloatOrDouble(objectInfo, odbTypeId);
}
private static object CheckIfFloatOrDouble(AbstractObjectInfo objectInfo, int odbTypeId)
{
if (odbTypeId == OdbType.FloatId)
{
if (objectInfo.GetObject() is float)
return objectInfo.GetObject();
return Convert.ToSingle(objectInfo.GetObject().ToString());
}
if (odbTypeId == OdbType.DoubleId)
{
if (objectInfo.GetObject() is double)
return objectInfo.GetObject();
return Convert.ToDouble(objectInfo.GetObject().ToString());
}
return CheckIfDecimal(objectInfo, odbTypeId);
}
private static object CheckIfDecimal(AbstractObjectInfo objectInfo, int odbTypeId)
{
return odbTypeId == OdbType.DecimalId
? Decimal.Parse(objectInfo.GetObject().ToString(), NumberStyles.Any)
: CheckIfCharacter(objectInfo, odbTypeId);
}
private static object CheckIfCharacter(AbstractObjectInfo objectInfo, int odbTypeId)
{
if (odbTypeId == OdbType.CharacterId)
{
if (objectInfo.GetObject() is char)
return objectInfo.GetObject();
return objectInfo.GetObject().ToString()[0];
}
return CheckIfOid(objectInfo, odbTypeId);
}
private static object CheckIfOid(AbstractObjectInfo objectInfo, int odbTypeId)
{
long l;
if (odbTypeId == OdbType.ObjectOidId)
{
if (objectInfo.GetObject() is long)
{
l = (long) objectInfo.GetObject();
}
else
{
var oid = (OID) objectInfo.GetObject();
l = oid.ObjectId;
}
return OIDFactory.BuildObjectOID(l);
}
if (odbTypeId == OdbType.ClassOidId)
{
if (objectInfo.GetObject() is long)
l = (long) objectInfo.GetObject();
else
l = Convert.ToInt64(objectInfo.GetObject().ToString());
return OIDFactory.BuildClassOID(l);
}
return ThrowIfNotFound(odbTypeId);
}
private static object ThrowIfNotFound(int odbTypeId)
{
throw new OdbRuntimeException(
NDatabaseError.InstanceBuilderNativeTypeInCollectionNotSupported.AddParameter(
OdbType.GetNameFromId(odbTypeId)));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using Microsoft.Msagl;
using Microsoft.Msagl.ControlForWpfObsolete;
using Microsoft.Msagl.Core.DataStructures;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Core.Routing;
using Microsoft.Msagl.DebugHelpers;
using Microsoft.Msagl.Drawing;
using Microsoft.Msagl.Layout.Layered;
using Microsoft.Msagl.Routing;
using Microsoft.Msagl.Routing.ConstrainedDelaunayTriangulation;
using Microsoft.Msagl.Routing.Rectilinear;
using LineSegment = System.Windows.Media.LineSegment;
using Node = Microsoft.Msagl.Core.Layout.Node;
using Point = Microsoft.Msagl.Core.Geometry.Point;
using Polyline = Microsoft.Msagl.Core.Geometry.Curves.Polyline;
using Shape = Microsoft.Msagl.Routing.Shape;
namespace TestForAvalon {
internal class PolygonManager {
int lastGivenId = -1;
readonly Dictionary<Path, Shape> pathsToShapes = new Dictionary<Path, Shape>();
readonly Diagram diagram;
readonly GraphScroller scroller;
Path currentPath;
System.Windows.Point pathStart;
System.Windows.Point pathEnd;
PathSegmentCollection pathSegmentCollection;
Dictionary<Shape, Set<Point>> shapesToInnerPoints = new Dictionary<Shape, Set<Point>>();
public PolygonManager(GraphScroller scroller) {
this.scroller = scroller;
diagram = scroller.Diagram;
}
internal void AttachEvents() {
scroller.MouseDown += scroller_MouseDown;
scroller.MouseMove += scroller_MouseMove;
scroller.MouseUp += scroller_MouseUp;
}
internal void DetachEvents() {
scroller.MouseDown -= scroller_MouseDown;
scroller.MouseMove -= scroller_MouseMove;
scroller.MouseUp -= scroller_MouseUp;
}
void scroller_MouseUp(object sender, MsaglMouseEventArgs e) {
MouseUp();
}
void scroller_MouseMove(object sender, MsaglMouseEventArgs e) {
MouseMove(e);
}
void scroller_MouseDown(object sender, MsaglMouseEventArgs e) {
MouseDown(e);
}
public void MouseMove(MsaglMouseEventArgs e) {
if (currentPath == null) return;
var point = scroller.GetWpfPosition(e);
if (DistanceBetweenWpfPoints(point, pathEnd) < 3 * currentPath.StrokeThickness) return;
pathEnd = point;
pathSegmentCollection.Add(new LineSegment(point, true));
var pathFigure = new PathFigure(pathStart, pathSegmentCollection, true);
var pathFigureCollection = new PathFigureCollection { pathFigure };
var pathGeometry = new PathGeometry(pathFigureCollection);
currentPath.Data = pathGeometry;
}
private double DistanceBetweenWpfPoints(System.Windows.Point a, System.Windows.Point b) {
var dx = a.X - b.X;
var dy = a.Y - b.Y;
return Math.Sqrt(dx * dx + dy * dy);
}
public void MouseUp() {
if (currentPath == null)
return;
if (pathSegmentCollection.Count > 2) {
var col=new System.Windows.Media.Color();
col.A=100;
col.G=255;
currentPath.Stroke=new SolidColorBrush(col);
currentPath.ContextMenu = new ContextMenu();
var path = currentPath;
currentPath.ContextMenu.Items.Add(GraphScroller.CreateMenuItem("Remove polyline", () => RemovePath(path)));
PathToShape(currentPath);
}
currentPath = null;
}
void PathToShape(Path path) {
var shape= new Shape(PolylineFromPath(path));
InsertShapeIntoHierarchy(shape);
pathsToShapes[path] = shape;
}
void InsertShapeIntoHierarchy(Shape shape) {
FindParents(shape);
FindChildren(shape);
}
void FindChildren(Shape shape) {
Set<Shape> successors = GetShapeSuccessors(shape);
foreach (var s in successors)
if (s.Parents.All(h => !successors.Contains(h)))
shape.AddChild(s);
}
void FindParents(Shape shape) {
Set<Shape> ancestors = GetShapeAncestors(shape);
foreach (var s in ancestors)
if (s.Children.All(h => !ancestors.Contains(h)))
s.AddChild(shape);
}
Set<Shape> GetShapeAncestors(Shape shape) {
var ret = new Set<Shape>();
foreach (var sh in pathsToShapes.Values)
if (CurveInsideOther(shape.BoundaryCurve, sh.BoundaryCurve))
ret.Insert(sh);
return ret;
}
Set<Shape> GetShapeSuccessors(Shape shape) {
var ret = new Set<Shape>();
foreach (var sh in pathsToShapes.Values)
if (CurveInsideOther(sh.BoundaryCurve, shape.BoundaryCurve))
ret.Insert(sh);
return ret;
}
///<summary>
///</summary>
///<param name="a"></param>
///<param name="b"></param>
///<returns>true if a is inside b</returns>
static bool CurveInsideOther(ICurve a, ICurve b) {
return b.BoundingBox.Contains(a.BoundingBox) && TestPoints(a).All(p => Curve.PointRelativeToCurveLocation(p, b) != PointLocation.Outside);
}
static IEnumerable<Point> TestPoints(ICurve curve) {
const int n = 10;
double del = (curve.ParEnd - curve.ParStart)/n;
for (int i = 0; i < n; i++)
yield return curve[curve.ParStart + i*del];
}
static ICurve PolylineFromPath(Path path) {
return new Polyline(GetPathPoints(path).Select(p => new Point(p.X, p.Y))) { Closed = true };
}
static IEnumerable<System.Windows.Point> GetPathPoints(Path path) {
var pathGeometry = (PathGeometry)path.Data;
var pathFigure = pathGeometry.Figures.First();
yield return pathFigure.StartPoint;
foreach (var lineSeg in pathFigure.Segments.Cast<LineSegment>())
yield return lineSeg.Point;
}
IComparable CreateId() {
lastGivenId++;
return "unique"+lastGivenId;
}
void RemovePath(Path path) {
var sh = pathsToShapes[path];
pathsToShapes.Remove(path);
diagram.Canvas.Children.Remove(path);
var listToRemove = new List<Shape>();
foreach(var parent in sh.Parents)
listToRemove.Add(parent);
foreach (var parent in listToRemove)
parent.RemoveChild(sh);
listToRemove.Clear();
foreach (var child in sh.Children)
listToRemove.Add(child);
foreach (var s in listToRemove)
s.RemoveParent(sh);
// RouteAroundGroups(erm);
}
public void MouseDown(MsaglMouseEventArgs e) {
StartNewPath(scroller.GetWpfPosition(e));
}
void StartNewPath(System.Windows.Point point) {
var color=new System.Windows.Media.Color();
color.A=255;
color.R=255;
currentPath = new Path
{
Stroke = new SolidColorBrush(color),
StrokeEndLineCap = PenLineCap.Round,
StrokeStartLineCap = PenLineCap.Round,
StrokeLineJoin = PenLineJoin.Round,
StrokeThickness = scroller.GetScale()
};
pathSegmentCollection = new PathSegmentCollection();
pathEnd = pathStart = point;
diagram.Canvas.Children.Add(currentPath);
}
public void ClearGroups() {
diagram.Canvas.Children.Clear();
pathsToShapes.Clear();
}
internal void Tesselate() {
OrientShapes();
double minLength = GetMinSideLength();
SubdividePolylines(minLength);
EnterInnerPoints(minLength);
RunTessellation();
}
private void SubdividePolylines(double minLength) {
foreach (var shape in ParentShapes())
SubdivideUnderShape(shape,minLength);
}
private void SubdivideUnderShape(Shape shape, double minLength) {
SubdividePolyline((Polyline)shape.BoundaryCurve, minLength);
foreach (var ch in shape.Children)
SubdivideUnderShape(ch, minLength);
}
private void SubdividePolyline(Polyline polyline, double minLength) {
var q = new Queue<PolylinePoint>();
foreach (var pp in polyline.PolylinePoints) {
var ppn = pp.NextOnPolyline;
if ((pp.Point - ppn.Point).Length > minLength)
q.Enqueue(pp);
}
while (q.Count > 0) {
var pp = q.Dequeue();
var ppn = pp.NextOnPolyline;
var p = new PolylinePoint(0.5 * (pp.Point + ppn.Point)) { Polyline = polyline };
bool tooBig=(p.Point-pp.Point).Length>minLength;
if (pp.Next != null) {
p.Prev = pp;
p.Next = ppn;
pp.Next = p;
ppn.Prev = p;
if(tooBig){
q.Enqueue(pp);
q.Enqueue(p);
}
} else {
polyline.AddPoint(p.Point);
if(tooBig){
q.Enqueue(polyline.EndPoint);
q.Enqueue(polyline.EndPoint.Prev);
}
}
}
}
private void RunTessellation() {
foreach(var shape in ParentShapes())
TesselateUnderShape(shape);
}
private void TesselateUnderShape(Shape shape) {
var polys=new List<Polyline>(shape.Children.Select(sh=>(Polyline)sh.BoundaryCurve));
polys.Add(shape.BoundaryCurve as Polyline);
var cdt=new Cdt(shapesToInnerPoints[shape], polys,null);
cdt.Run();
Set<CdtTriangle> triangles=cdt.GetTriangles();
cdt.SetInEdges();
CleanUpTriangles(shape, ref triangles,cdt);
foreach(var t in triangles){
AddTriangleToCanvas(t);
}
}
private void CleanUpTriangles(Shape shape, ref Set<CdtTriangle> triangles, Cdt cdt) {
CleanUpExternalTriangles(shape, ref triangles, cdt);
foreach (var sh in shape.Children)
CleanUpInternalTriangles(sh, ref triangles, cdt);
}
private void CleanUpInternalTriangles(Shape shape, ref Set<CdtTriangle> triangles, Cdt cdt) {
Set<CdtTriangle> removedTriangles = new Set<CdtTriangle>();
var poly = (Polyline)shape.BoundaryCurve;
for (var p = poly.StartPoint; p.Next != null; p = p.Next)
FillRemovedForExternalTriangle(p, p.Next, removedTriangles, cdt);
FillRemovedForExternalTriangle(poly.EndPoint, poly.StartPoint, removedTriangles, cdt);
//var l = new List<DebugCurve>();
//l.Add(new DebugCurve(100, 1, "black", poly));
//l.AddRange(removedTriangles.Select(t => new DebugCurve(100, 0.1, "red", new Polyline(t.Sites.Select(s => s.Point).ToArray()) { Closed = true })));
// LayoutAlgorithmSettings.ShowDebugCurvesEnumeration(l);
triangles -= removedTriangles;
}
private void CleanUpExternalTriangles(Shape shape, ref Set<CdtTriangle> triangles, Cdt cdt) {
Set<CdtTriangle> removedTriangles = new Set<CdtTriangle>();
var poly = (Polyline)shape.BoundaryCurve;
for (var p = poly.StartPoint; p.Next != null; p = p.Next)
FillRemovedForExternalTriangle(p, p.Next, removedTriangles, cdt);
FillRemovedForExternalTriangle(poly.EndPoint, poly.StartPoint, removedTriangles, cdt);
//var l = new List<DebugCurve>();
//l.Add(new DebugCurve(100, 1, "black", poly));
//l.AddRange(removedTriangles.Select(t => new DebugCurve(100, 0.1, "red", new Polyline(t.Sites.Select(s => s.Point).ToArray()) { Closed = true })));
//LayoutAlgorithmSettings.ShowDebugCurvesEnumeration(l);
triangles -= removedTriangles;
}
private void FillRemovedForExternalTriangle(PolylinePoint a, PolylinePoint b, Set<CdtTriangle> removedTriangles, Cdt cdt) {
CdtEdge e = FindEdge(a, b, cdt);
if (e.CcwTriangle == null || e.CwTriangle == null) return;
bool aligned = a.Point == e.upperSite.Point;
if (aligned) {
// LayoutAlgorithmSettings.ShowDebugCurves(new DebugCurve(100, 0.1, "black", a.Polyline), new DebugCurve(100, 0.1, "red", new Polyline(e.CcwTriangle.Sites.Select(s => s.Point).ToArray()) { Closed = true }));
FillRemovedConnectedRegion(e.CcwTriangle, removedTriangles);
} else {
// LayoutAlgorithmSettings.ShowDebugCurves(new DebugCurve(100, 0.1, "black", a.Polyline), new DebugCurve(100,0.1,"red", new Polyline(e.CwTriangle.Sites.Select(s => s.Point).ToArray()) { Closed = true }));
FillRemovedConnectedRegion(e.CwTriangle, removedTriangles);
}
}
private void FillRemovedConnectedRegion(CdtTriangle t, Set<CdtTriangle> removedTriangles) {
if (removedTriangles.Contains(t))
return;
var q = new Queue<CdtTriangle>();
q.Enqueue(t);
while (q.Count > 0) {
t = q.Dequeue();
removedTriangles.Insert(t);
foreach(var e in t.Edges)
if (!e.Constrained) {
var tr = e.GetOtherTriangle(t);
if (tr!=null && !removedTriangles.Contains(tr))
q.Enqueue(tr);
}
}
}
private CdtEdge FindEdge(PolylinePoint a, PolylinePoint b, Cdt cdt) {
int aIsAboveB = Cdt.Above(a.Point, b.Point);
System.Diagnostics.Debug.Assert(aIsAboveB != 0);
if (aIsAboveB > 0) {
foreach (var e in cdt.FindSite(a.Point).Edges)
if (e.lowerSite.Point == b.Point)
return e;
} else {
foreach (var e in cdt.FindSite(b.Point).Edges)
if (e.lowerSite.Point == a.Point)
return e;
}
throw new InvalidOperationException("cannot find an edge of a polyline in the tessellation");
}
private void AddTriangleToCanvas(CdtTriangle t) {
var color = new System.Windows.Media.Color();
color.A = 100;
color.B = 255;
var wpfTriangle = new Polygon {
Stroke = new SolidColorBrush(color),
StrokeEndLineCap = PenLineCap.Round,
StrokeStartLineCap = PenLineCap.Round,
StrokeLineJoin = PenLineJoin.Round,
StrokeThickness = scroller.GetScale()
};
PointCollection trianglePoints = new PointCollection();
trianglePoints.Add(ToWpfPoint( t.Sites[0].Point));
trianglePoints.Add(ToWpfPoint(t.Sites[1].Point));
trianglePoints.Add(ToWpfPoint(t.Sites[2].Point));
wpfTriangle.Points = trianglePoints;
diagram.Canvas.Children.Add(wpfTriangle);
}
private System.Windows.Point ToWpfPoint(Point point) {
return new System.Windows.Point(point.X, point.Y);
}
private void EnterInnerPoints(double minLength) {
Set<Point> points = new Set<Point>();
foreach (var shape in ParentShapes()) {
EnterInnerPointsUnderShape(shape, minLength, points);
shapesToInnerPoints[shape] = points;
}
}
private void EnterInnerPointsUnderShape(Shape shape, double l, Set<Point> points) {
var h = l * Math.Sqrt(3) / 2*10;
var box=shape.BoundingBox;
var p = shape.BoundingBox.LeftBottom;
bool odd = false;
while (p.Y < box.Top) {
AddStringToShape(shape, p, box, l, points);
p += new Point(odd? l/2:-l/2 , h);
odd = !odd;
}
}
private void AddStringToShape(Shape shape, Point p, Microsoft.Msagl.Core.Geometry.Rectangle box, double l, Set<Point> points) {
while (p.X <= box.Right) {
if (IsInsideShape(shape, p))
points.Insert(p);
p.X += l;
}
}
private bool IsInsideShape(Shape shape, Point p) {
return Curve.PointRelativeToCurveLocation(p, shape.BoundaryCurve) == PointLocation.Inside &&
shape.Children.All(ch => Curve.PointRelativeToCurveLocation(p, ch.BoundaryCurve) == PointLocation.Outside);
}
private double GetMinSideLength() {
double l = double.PositiveInfinity;
foreach (var s in pathsToShapes.Values) {
var d = s.BoundingBox.Diagonal / 10;
if (d < l)
l = d;
}
return l;
}
private void OrientShapes() {
foreach (var shape in ParentShapes())
OrientUnderShape(shape, true);
}
private IEnumerable<Shape> ParentShapes() {
return pathsToShapes.Values.Where(s => s.Parents == null || s.Parents.Count() == 0);
}
private void OrientUnderShape(Shape shape, bool clockwise) {
shape.BoundaryCurve = OrientPolyline(shape.BoundaryCurve as Polyline, clockwise);
foreach(var sh in shape.Children)
OrientUnderShape(sh,!clockwise);
}
private ICurve OrientPolyline(Polyline polyline, bool clockwise) {
bool isClockwise = IsClockwise(polyline);
if (isClockwise == clockwise)
return polyline;
return polyline.Reverse();
}
private bool IsClockwise(Polyline polyline) {
PolylinePoint convexHullPolyPoint = FindConvexHullPolyPoint(polyline);
return Point.GetTriangleOrientation(convexHullPolyPoint.PrevOnPolyline.Point, convexHullPolyPoint.Point, convexHullPolyPoint.NextOnPolyline.Point) == TriangleOrientation.Clockwise;
}
private static PolylinePoint FindConvexHullPolyPoint(Polyline polyline) {
PolylinePoint convexHullPolyPoint = polyline.StartPoint;
for (var p = polyline.StartPoint.Next; p != null; p = p.Next) {
if (p.Point.Y < convexHullPolyPoint.Point.Y)
convexHullPolyPoint = p;
else if (p.Point.Y > convexHullPolyPoint.Point.Y) continue;
if (p.Point.X < convexHullPolyPoint.Point.X)
convexHullPolyPoint = p;
}
return convexHullPolyPoint;
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using AspNetUpgrade.Actions;
using AspNetUpgrade.Actions.LaunchSettings;
using AspNetUpgrade.Actions.ProjectJson;
using AspNetUpgrade.Actions.Xproj;
using AspNetUpgrade.Migrator.DependencyMigrations;
using AspNetUpgrade.Migrator.DependencyMigrations.RTM;
using AspNetUpgrade.Migrator.ToolMigrations;
using AspNetUpgrade.Model;
using AspNetUpgrade.UpgradeContext;
namespace AspNetUpgrade.Migrator
{
public class ProjectMigrator : BaseProjectMigrator
{
public ProjectMigrator(BaseProjectUpgradeContext context) : base(context)
{
}
/// <summary>
/// Migrates the project.
/// </summary>
/// <param name="options">migration options.</param>
/// <param name="additionalMigrations">any additional migrations to apply.</param>
public void Apply(ProjectMigrationOptions options, IList<IProjectUpgradeAction> additionalMigrations = null)
{
List<IProjectUpgradeAction> migrations = new List<IProjectUpgradeAction>();
var context = this.Context;
//if (options.UpgradeToPreview1)
//{
migrations.AddRange(GetSchemaUpgrades(options, context));
//}
// if (options.UpgradePackagesToRc2)
// {
migrations.AddRange(GetPackagesUpgrades(context, options.PackagesVersion));
// }
if (options.AddNetCoreTargetForApplications)
{
//// Makes applications target .netcoreapp.
var addNetCoreApp = new AddNetCoreFrameworkToApplications("1.0.0-rc2-3002702");
migrations.Add(addNetCoreApp);
}
if (options.AddNetStandardTargetForLibraries)
{
// Adds the netStandard framework, with specified version of NETStandard.Library dependency, to any library project.json's.
var addNetStandard = new AddNetStandardFrameworkToLibrariesJson("netstandard1.5", "1.5.0-rc2-24027");
migrations.Add(addNetStandard);
}
// upgrade to preview 2
//if (options.ToolingVersion)
//{
// migrations.AddRange(GetSchemaUpgrades(options, context));
//}
//if (options.PackagesVersion == ReleaseVersion.RTM)
//{
// migrations.AddRange(GetPackagesUpgrades(context));
//}
// additional migrations to apply
if (additionalMigrations != null && additionalMigrations.Any())
{
migrations.AddRange(additionalMigrations);
}
this.Apply(migrations);
}
private IEnumerable<IProjectUpgradeAction> GetSchemaUpgrades(ProjectMigrationOptions options, BaseProjectUpgradeContext context)
{
var upgradeActions = new List<IProjectUpgradeAction>();
//if (options.PackagesVersion == ReleaseVersion.)
//{
// upgrades the compilation options section.
var compilationOptionsUpgradeAction = new UpgradeCompilationOptionsJson();
upgradeActions.Add(compilationOptionsUpgradeAction);
// moves things to packOptions.
var upgradePackOptions = new UpgradePackOptions();
upgradeActions.Add(upgradePackOptions);
// moves content to the new packOptions and buildOptions / copyToOutput
var moveContent = new MoveContentToNewOptions();
upgradeActions.Add(moveContent);
// moves resources to buildOptions.
var moveResources = new MoveResourcesToBuildOptions();
upgradeActions.Add(moveResources);
// move compile to build options.
var moveCompileToBuildOptions = new MoveCompileToBuildOptions();
upgradeActions.Add(moveCompileToBuildOptions);
// move exclude to build options
var moveExcludeToBuildOptions = new MoveExcludeToBuildOptions();
upgradeActions.Add(moveExcludeToBuildOptions);
// moves things to publishOptions.
var upgradePublishOptions = new UpgradePublishOptions();
upgradeActions.Add(upgradePublishOptions);
// includes appSettings.Json files in copyToOutput
var includeAppSettingsFilesInCopyToOutput = new IncludeAppSettingsFilesInCopyToOutput();
upgradeActions.Add(includeAppSettingsFilesInCopyToOutput);
// includes Views folder in copyToOutput
var includeViewsFolderInCopyToOutput = new IncludeViewsFolderInCopyToOutput();
upgradeActions.Add(includeViewsFolderInCopyToOutput);
// renames the old dnx4YZ TFM's to be the net4YZ Tfm's.
var frameworksUpgradeAction = new MigrateDnxFrameworksToNetFramework452Json();
upgradeActions.Add(frameworksUpgradeAction);
// upgrades xproj file, by updating old dnx imports to new dotnet ones.
var xprojImportsUpgrade = new MigrateProjectImportsFromDnxToDotNet();
upgradeActions.Add(xprojImportsUpgrade);
// updates xproj baseintermediate output path
var xprojUpdateBaseIntermediateOutputPath = new UpdateBaseIntermediateOutputPath();
upgradeActions.Add(xprojUpdateBaseIntermediateOutputPath);
// updates xproj targetFramework
var xprojUpdateTargetFramework = new SetTargetFrameworkVersion(options.TargetFrameworkVersionForXprojFile);
upgradeActions.Add(xprojUpdateTargetFramework);
// updates launch settings
var updateLaunchSettings = new UpdateLaunchSettings();
upgradeActions.Add(updateLaunchSettings);
// }
// if (options.PackagesVersion == ReleaseVersion.RTM)
// {
// NONE NECESSAERY.
// }
return upgradeActions;
}
protected virtual IList<IProjectUpgradeAction> GetPackagesUpgrades(IProjectUpgradeContext projectUpgradeContext, ReleaseVersion version)
{
var upgradeActions = new List<IProjectUpgradeAction>();
//if (version == ReleaseVersion.RC2)
//{
// migrates specific nuget packages where their name has completely changed, and also adds new ones that the project may require.
// this is currently described by a hardcoded list.
ToolingVersion toolingVersion = ToolingVersion.Preview1;
if (version == ReleaseVersion.RTM)
{
toolingVersion = ToolingVersion.Preview2;
}
var nugetPackagesToMigrate = ProjectMigrator.GetRc2DependencyPackageMigrationList(toolingVersion, projectUpgradeContext);
var packageMigrationAction = new MigrateDependencyPackages(nugetPackagesToMigrate);
upgradeActions.Add(packageMigrationAction);
// renames microsoft.aspnet packages to be microsoft.aspnetcore.
var renameAspNetPackagesAction = new RenameAspNetPackagesToAspNetCore();
upgradeActions.Add(renameAspNetPackagesAction);
// updates microsoft. packages to be rc2 version numbers.
var updateMicrosoftPackageVersionNumbersAction = new UpgradeMicrosoftPackageVersionNumbers(version);
upgradeActions.Add(updateMicrosoftPackageVersionNumbersAction);
// renames "commands" to "tools"
var renameCommandstoToolsAndClear = new RenameCommandsToTools();
upgradeActions.Add(renameCommandstoToolsAndClear);
// migrates old command packages to the new tool nuget packages.
var toolPackagestoMigrate = GetToolPackageMigrationList(ToolingVersion.Preview1, projectUpgradeContext);
var migrateToolPackages = new MigrateToolPackages(toolPackagestoMigrate);
upgradeActions.Add(migrateToolPackages);
// }
if (version == ReleaseVersion.RTM)
{
// migrates specific nuget packages where their name has completely changed, and also adds new ones that the project may require.
// this is currently described by a hardcoded list.
var nugetPackagesToMigrateRTM = ProjectMigrator.GetRtmDependencyPackageMigrationList(ToolingVersion.Preview2, projectUpgradeContext);
var packageMigrationActionRTM = new MigrateDependencyPackages(nugetPackagesToMigrateRTM);
upgradeActions.Add(packageMigrationActionRTM);
// updates remaining microsoft rc2 packages to be rtm version numbers i.e 1.0.0 instead of 1.0.0-rc2-final
var updateMicrosoftPackageVersionNumbersActionRtm = new UpgradeMicrosoftPackageVersionNumbers(version);
upgradeActions.Add(updateMicrosoftPackageVersionNumbersActionRtm);
// migrates old command packages to the new tool nuget packages.
var toolPackagestoMigrateRtm = GetToolPackageMigrationList(ToolingVersion.Preview2, projectUpgradeContext);
var migrateToolPackagesRtm = new MigrateToolPackages(toolPackagestoMigrateRtm);
upgradeActions.Add(migrateToolPackagesRtm);
}
return upgradeActions;
}
public static List<DependencyPackageMigrationInfo> GetRc2DependencyPackageMigrationList(ToolingVersion targetToolingVersion, IProjectUpgradeContext projectContext)
{
var packageMigrationProviders = new List<IDependencyPackageMigrationProvider>();
packageMigrationProviders.Add(new AspNetDependencyPackageMigrationProvider());
packageMigrationProviders.Add(new EntityFrameworkDependencyPackageMigrationProvider());
packageMigrationProviders.Add(new FileProviderDependencyPackageMigrationProvider());
packageMigrationProviders.Add(new MicrosoftExtensionsDependencyPackageMigrationProvider());
packageMigrationProviders.Add(new AutofacPackageMigrationProvider());
var migrations = new List<DependencyPackageMigrationInfo>();
foreach (var provider in packageMigrationProviders)
{
var packageMigrations = provider.GetPackageMigrations(targetToolingVersion, projectContext);
migrations.AddRange(packageMigrations);
}
return migrations;
// Microsoft.VisualStudio.Web.BrowserLink.Loader?
}
public static List<DependencyPackageMigrationInfo> GetRtmDependencyPackageMigrationList(ToolingVersion targetToolingVersion, IProjectUpgradeContext projectContext)
{
var packageMigrationProviders = new List<IDependencyPackageMigrationProvider>();
// packageMigrationProviders.Add(new AspNetDependencyPackageMigrationProvider());
packageMigrationProviders.Add(new EntityFrameworkRtmDependencyPackageMigrationProvider());
packageMigrationProviders.Add(new AspNetRtmDependencyPackageMigrationProvider());
var migrations = new List<DependencyPackageMigrationInfo>();
foreach (var provider in packageMigrationProviders)
{
var packageMigrations = provider.GetPackageMigrations(targetToolingVersion, projectContext);
migrations.AddRange(packageMigrations);
}
return migrations;
// Microsoft.VisualStudio.Web.BrowserLink.Loader?
}
public static List<ToolPackageMigrationInfo> GetToolPackageMigrationList(ToolingVersion targetToolingVersion, IProjectUpgradeContext projectContext)
{
var toolMigrationProviders = new List<IToolPackageMigrationProvider>();
toolMigrationProviders.Add(new CommonToolPackagesMigration());
var migrations = new List<ToolPackageMigrationInfo>();
foreach (var provider in toolMigrationProviders)
{
var packageMigrations = provider.GetPackageMigrations(targetToolingVersion, projectContext);
migrations.AddRange(packageMigrations);
}
return migrations;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Web;
using Newtonsoft.Json;
using Umbraco.Core;
using Umbraco.Core.Logging;
using umbraco.cms.businesslogic.web;
using umbraco.cms.businesslogic.macro;
using Umbraco.Core.IO;
using Umbraco.Core.Models;
using File = System.IO.File;
using Template = umbraco.cms.businesslogic.template.Template;
namespace umbraco.cms.businesslogic.packager
{
public class CreatedPackage
{
public static CreatedPackage GetById(int id)
{
var pack = new CreatedPackage();
pack.Data = data.Package(id, IOHelper.MapPath(Settings.CreatedPackagesSettings));
return pack;
}
public static CreatedPackage MakeNew(string name)
{
var pack = new CreatedPackage();
pack.Data = data.MakeNew(name, IOHelper.MapPath(Settings.CreatedPackagesSettings));
var e = new NewEventArgs();
pack.OnNew(e);
return pack;
}
public void Save()
{
var e = new SaveEventArgs();
FireBeforeSave(e);
if (!e.Cancel)
{
data.Save(this.Data, IOHelper.MapPath(Settings.CreatedPackagesSettings));
FireAfterSave(e);
}
}
public void Delete()
{
var e = new DeleteEventArgs();
FireBeforeDelete(e);
if (!e.Cancel)
{
data.Delete(this.Data.Id, IOHelper.MapPath(Settings.CreatedPackagesSettings));
FireAfterDelete(e);
}
}
public PackageInstance Data { get; set; }
public static List<CreatedPackage> GetAllCreatedPackages()
{
var val = new List<CreatedPackage>();
foreach (var pack in data.GetAllPackages(IOHelper.MapPath(Settings.CreatedPackagesSettings)))
{
var crPack = new CreatedPackage();
crPack.Data = pack;
val.Add(crPack);
}
return val;
}
private static XmlDocument _packageManifest;
private static void CreatePackageManifest()
{
_packageManifest = new XmlDocument();
var xmldecl = _packageManifest.CreateXmlDeclaration("1.0", "UTF-8", "no");
_packageManifest.AppendChild(xmldecl);
//root node
XmlNode umbPackage = _packageManifest.CreateElement("umbPackage");
_packageManifest.AppendChild(umbPackage);
//Files node
umbPackage.AppendChild(_packageManifest.CreateElement("files"));
}
private static void AppendElement(XmlNode node)
{
var root = _packageManifest.SelectSingleNode("/umbPackage");
root.AppendChild(node);
}
public void Publish()
{
var package = this;
var pack = package.Data;
var e = new PublishEventArgs();
package.FireBeforePublish(e);
if (e.Cancel == false)
{
var outInt = 0;
//Path checking...
var localPath = IOHelper.MapPath(SystemDirectories.Media + "/" + pack.Folder);
if (Directory.Exists(localPath) == false)
Directory.CreateDirectory(localPath);
//Init package file...
CreatePackageManifest();
//Info section..
AppendElement(utill.PackageInfo(pack, _packageManifest));
//Documents and tags...
var contentNodeId = 0;
if (string.IsNullOrEmpty(pack.ContentNodeId) == false && int.TryParse(pack.ContentNodeId, out contentNodeId))
{
if (contentNodeId > 0)
{
//Create the Documents/DocumentSet node
XmlNode documents = _packageManifest.CreateElement("Documents");
XmlNode documentSet = _packageManifest.CreateElement("DocumentSet");
XmlAttribute importMode = _packageManifest.CreateAttribute("importMode", "");
importMode.Value = "root";
documentSet.Attributes.Append(importMode);
documents.AppendChild(documentSet);
//load content from umbraco.
var umbDocument = new Document(contentNodeId);
documentSet.AppendChild(umbDocument.ToXml(_packageManifest, pack.ContentLoadChildNodes));
AppendElement(documents);
////Create the TagProperties node - this is used to store a definition for all
//// document properties that are tags, this ensures that we can re-import tags properly
//XmlNode tagProps = _packageManifest.CreateElement("TagProperties");
////before we try to populate this, we'll do a quick lookup to see if any of the documents
//// being exported contain published tags.
//var allExportedIds = documents.SelectNodes("//@id").Cast<XmlNode>()
// .Select(x => x.Value.TryConvertTo<int>())
// .Where(x => x.Success)
// .Select(x => x.Result)
// .ToArray();
//var allContentTags = new List<ITag>();
//foreach (var exportedId in allExportedIds)
//{
// allContentTags.AddRange(
// ApplicationContext.Current.Services.TagService.GetTagsForEntity(exportedId));
//}
////This is pretty round-about but it works. Essentially we need to get the properties that are tagged
//// but to do that we need to lookup by a tag (string)
//var allTaggedEntities = new List<TaggedEntity>();
//foreach (var group in allContentTags.Select(x => x.Group).Distinct())
//{
// allTaggedEntities.AddRange(
// ApplicationContext.Current.Services.TagService.GetTaggedContentByTagGroup(group));
//}
////Now, we have all property Ids/Aliases and their referenced document Ids and tags
//var allExportedTaggedEntities = allTaggedEntities.Where(x => allExportedIds.Contains(x.EntityId))
// .DistinctBy(x => x.EntityId)
// .OrderBy(x => x.EntityId);
//foreach (var taggedEntity in allExportedTaggedEntities)
//{
// foreach (var taggedProperty in taggedEntity.TaggedProperties.Where(x => x.Tags.Any()))
// {
// XmlNode tagProp = _packageManifest.CreateElement("TagProperty");
// var docId = _packageManifest.CreateAttribute("docId", "");
// docId.Value = taggedEntity.EntityId.ToString(CultureInfo.InvariantCulture);
// tagProp.Attributes.Append(docId);
// var propertyAlias = _packageManifest.CreateAttribute("propertyAlias", "");
// propertyAlias.Value = taggedProperty.PropertyTypeAlias;
// tagProp.Attributes.Append(propertyAlias);
// var group = _packageManifest.CreateAttribute("group", "");
// group.Value = taggedProperty.Tags.First().Group;
// tagProp.Attributes.Append(group);
// tagProp.AppendChild(_packageManifest.CreateCDataSection(
// JsonConvert.SerializeObject(taggedProperty.Tags.Select(x => x.Text).ToArray())));
// tagProps.AppendChild(tagProp);
// }
//}
//AppendElement(tagProps);
}
}
//Document types..
var dtl = new List<DocumentType>();
var docTypes = _packageManifest.CreateElement("DocumentTypes");
foreach (var dtId in pack.Documenttypes)
{
if (int.TryParse(dtId, out outInt))
{
DocumentType docT = new DocumentType(outInt);
AddDocumentType(docT, ref dtl);
}
}
foreach (DocumentType d in dtl)
{
docTypes.AppendChild(d.ToXml(_packageManifest));
}
AppendElement(docTypes);
//Templates
var templates = _packageManifest.CreateElement("Templates");
foreach (var templateId in pack.Templates)
{
if (int.TryParse(templateId, out outInt))
{
var t = new Template(outInt);
templates.AppendChild(t.ToXml(_packageManifest));
}
}
AppendElement(templates);
//Stylesheets
var stylesheets = _packageManifest.CreateElement("Stylesheets");
foreach (var ssId in pack.Stylesheets)
{
if (int.TryParse(ssId, out outInt))
{
var s = new StyleSheet(outInt);
stylesheets.AppendChild(s.ToXml(_packageManifest));
}
}
AppendElement(stylesheets);
//Macros
var macros = _packageManifest.CreateElement("Macros");
foreach (var macroId in pack.Macros)
{
if (int.TryParse(macroId, out outInt))
{
macros.AppendChild(utill.Macro(int.Parse(macroId), true, localPath, _packageManifest));
}
}
AppendElement(macros);
//Dictionary Items
var dictionaryItems = _packageManifest.CreateElement("DictionaryItems");
foreach (var dictionaryId in pack.DictionaryItems)
{
if (int.TryParse(dictionaryId, out outInt))
{
var di = new Dictionary.DictionaryItem(outInt);
dictionaryItems.AppendChild(di.ToXml(_packageManifest));
}
}
AppendElement(dictionaryItems);
//Languages
var languages = _packageManifest.CreateElement("Languages");
foreach (var langId in pack.Languages)
{
if (int.TryParse(langId, out outInt))
{
var lang = new language.Language(outInt);
languages.AppendChild(lang.ToXml(_packageManifest));
}
}
AppendElement(languages);
//Datatypes
var dataTypes = _packageManifest.CreateElement("DataTypes");
foreach (var dtId in pack.DataTypes)
{
if (int.TryParse(dtId, out outInt))
{
datatype.DataTypeDefinition dtd = new datatype.DataTypeDefinition(outInt);
dataTypes.AppendChild(dtd.ToXml(_packageManifest));
}
}
AppendElement(dataTypes);
//Files
foreach (var fileName in pack.Files)
{
utill.AppendFileToManifest(fileName, localPath, _packageManifest);
}
//Load control on install...
if (string.IsNullOrEmpty(pack.LoadControl) == false)
{
XmlNode control = _packageManifest.CreateElement("control");
control.InnerText = pack.LoadControl;
utill.AppendFileToManifest(pack.LoadControl, localPath, _packageManifest);
AppendElement(control);
}
//Actions
if (string.IsNullOrEmpty(pack.Actions) == false)
{
try
{
var xdActions = new XmlDocument();
xdActions.LoadXml("<Actions>" + pack.Actions + "</Actions>");
var actions = xdActions.DocumentElement.SelectSingleNode(".");
if (actions != null)
{
actions = _packageManifest.ImportNode(actions, true).Clone();
AppendElement(actions);
}
}
catch { }
}
var manifestFileName = localPath + "/package.xml";
if (File.Exists(manifestFileName))
File.Delete(manifestFileName);
_packageManifest.Save(manifestFileName);
_packageManifest = null;
//string packPath = Settings.PackagerRoot.Replace(System.IO.Path.DirectorySeparatorChar.ToString(), "/") + "/" + pack.Name.Replace(' ', '_') + "_" + pack.Version.Replace(' ', '_') + "." + Settings.PackageFileExtension;
// check if there's a packages directory below media
var packagesDirectory = SystemDirectories.Media + "/created-packages";
if (Directory.Exists(IOHelper.MapPath(packagesDirectory)) == false)
{
Directory.CreateDirectory(IOHelper.MapPath(packagesDirectory));
}
var packPath = packagesDirectory + "/" + (pack.Name + "_" + pack.Version).Replace(' ', '_') + "." + Settings.PackageFileExtension;
utill.ZipPackage(localPath, IOHelper.MapPath(packPath));
pack.PackagePath = packPath;
if (pack.PackageGuid.Trim() == "")
pack.PackageGuid = Guid.NewGuid().ToString();
package.Save();
//Clean up..
File.Delete(localPath + "/package.xml");
Directory.Delete(localPath, true);
package.FireAfterPublish(e);
}
}
private void AddDocumentType(DocumentType dt, ref List<DocumentType> dtl)
{
if (dt.MasterContentType != 0)
{
//first add masters
var mDocT = new DocumentType(dt.MasterContentType);
AddDocumentType(mDocT, ref dtl);
}
if (dtl.Contains(dt) == false)
{
dtl.Add(dt);
}
}
//EVENTS
public delegate void SaveEventHandler(CreatedPackage sender, SaveEventArgs e);
public delegate void NewEventHandler(CreatedPackage sender, NewEventArgs e);
public delegate void PublishEventHandler(CreatedPackage sender, PublishEventArgs e);
public delegate void DeleteEventHandler(CreatedPackage sender, DeleteEventArgs e);
/// <summary>
/// Occurs when a macro is saved.
/// </summary>
public static event SaveEventHandler BeforeSave;
protected virtual void FireBeforeSave(SaveEventArgs e)
{
if (BeforeSave != null)
BeforeSave(this, e);
}
public static event SaveEventHandler AfterSave;
protected virtual void FireAfterSave(SaveEventArgs e)
{
if (AfterSave != null)
AfterSave(this, e);
}
public static event NewEventHandler New;
protected virtual void OnNew(NewEventArgs e)
{
if (New != null)
New(this, e);
}
public static event DeleteEventHandler BeforeDelete;
protected virtual void FireBeforeDelete(DeleteEventArgs e)
{
if (BeforeDelete != null)
BeforeDelete(this, e);
}
public static event DeleteEventHandler AfterDelete;
protected virtual void FireAfterDelete(DeleteEventArgs e)
{
if (AfterDelete != null)
AfterDelete(this, e);
}
public static event PublishEventHandler BeforePublish;
protected virtual void FireBeforePublish(PublishEventArgs e)
{
if (BeforePublish != null)
BeforePublish(this, e);
}
public static event PublishEventHandler AfterPublish;
protected virtual void FireAfterPublish(PublishEventArgs e)
{
if (AfterPublish != null)
AfterPublish(this, e);
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityModel;
using IdentityServer4.Configuration;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Stores;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace IdentityServer4.Services
{
/// <summary>
/// Default token service
/// </summary>
public class DefaultTokenService : ITokenService
{
/// <summary>
/// The logger
/// </summary>
protected readonly ILogger Logger;
/// <summary>
/// The HTTP context accessor
/// </summary>
protected readonly IHttpContextAccessor ContextAccessor;
/// <summary>
/// The claims provider
/// </summary>
protected readonly IClaimsService ClaimsProvider;
/// <summary>
/// The reference token store
/// </summary>
protected readonly IReferenceTokenStore ReferenceTokenStore;
/// <summary>
/// The signing service
/// </summary>
protected readonly ITokenCreationService CreationService;
/// <summary>
/// The clock
/// </summary>
protected readonly ISystemClock Clock;
/// <summary>
/// The key material service
/// </summary>
protected readonly IKeyMaterialService KeyMaterialService;
/// <summary>
/// The IdentityServer options
/// </summary>
protected readonly IdentityServerOptions Options;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultTokenService" /> class.
/// </summary>
/// <param name="claimsProvider">The claims provider.</param>
/// <param name="referenceTokenStore">The reference token store.</param>
/// <param name="creationService">The signing service.</param>
/// <param name="contextAccessor">The HTTP context accessor.</param>
/// <param name="clock">The clock.</param>
/// <param name="keyMaterialService"></param>
/// <param name="options">The IdentityServer options</param>
/// <param name="logger">The logger.</param>
public DefaultTokenService(
IClaimsService claimsProvider,
IReferenceTokenStore referenceTokenStore,
ITokenCreationService creationService,
IHttpContextAccessor contextAccessor,
ISystemClock clock,
IKeyMaterialService keyMaterialService,
IdentityServerOptions options,
ILogger<DefaultTokenService> logger)
{
ContextAccessor = contextAccessor;
ClaimsProvider = claimsProvider;
ReferenceTokenStore = referenceTokenStore;
CreationService = creationService;
Clock = clock;
KeyMaterialService = keyMaterialService;
Options = options;
Logger = logger;
}
/// <summary>
/// Creates an identity token.
/// </summary>
/// <param name="request">The token creation request.</param>
/// <returns>
/// An identity token
/// </returns>
public virtual async Task<Token> CreateIdentityTokenAsync(TokenCreationRequest request)
{
Logger.LogTrace("Creating identity token");
request.Validate();
// todo: Dom, add a test for this. validate the at and c hashes are correct for the id_token when the client's alg doesn't match the server default.
var credential = await KeyMaterialService.GetSigningCredentialsAsync(request.ValidatedRequest.Client.AllowedIdentityTokenSigningAlgorithms);
if (credential == null)
{
throw new InvalidOperationException("No signing credential is configured.");
}
var signingAlgorithm = credential.Algorithm;
// host provided claims
var claims = new List<Claim>();
// if nonce was sent, must be mirrored in id token
if (request.Nonce.IsPresent())
{
claims.Add(new Claim(JwtClaimTypes.Nonce, request.Nonce));
}
// add iat claim
claims.Add(new Claim(JwtClaimTypes.IssuedAt, Clock.UtcNow.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64));
// add at_hash claim
if (request.AccessTokenToHash.IsPresent())
{
claims.Add(new Claim(JwtClaimTypes.AccessTokenHash, CryptoHelper.CreateHashClaimValue(request.AccessTokenToHash, signingAlgorithm)));
}
// add c_hash claim
if (request.AuthorizationCodeToHash.IsPresent())
{
claims.Add(new Claim(JwtClaimTypes.AuthorizationCodeHash, CryptoHelper.CreateHashClaimValue(request.AuthorizationCodeToHash, signingAlgorithm)));
}
// add s_hash claim
if (request.StateHash.IsPresent())
{
claims.Add(new Claim(JwtClaimTypes.StateHash, request.StateHash));
}
// add sid if present
if (request.ValidatedRequest.SessionId.IsPresent())
{
claims.Add(new Claim(JwtClaimTypes.SessionId, request.ValidatedRequest.SessionId));
}
claims.AddRange(await ClaimsProvider.GetIdentityTokenClaimsAsync(
request.Subject,
request.Resources,
request.IncludeAllIdentityClaims,
request.ValidatedRequest));
var issuer = ContextAccessor.HttpContext.GetIdentityServerIssuerUri();
var token = new Token(OidcConstants.TokenTypes.IdentityToken)
{
CreationTime = Clock.UtcNow.UtcDateTime,
Audiences = { request.ValidatedRequest.Client.ClientId },
Issuer = issuer,
Lifetime = request.ValidatedRequest.Client.IdentityTokenLifetime,
Claims = claims.Distinct(new ClaimComparer()).ToList(),
ClientId = request.ValidatedRequest.Client.ClientId,
AccessTokenType = request.ValidatedRequest.AccessTokenType,
AllowedSigningAlgorithms = request.ValidatedRequest.Client.AllowedIdentityTokenSigningAlgorithms
};
return token;
}
/// <summary>
/// Creates an access token.
/// </summary>
/// <param name="request">The token creation request.</param>
/// <returns>
/// An access token
/// </returns>
public virtual async Task<Token> CreateAccessTokenAsync(TokenCreationRequest request)
{
Logger.LogTrace("Creating access token");
request.Validate();
var claims = new List<Claim>();
claims.AddRange(await ClaimsProvider.GetAccessTokenClaimsAsync(
request.Subject,
request.Resources,
request.ValidatedRequest));
if (request.ValidatedRequest.Client.IncludeJwtId)
{
claims.Add(new Claim(JwtClaimTypes.JwtId, CryptoRandom.CreateUniqueId(16)));
}
var issuer = ContextAccessor.HttpContext.GetIdentityServerIssuerUri();
var token = new Token(OidcConstants.TokenTypes.AccessToken)
{
CreationTime = Clock.UtcNow.UtcDateTime,
Issuer = issuer,
Lifetime = request.ValidatedRequest.AccessTokenLifetime,
Claims = claims.Distinct(new ClaimComparer()).ToList(),
ClientId = request.ValidatedRequest.Client.ClientId,
AccessTokenType = request.ValidatedRequest.AccessTokenType,
AllowedSigningAlgorithms = request.Resources.ApiResources.FindMatchingSigningAlgorithms()
};
if (Options.EmitLegacyResourceAudienceClaim)
{
token.Audiences.Add(string.Format(IdentityServerConstants.AccessTokenAudience, issuer.EnsureTrailingSlash()));
}
// add cnf if present
if (request.ValidatedRequest.Confirmation.IsPresent())
{
token.Confirmation = request.ValidatedRequest.Confirmation;
}
else
{
if (Options.MutualTls.AlwaysEmitConfirmationClaim)
{
var clientCertificate = await ContextAccessor.HttpContext.Connection.GetClientCertificateAsync();
if (clientCertificate != null)
{
token.Confirmation = clientCertificate.CreateThumbprintCnf();
}
}
}
foreach (var api in request.Resources.ApiResources)
{
if (api.Name.IsPresent())
{
token.Audiences.Add(api.Name);
}
}
return token;
}
/// <summary>
/// Creates a serialized and protected security token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns>
/// A security token in serialized form
/// </returns>
/// <exception cref="System.InvalidOperationException">Invalid token type.</exception>
public virtual async Task<string> CreateSecurityTokenAsync(Token token)
{
string tokenResult;
if (token.Type == OidcConstants.TokenTypes.AccessToken)
{
if (token.AccessTokenType == AccessTokenType.Jwt)
{
Logger.LogTrace("Creating JWT access token");
tokenResult = await CreationService.CreateTokenAsync(token);
}
else
{
Logger.LogTrace("Creating reference access token");
var handle = await ReferenceTokenStore.StoreReferenceTokenAsync(token);
tokenResult = handle;
}
}
else if (token.Type == OidcConstants.TokenTypes.IdentityToken)
{
Logger.LogTrace("Creating JWT identity token");
tokenResult = await CreationService.CreateTokenAsync(token);
}
else
{
throw new InvalidOperationException("Invalid token type.");
}
return tokenResult;
}
}
}
| |
# CS_ARCH_MIPS, CS_MODE_MIPS32+CS_MODE_BIG_ENDIAN, None
0x78,0x04,0x4e,0x90 = add_a.b $w26, $w9, $w4
0x78,0x3f,0xdd,0xd0 = add_a.h $w23, $w27, $w31
0x78,0x56,0x32,0xd0 = add_a.w $w11, $w6, $w22
0x78,0x60,0x51,0x90 = add_a.d $w6, $w10, $w0
0x78,0x93,0xc4,0xd0 = adds_a.b $w19, $w24, $w19
0x78,0xa4,0x36,0x50 = adds_a.h $w25, $w6, $w4
0x78,0xdb,0x8e,0x50 = adds_a.w $w25, $w17, $w27
0x78,0xfa,0x93,0xd0 = adds_a.d $w15, $w18, $w26
0x79,0x13,0x5f,0x50 = adds_s.b $w29, $w11, $w19
0x79,0x3a,0xb9,0x50 = adds_s.h $w5, $w23, $w26
0x79,0x4d,0x74,0x10 = adds_s.w $w16, $w14, $w13
0x79,0x7c,0x70,0x90 = adds_s.d $w2, $w14, $w28
0x79,0x8e,0x88,0xd0 = adds_u.b $w3, $w17, $w14
0x79,0xa4,0xf2,0x90 = adds_u.h $w10, $w30, $w4
0x79,0xd4,0x93,0xd0 = adds_u.w $w15, $w18, $w20
0x79,0xe9,0x57,0x90 = adds_u.d $w30, $w10, $w9
0x78,0x15,0xa6,0x0e = addv.b $w24, $w20, $w21
0x78,0x3b,0x69,0x0e = addv.h $w4, $w13, $w27
0x78,0x4e,0x5c,0xce = addv.w $w19, $w11, $w14
0x78,0x7f,0xa8,0x8e = addv.d $w2, $w21, $w31
0x7a,0x03,0x85,0xd1 = asub_s.b $w23, $w16, $w3
0x7a,0x39,0x8d,0x91 = asub_s.h $w22, $w17, $w25
0x7a,0x49,0x0e,0x11 = asub_s.w $w24, $w1, $w9
0x7a,0x6c,0x63,0x51 = asub_s.d $w13, $w12, $w12
0x7a,0x8b,0xea,0x91 = asub_u.b $w10, $w29, $w11
0x7a,0xaf,0x4c,0x91 = asub_u.h $w18, $w9, $w15
0x7a,0xdf,0x9a,0x91 = asub_u.w $w10, $w19, $w31
0x7a,0xe0,0x54,0x51 = asub_u.d $w17, $w10, $w0
0x7a,0x01,0x28,0x90 = ave_s.b $w2, $w5, $w1
0x7a,0x29,0x9c,0x10 = ave_s.h $w16, $w19, $w9
0x7a,0x45,0xfc,0x50 = ave_s.w $w17, $w31, $w5
0x7a,0x6a,0xce,0xd0 = ave_s.d $w27, $w25, $w10
0x7a,0x89,0x9c,0x10 = ave_u.b $w16, $w19, $w9
0x7a,0xab,0xe7,0x10 = ave_u.h $w28, $w28, $w11
0x7a,0xcb,0x62,0xd0 = ave_u.w $w11, $w12, $w11
0x7a,0xfc,0x9f,0x90 = ave_u.d $w30, $w19, $w28
0x7b,0x02,0x86,0x90 = aver_s.b $w26, $w16, $w2
0x7b,0x3b,0xdf,0xd0 = aver_s.h $w31, $w27, $w27
0x7b,0x59,0x97,0x10 = aver_s.w $w28, $w18, $w25
0x7b,0x7b,0xaf,0x50 = aver_s.d $w29, $w21, $w27
0x7b,0x83,0xd7,0x50 = aver_u.b $w29, $w26, $w3
0x7b,0xa9,0x94,0x90 = aver_u.h $w18, $w18, $w9
0x7b,0xdd,0xcc,0x50 = aver_u.w $w17, $w25, $w29
0x7b,0xf3,0xb5,0x90 = aver_u.d $w22, $w22, $w19
0x79,0x9d,0x78,0x8d = bclr.b $w2, $w15, $w29
0x79,0xbc,0xac,0x0d = bclr.h $w16, $w21, $w28
0x79,0xc9,0x14,0xcd = bclr.w $w19, $w2, $w9
0x79,0xe4,0xfe,0xcd = bclr.d $w27, $w31, $w4
0x7b,0x18,0x81,0x4d = binsl.b $w5, $w16, $w24
0x7b,0x2a,0x2f,0x8d = binsl.h $w30, $w5, $w10
0x7b,0x4d,0x7b,0x8d = binsl.w $w14, $w15, $w13
0x7b,0x6c,0xa5,0xcd = binsl.d $w23, $w20, $w12
0x7b,0x82,0x5d,0x8d = binsr.b $w22, $w11, $w2
0x7b,0xa6,0xd0,0x0d = binsr.h $w0, $w26, $w6
0x7b,0xdc,0x1e,0x8d = binsr.w $w26, $w3, $w28
0x7b,0xf5,0x00,0x0d = binsr.d $w0, $w0, $w21
0x7a,0x98,0x58,0x0d = bneg.b $w0, $w11, $w24
0x7a,0xa4,0x87,0x0d = bneg.h $w28, $w16, $w4
0x7a,0xd3,0xd0,0xcd = bneg.w $w3, $w26, $w19
0x7a,0xef,0xeb,0x4d = bneg.d $w13, $w29, $w15
0x7a,0x1f,0x2f,0xcd = bset.b $w31, $w5, $w31
0x7a,0x26,0x63,0x8d = bset.h $w14, $w12, $w6
0x7a,0x4c,0x4f,0xcd = bset.w $w31, $w9, $w12
0x7a,0x65,0xb1,0x4d = bset.d $w5, $w22, $w5
0x78,0x12,0xff,0xcf = ceq.b $w31, $w31, $w18
0x78,0x29,0xda,0x8f = ceq.h $w10, $w27, $w9
0x78,0x4e,0x2a,0x4f = ceq.w $w9, $w5, $w14
0x78,0x60,0x89,0x4f = ceq.d $w5, $w17, $w0
0x7a,0x09,0x25,0xcf = cle_s.b $w23, $w4, $w9
0x7a,0x33,0xdd,0x8f = cle_s.h $w22, $w27, $w19
0x7a,0x4a,0xd7,0x8f = cle_s.w $w30, $w26, $w10
0x7a,0x6a,0x2c,0x8f = cle_s.d $w18, $w5, $w10
0x7a,0x80,0xc8,0x4f = cle_u.b $w1, $w25, $w0
0x7a,0xbd,0x01,0xcf = cle_u.h $w7, $w0, $w29
0x7a,0xc1,0x96,0x4f = cle_u.w $w25, $w18, $w1
0x7a,0xfe,0x01,0x8f = cle_u.d $w6, $w0, $w30
0x79,0x15,0x16,0x4f = clt_s.b $w25, $w2, $w21
0x79,0x29,0x98,0x8f = clt_s.h $w2, $w19, $w9
0x79,0x50,0x45,0xcf = clt_s.w $w23, $w8, $w16
0x79,0x6c,0xf1,0xcf = clt_s.d $w7, $w30, $w12
0x79,0x8d,0xf8,0x8f = clt_u.b $w2, $w31, $w13
0x79,0xb7,0xfc,0x0f = clt_u.h $w16, $w31, $w23
0x79,0xc9,0xc0,0xcf = clt_u.w $w3, $w24, $w9
0x79,0xe1,0x01,0xcf = clt_u.d $w7, $w0, $w1
0x7a,0x12,0x1f,0x52 = div_s.b $w29, $w3, $w18
0x7a,0x2d,0x84,0x52 = div_s.h $w17, $w16, $w13
0x7a,0x5e,0xc9,0x12 = div_s.w $w4, $w25, $w30
0x7a,0x74,0x4f,0xd2 = div_s.d $w31, $w9, $w20
0x7a,0x8a,0xe9,0x92 = div_u.b $w6, $w29, $w10
0x7a,0xae,0xae,0x12 = div_u.h $w24, $w21, $w14
0x7a,0xd9,0x77,0x52 = div_u.w $w29, $w14, $w25
0x7a,0xf5,0x0f,0xd2 = div_u.d $w31, $w1, $w21
0x78,0x39,0xb5,0xd3 = dotp_s.h $w23, $w22, $w25
0x78,0x45,0x75,0x13 = dotp_s.w $w20, $w14, $w5
0x78,0x76,0x14,0x53 = dotp_s.d $w17, $w2, $w22
0x78,0xa6,0x13,0x53 = dotp_u.h $w13, $w2, $w6
0x78,0xd5,0xb3,0xd3 = dotp_u.w $w15, $w22, $w21
0x78,0xfa,0x81,0x13 = dotp_u.d $w4, $w16, $w26
0x79,0x36,0xe0,0x53 = dpadd_s.h $w1, $w28, $w22
0x79,0x4c,0x0a,0x93 = dpadd_s.w $w10, $w1, $w12
0x79,0x7b,0xa8,0xd3 = dpadd_s.d $w3, $w21, $w27
0x79,0xb4,0x2c,0x53 = dpadd_u.h $w17, $w5, $w20
0x79,0xd0,0x46,0x13 = dpadd_u.w $w24, $w8, $w16
0x79,0xf0,0xeb,0xd3 = dpadd_u.d $w15, $w29, $w16
0x7a,0x2c,0x59,0x13 = dpsub_s.h $w4, $w11, $w12
0x7a,0x46,0x39,0x13 = dpsub_s.w $w4, $w7, $w6
0x7a,0x7c,0x67,0xd3 = dpsub_s.d $w31, $w12, $w28
0x7a,0xb1,0xc9,0x13 = dpsub_u.h $w4, $w25, $w17
0x7a,0xd0,0xcc,0xd3 = dpsub_u.w $w19, $w25, $w16
0x7a,0xfa,0x51,0xd3 = dpsub_u.d $w7, $w10, $w26
0x7a,0x22,0xc7,0x15 = hadd_s.h $w28, $w24, $w2
0x7a,0x4b,0x8e,0x15 = hadd_s.w $w24, $w17, $w11
0x7a,0x74,0x7c,0x55 = hadd_s.d $w17, $w15, $w20
0x7a,0xb1,0xeb,0x15 = hadd_u.h $w12, $w29, $w17
0x7a,0xc6,0x2a,0x55 = hadd_u.w $w9, $w5, $w6
0x7a,0xe6,0xa0,0x55 = hadd_u.d $w1, $w20, $w6
0x7b,0x3d,0x74,0x15 = hsub_s.h $w16, $w14, $w29
0x7b,0x4b,0x6a,0x55 = hsub_s.w $w9, $w13, $w11
0x7b,0x6e,0x97,0x95 = hsub_s.d $w30, $w18, $w14
0x7b,0xae,0x61,0xd5 = hsub_u.h $w7, $w12, $w14
0x7b,0xc5,0x2d,0x55 = hsub_u.w $w21, $w5, $w5
0x7b,0xff,0x62,0xd5 = hsub_u.d $w11, $w12, $w31
0x7b,0x1e,0x84,0x94 = ilvev.b $w18, $w16, $w30
0x7b,0x2d,0x03,0x94 = ilvev.h $w14, $w0, $w13
0x7b,0x56,0xcb,0x14 = ilvev.w $w12, $w25, $w22
0x7b,0x63,0xdf,0x94 = ilvev.d $w30, $w27, $w3
0x7a,0x15,0x1f,0x54 = ilvl.b $w29, $w3, $w21
0x7a,0x31,0x56,0xd4 = ilvl.h $w27, $w10, $w17
0x7a,0x40,0x09,0x94 = ilvl.w $w6, $w1, $w0
0x7a,0x78,0x80,0xd4 = ilvl.d $w3, $w16, $w24
0x7b,0x94,0x2a,0xd4 = ilvod.b $w11, $w5, $w20
0x7b,0xbf,0x6c,0x94 = ilvod.h $w18, $w13, $w31
0x7b,0xd8,0x87,0x54 = ilvod.w $w29, $w16, $w24
0x7b,0xfd,0x65,0x94 = ilvod.d $w22, $w12, $w29
0x7a,0x86,0xf1,0x14 = ilvr.b $w4, $w30, $w6
0x7a,0xbd,0x9f,0x14 = ilvr.h $w28, $w19, $w29
0x7a,0xd5,0xa4,0x94 = ilvr.w $w18, $w20, $w21
0x7a,0xec,0xf5,0xd4 = ilvr.d $w23, $w30, $w12
0x78,0x9d,0xfc,0x52 = maddv.b $w17, $w31, $w29
0x78,0xa9,0xc1,0xd2 = maddv.h $w7, $w24, $w9
0x78,0xd4,0xb5,0x92 = maddv.w $w22, $w22, $w20
0x78,0xf4,0xd7,0x92 = maddv.d $w30, $w26, $w20
0x7b,0x17,0x5d,0xce = max_a.b $w23, $w11, $w23
0x7b,0x3e,0x2d,0x0e = max_a.h $w20, $w5, $w30
0x7b,0x5e,0x91,0xce = max_a.w $w7, $w18, $w30
0x7b,0x7f,0x42,0x0e = max_a.d $w8, $w8, $w31
0x79,0x13,0x0a,0x8e = max_s.b $w10, $w1, $w19
0x79,0x31,0xeb,0xce = max_s.h $w15, $w29, $w17
0x79,0x4e,0xeb,0xce = max_s.w $w15, $w29, $w14
0x79,0x63,0xc6,0x4e = max_s.d $w25, $w24, $w3
0x79,0x85,0xc3,0x0e = max_u.b $w12, $w24, $w5
0x79,0xa7,0x31,0x4e = max_u.h $w5, $w6, $w7
0x79,0xc7,0x24,0x0e = max_u.w $w16, $w4, $w7
0x79,0xf8,0x66,0x8e = max_u.d $w26, $w12, $w24
0x7b,0x81,0xd1,0x0e = min_a.b $w4, $w26, $w1
0x7b,0xbf,0x6b,0x0e = min_a.h $w12, $w13, $w31
0x7b,0xc0,0xa7,0x0e = min_a.w $w28, $w20, $w0
0x7b,0xf3,0xa3,0x0e = min_a.d $w12, $w20, $w19
0x7a,0x0e,0x1c,0xce = min_s.b $w19, $w3, $w14
0x7a,0x28,0xae,0xce = min_s.h $w27, $w21, $w8
0x7a,0x5e,0x70,0x0e = min_s.w $w0, $w14, $w30
0x7a,0x75,0x41,0x8e = min_s.d $w6, $w8, $w21
0x7a,0x88,0xd5,0x8e = min_u.b $w22, $w26, $w8
0x7a,0xac,0xd9,0xce = min_u.h $w7, $w27, $w12
0x7a,0xce,0xa2,0x0e = min_u.w $w8, $w20, $w14
0x7a,0xef,0x76,0x8e = min_u.d $w26, $w14, $w15
0x7b,0x1a,0x0c,0x92 = mod_s.b $w18, $w1, $w26
0x7b,0x3c,0xf7,0xd2 = mod_s.h $w31, $w30, $w28
0x7b,0x4d,0x30,0x92 = mod_s.w $w2, $w6, $w13
0x7b,0x76,0xdd,0x52 = mod_s.d $w21, $w27, $w22
0x7b,0x8d,0x3c,0x12 = mod_u.b $w16, $w7, $w13
0x7b,0xa7,0x46,0x12 = mod_u.h $w24, $w8, $w7
0x7b,0xd1,0x17,0x92 = mod_u.w $w30, $w2, $w17
0x7b,0xf9,0x17,0xd2 = mod_u.d $w31, $w2, $w25
0x79,0x0c,0x2b,0x92 = msubv.b $w14, $w5, $w12
0x79,0x3e,0x39,0x92 = msubv.h $w6, $w7, $w30
0x79,0x55,0x13,0x52 = msubv.w $w13, $w2, $w21
0x79,0x7b,0x74,0x12 = msubv.d $w16, $w14, $w27
0x78,0x0d,0x1d,0x12 = mulv.b $w20, $w3, $w13
0x78,0x2e,0xd6,0xd2 = mulv.h $w27, $w26, $w14
0x78,0x43,0xea,0x92 = mulv.w $w10, $w29, $w3
0x78,0x7d,0x99,0xd2 = mulv.d $w7, $w19, $w29
0x79,0x07,0xd9,0x54 = pckev.b $w5, $w27, $w7
0x79,0x3b,0x20,0x54 = pckev.h $w1, $w4, $w27
0x79,0x40,0xa7,0x94 = pckev.w $w30, $w20, $w0
0x79,0x6f,0x09,0x94 = pckev.d $w6, $w1, $w15
0x79,0x9e,0xe4,0x94 = pckod.b $w18, $w28, $w30
0x79,0xa8,0x2e,0x94 = pckod.h $w26, $w5, $w8
0x79,0xc2,0x22,0x54 = pckod.w $w9, $w4, $w2
0x79,0xf4,0xb7,0x94 = pckod.d $w30, $w22, $w20
0x78,0x0c,0xb9,0x54 = sld.b $w5, $w23[$12]
0x78,0x23,0xb8,0x54 = sld.h $w1, $w23[$3]
0x78,0x49,0x45,0x14 = sld.w $w20, $w8[$9]
0x78,0x7e,0xb9,0xd4 = sld.d $w7, $w23[$fp]
0x78,0x11,0x00,0xcd = sll.b $w3, $w0, $w17
0x78,0x23,0xdc,0x4d = sll.h $w17, $w27, $w3
0x78,0x46,0x3c,0x0d = sll.w $w16, $w7, $w6
0x78,0x7a,0x02,0x4d = sll.d $w9, $w0, $w26
0x78,0x81,0x0f,0x14 = splat.b $w28, $w1[$1]
0x78,0xab,0x58,0x94 = splat.h $w2, $w11[$11]
0x78,0xcb,0x05,0x94 = splat.w $w22, $w0[$11]
0x78,0xe2,0x00,0x14 = splat.d $w0, $w0[$2]
0x78,0x91,0x27,0x0d = sra.b $w28, $w4, $w17
0x78,0xa3,0x4b,0x4d = sra.h $w13, $w9, $w3
0x78,0xd3,0xae,0xcd = sra.w $w27, $w21, $w19
0x78,0xf7,0x47,0x8d = sra.d $w30, $w8, $w23
0x78,0x92,0x94,0xd5 = srar.b $w19, $w18, $w18
0x78,0xa8,0xb9,0xd5 = srar.h $w7, $w23, $w8
0x78,0xc2,0x60,0x55 = srar.w $w1, $w12, $w2
0x78,0xee,0x3d,0x55 = srar.d $w21, $w7, $w14
0x79,0x13,0x1b,0x0d = srl.b $w12, $w3, $w19
0x79,0x34,0xfd,0xcd = srl.h $w23, $w31, $w20
0x79,0x4b,0xdc,0x8d = srl.w $w18, $w27, $w11
0x79,0x7a,0x60,0xcd = srl.d $w3, $w12, $w26
0x79,0x0b,0xab,0xd5 = srlr.b $w15, $w21, $w11
0x79,0x33,0x6d,0x55 = srlr.h $w21, $w13, $w19
0x79,0x43,0xf1,0x95 = srlr.w $w6, $w30, $w3
0x79,0x6e,0x10,0x55 = srlr.d $w1, $w2, $w14
0x78,0x01,0x7e,0x51 = subs_s.b $w25, $w15, $w1
0x78,0x36,0xcf,0x11 = subs_s.h $w28, $w25, $w22
0x78,0x55,0x62,0x91 = subs_s.w $w10, $w12, $w21
0x78,0x72,0xa1,0x11 = subs_s.d $w4, $w20, $w18
0x78,0x99,0x35,0x51 = subs_u.b $w21, $w6, $w25
0x78,0xa7,0x50,0xd1 = subs_u.h $w3, $w10, $w7
0x78,0xca,0x7a,0x51 = subs_u.w $w9, $w15, $w10
0x78,0xea,0x99,0xd1 = subs_u.d $w7, $w19, $w10
0x79,0x0c,0x39,0x91 = subsus_u.b $w6, $w7, $w12
0x79,0x33,0xe9,0x91 = subsus_u.h $w6, $w29, $w19
0x79,0x47,0x79,0xd1 = subsus_u.w $w7, $w15, $w7
0x79,0x6f,0x1a,0x51 = subsus_u.d $w9, $w3, $w15
0x79,0x9f,0x1d,0x91 = subsuu_s.b $w22, $w3, $w31
0x79,0xb6,0xbc,0xd1 = subsuu_s.h $w19, $w23, $w22
0x79,0xcd,0x52,0x51 = subsuu_s.w $w9, $w10, $w13
0x79,0xe0,0x31,0x51 = subsuu_s.d $w5, $w6, $w0
0x78,0x93,0x69,0x8e = subv.b $w6, $w13, $w19
0x78,0xac,0xc9,0x0e = subv.h $w4, $w25, $w12
0x78,0xcb,0xde,0xce = subv.w $w27, $w27, $w11
0x78,0xea,0xc2,0x4e = subv.d $w9, $w24, $w10
0x78,0x05,0x80,0xd5 = vshf.b $w3, $w16, $w5
0x78,0x28,0x9d,0x15 = vshf.h $w20, $w19, $w8
0x78,0x59,0xf4,0x15 = vshf.w $w16, $w30, $w25
0x78,0x6f,0x5c,0xd5 = vshf.d $w19, $w11, $w15
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* 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 halcyon nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenMetaverse;
using TransactionInfoBlock = OpenMetaverse.Packets.MoneyBalanceReplyPacket.TransactionInfoBlock;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using System.Net;
using System.Xml;
using OpenSim.Region.Framework.Interfaces;
using log4net;
using System.Reflection;
using OpenMetaverse.StructuredData;
namespace OpenSim.Region.CoreModules.Agent.BotManager
{
public class BotClient : IBot, IClientAPI
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#region Declares
private UUID m_UUID, m_sessionId;
public string m_firstName, m_lastName;
private int m_animationSequenceNumber = 1;
private uint m_circuitCode;
private Scene m_scene;
private Dictionary<string, UUID> m_defaultAnimations = new Dictionary<string, UUID>();
private bool m_frozenUser = false;
private bool m_closing = false;
#endregion
#region Constructor
public BotClient(string firstName, string lastName, Scene scene, Vector3 startPos, UUID ownerID)
{
m_circuitCode = (uint)Util.RandomClass.Next(0, int.MaxValue);
m_UUID = UUID.Random();
m_sessionId = UUID.Random();
m_firstName = firstName;
m_lastName = lastName;
m_scene = scene;
StartPos = startPos;
OwnerID = ownerID;
MovementController = new BotMovementController(this);
RegisteredScriptsForPathUpdateEvents = new List<UUID>();
TimeCreated = DateTime.Now;
InitDefaultAnimations();
}
#endregion
#region IBot Properties
public UUID OwnerID { get; private set; }
public OpenMetaverse.UUID AgentID { get { return m_UUID; } }
public BotMovementController MovementController { get; private set; }
public List<UUID> RegisteredScriptsForPathUpdateEvents { get; private set; }
public DateTime TimeCreated { get; private set; }
public bool Frozen { get { return m_frozenUser; } }
#endregion
#region IBot Methods
#region Bot Property Methods
public void Close()
{
if (!m_closing)
{
m_closing = true;
MovementController.StopMovement();
m_scene.RemoveClient(AgentID);
// Fire the callback for this connection closing
if (OnConnectionClosed != null)
OnConnectionClosed(this);
}
}
#endregion
#region Region Interaction Methods
public bool SitOnObject(UUID objectID)
{
if (m_frozenUser)
return false;
ScenePresence sp = m_scene.GetScenePresence(m_UUID);
if (sp == null)
return false;
SceneObjectPart child = m_scene.GetSceneObjectPart(objectID);
if (child == null)
return false;
sp.HandleAgentRequestSit(sp.ControllingClient, AgentID, objectID, Vector3.Zero);
return true;
}
public bool StandUp()
{
if (m_frozenUser)
return false;
ScenePresence sp = m_scene.GetScenePresence(m_UUID);
if (sp == null)
return false;
sp.StandUp(false, true);
return true;
}
public bool TouchObject(UUID objectID)
{
if (m_frozenUser)
return false;
ScenePresence sp = m_scene.GetScenePresence(AgentID);
if (sp == null)
return false;
SceneObjectPart part = m_scene.GetSceneObjectPart(objectID);
if (part == null)
return false;
m_scene.ProcessObjectGrab(part.LocalId, Vector3.Zero, this, null);
m_scene.ProcessObjectDeGrab(part.LocalId, this, null);
return true;
}
#endregion
#region Bot Animation Methods
public bool StartAnimation(UUID animID, string anim, UUID objectID)
{
if (m_frozenUser)
return false;
ScenePresence sp = m_scene.GetScenePresence(AgentID);
if (sp == null)
return false;
if (animID == UUID.Zero)
sp.AddAnimation(anim, objectID);
else
sp.AddAnimation(animID, objectID);
return true;
}
public bool StopAnimation(UUID animID, string anim)
{
if (m_frozenUser)
return false;
ScenePresence sp = m_scene.GetScenePresence(AgentID);
if (sp == null)
return false;
if (animID == UUID.Zero)
sp.RemoveAnimation(anim);
else
sp.RemoveAnimation(animID);
return true;
}
#endregion
#region Bot Movement Methods
public bool SetSpeed(float speed)
{
if (m_frozenUser)
return false;
ScenePresence sp = m_scene.GetScenePresence(AgentID);
if (sp == null)
return false;
sp.SpeedModifier = speed;
return true;
}
#endregion
#region Chat Methods
public void Say(int channel, string message, ChatTypeEnum sourceType)
{
if (m_frozenUser)
return;
if (channel == 0 && sourceType != ChatTypeEnum.StartTyping && sourceType != ChatTypeEnum.StopTyping)
{
message = message.Trim();
if (string.IsNullOrEmpty(message))
{
return;
}
}
if (sourceType == ChatTypeEnum.StartTyping)
{
StartAnimation(UUID.Zero, "TYPE", UUID.Zero);
}
else if (sourceType == ChatTypeEnum.StopTyping)
{
StopAnimation(UUID.Zero, "TYPE");
}
OSChatMessage chatFromClient = new OSChatMessage();
chatFromClient.Channel = channel;
chatFromClient.From = Name;
chatFromClient.Message = message;
chatFromClient.Position = StartPos;
chatFromClient.Scene = m_scene;
chatFromClient.SenderUUID = AgentId;
chatFromClient.Type = sourceType;
// Force avatar position to be server-known avatar position. (Former contents of FixPositionOfChatMessage.)
ScenePresence avatar;
if (m_scene.TryGetAvatar(m_UUID, out avatar))
chatFromClient.Position = avatar.AbsolutePosition;
OnChatFromClient(this, chatFromClient);
}
public void SendInstantMessage(UUID agentId, string message)
{
if (m_frozenUser)
return;
// We may be able to use ClientView.SendInstantMessage here, but we need a client instance.
// InstantMessageModule.OnInstantMessage searches through a list of scenes for a client matching the toAgent,
// but I don't think we have a list of scenes available from here.
// (We also don't want to duplicate the code in OnInstantMessage if we can avoid it.)
// user is a UUID
// client.SendInstantMessage(m_host.UUID, fromSession, message, user, imSessionID, m_host.Name, AgentManager.InstantMessageDialog.MessageFromAgent, (uint)Util.UnixTimeSinceEpoch());
UUID friendTransactionID = UUID.Random();
//m_pendingFriendRequests.Add(friendTransactionID, fromAgentID);
GridInstantMessage msg = new GridInstantMessage();
msg.fromAgentID = new Guid(AgentID.ToString());
msg.toAgentID = agentId.Guid;
msg.imSessionID = new Guid(friendTransactionID.ToString()); // This is the item we're mucking with here
msg.timestamp = (uint)Util.UnixTimeSinceEpoch();// timestamp;
msg.fromAgentName = Name;
// Cap the message length at 1024.
if (message != null && message.Length > 1024)
msg.message = message.Substring(0, 1024);
else
msg.message = message;
msg.dialog = (byte)InstantMessageDialog.MessageFromAgent;
msg.fromGroup = false;// fromGroup;
msg.offline = (byte)0; //offline;
msg.ParentEstateID = 0; //ParentEstateID;
ScenePresence sp = m_scene.GetScenePresence(AgentID);
msg.Position = sp.AbsolutePosition;
msg.RegionID = m_scene.RegionInfo.RegionID.Guid;//RegionID.Guid;
// binaryBucket is the SL URL without the prefix, e.g. "Region/x/y/z"
string url = Util.LocationShortCode(m_scene.RegionInfo.RegionName, msg.Position, "/");
byte[] bucket = Utils.StringToBytes(url);
msg.binaryBucket = new byte[bucket.Length];// binaryBucket;
bucket.CopyTo(msg.binaryBucket, 0);
IMessageTransferModule transferModule = m_scene.RequestModuleInterface<IMessageTransferModule>();
if (transferModule != null)
{
transferModule.SendInstantMessage(msg, delegate(bool success) { });
}
}
public void SendChatMessage(string message, byte type, OpenMetaverse.Vector3 fromPos, string fromName, OpenMetaverse.UUID fromAgentID, OpenMetaverse.UUID ownerID, byte source, byte audible)
{
}
#endregion
#region Give Inventory
public void GiveInventoryObject(SceneObjectPart part, string objName, UUID objId, byte assetType, UUID destId)
{
if (m_frozenUser)
return;
// check if destination is an avatar
if (!String.IsNullOrEmpty(m_scene.CommsManager.UserService.Key2Name(destId, false)))
{
if (m_scene.GetScenePresence(destId) == null || m_scene.GetScenePresence(destId).IsChildAgent)
return;//Only allow giving items to users in the sim
// destination is an avatar
InventoryItemBase agentItem =
m_scene.MoveTaskInventoryItem(destId, UUID.Zero, part, objId);
if (agentItem == null)
return;
byte dialog = (byte)InstantMessageDialog.InventoryOffered;
byte[] bucket = new byte[17];
bucket[0] = assetType;
agentItem.ID.ToBytes(bucket, 1);
ScenePresence sp = m_scene.GetScenePresence(AgentID);
string URL = Util.LocationURL(m_scene.RegionInfo.RegionName, sp.AbsolutePosition);
GridInstantMessage msg = new GridInstantMessage(m_scene,
AgentID, Name, destId,
dialog, false, "'" + objName + "' ( " + URL + " )",
agentItem.ID, true, sp.AbsolutePosition,
bucket);
IMessageTransferModule transferModule = m_scene.RequestModuleInterface<IMessageTransferModule>();
if (transferModule != null)
{
transferModule.SendInstantMessage(msg, delegate(bool success) { });
}
}
}
#endregion
#endregion
#region IClientAPI Properties / Methods
public OpenMetaverse.Vector3 StartPos
{
get;
set;
}
public OpenMetaverse.UUID AgentId
{
get { return m_UUID; }
}
public OpenMetaverse.UUID SessionId
{
get { return m_sessionId; }
}
public OpenMetaverse.UUID SecureSessionId
{
get { return UUID.Zero; }
}
public OpenMetaverse.UUID ActiveGroupId
{
get { return UUID.Zero; }
}
public string ActiveGroupName
{
get { return String.Empty; }
}
public ulong ActiveGroupPowers
{
get { return 0; }
}
public ulong GetGroupPowers(OpenMetaverse.UUID groupID) { return 0; }
public ulong? GetGroupPowersOrNull(OpenMetaverse.UUID groupID) { return null; }
public bool IsGroupMember(OpenMetaverse.UUID GroupID) { return false; }
public string FirstName
{
get { return m_firstName; }
}
public string LastName
{
get { return m_lastName; }
}
public IScene Scene
{
get { return m_scene; }
}
public int NextAnimationSequenceNumber
{
get { return m_animationSequenceNumber++; }
}
public string Name
{
get { return FirstName + " " + LastName; }
}
public bool IsActive
{
get;
set;
}
public bool SendLogoutPacketWhenClosing
{
set { }
}
public bool DebugCrossings
{
get { return false; }
set { }
}
public uint CircuitCode
{
get { return m_circuitCode; }
}
#pragma warning disable 0067 // disable "X is never used"
public event Action<int> OnSetThrottles;
public event GenericMessage OnGenericMessage;
public event ImprovedInstantMessage OnInstantMessage;
public event ChatMessage OnChatFromClient;
public event TextureRequest OnRequestTexture;
public event RezObject OnRezObject;
public event RestoreObject OnRestoreObject;
public event ModifyTerrain OnModifyTerrain;
public event BakeTerrain OnBakeTerrain;
public event EstateChangeInfo OnEstateChangeInfo;
public event SimWideDeletesDelegate OnSimWideDeletes;
public event SetAppearance OnSetAppearance;
public event AvatarNowWearing OnAvatarNowWearing;
public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv;
public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv;
public event UUIDNameRequest OnDetachAttachmentIntoInv;
public event ObjectAttach OnObjectAttach;
public event ObjectDeselect OnObjectDetach;
public event ObjectDrop OnObjectDrop;
public event StartAnim OnStartAnim;
public event StopAnim OnStopAnim;
public event LinkObjects OnLinkObjects;
public event DelinkObjects OnDelinkObjects;
public event RequestMapBlocks OnRequestMapBlocks;
public event RequestMapName OnMapNameRequest;
public event TeleportLocationRequest OnTeleportLocationRequest;
public event DisconnectUser OnDisconnectUser;
public event RequestAvatarProperties OnRequestAvatarProperties;
public event RequestAvatarInterests OnRequestAvatarInterests;
public event SetAlwaysRun OnSetAlwaysRun;
public event TeleportLandmarkRequest OnTeleportLandmarkRequest;
public event DeRezObjects OnDeRezObjects;
public event Action<IClientAPI> OnRegionHandShakeReply;
public event GenericCall2 OnRequestWearables;
public event GenericCall2 OnCompleteMovementToRegion;
public event UpdateAgent OnAgentUpdate;
public event AgentRequestSit OnAgentRequestSit;
public event AgentSit OnAgentSit;
public event AvatarPickerRequest OnAvatarPickerRequest;
public event Action<IClientAPI> OnRequestAvatarsData;
public event AddNewPrim OnAddPrim;
public event FetchInventory OnAgentDataUpdateRequest;
public event TeleportLocationRequest OnSetStartLocationRequest;
public event RequestGodlikePowers OnRequestGodlikePowers;
public event GodKickUser OnGodKickUser;
public event ObjectDuplicate OnObjectDuplicate;
public event ObjectDuplicateOnRay OnObjectDuplicateOnRay;
public event GrabObject OnGrabObject;
public event DeGrabObject OnDeGrabObject;
public event MoveObject OnGrabUpdate;
public event SpinStart OnSpinStart;
public event SpinObject OnSpinUpdate;
public event SpinStop OnSpinStop;
public event UpdateShape OnUpdatePrimShape;
public event ObjectExtraParams OnUpdateExtraParams;
public event ObjectRequest OnObjectRequest;
public event ObjectSelect OnObjectSelect;
public event ObjectDeselect OnObjectDeselect;
public event GenericCall7 OnObjectDescription;
public event GenericCall7 OnObjectName;
public event GenericCall7 OnObjectClickAction;
public event GenericCall7 OnObjectMaterial;
public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily;
public event UpdatePrimFlags OnUpdatePrimFlags;
public event UpdatePrimTexture OnUpdatePrimTexture;
public event UpdateVectorWithUndoSupport OnUpdatePrimGroupPosition;
public event UpdateVectorWithUndoSupport OnUpdatePrimSinglePosition;
public event UpdatePrimRotation OnUpdatePrimGroupRotation;
public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation;
public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition;
public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation;
public event UpdateVector OnUpdatePrimScale;
public event UpdateVector OnUpdatePrimGroupScale;
public event StatusChange OnChildAgentStatus;
public event GenericCall2 OnStopMovement;
public event Action<OpenMetaverse.UUID> OnRemoveAvatar;
public event ObjectPermissions OnObjectPermissions;
public event CreateNewInventoryItem OnCreateNewInventoryItem;
public event LinkInventoryItem OnLinkInventoryItem;
public event CreateInventoryFolder OnCreateNewInventoryFolder;
public event UpdateInventoryFolder OnUpdateInventoryFolder;
public event MoveInventoryFolder OnMoveInventoryFolder;
public event FetchInventoryDescendents OnFetchInventoryDescendents;
public event PurgeInventoryDescendents OnPurgeInventoryDescendents;
public event FetchInventory OnFetchInventory;
public event RequestTaskInventory OnRequestTaskInventory;
public event UpdateInventoryItem OnUpdateInventoryItem;
public event CopyInventoryItem OnCopyInventoryItem;
public event MoveInventoryItem OnMoveInventoryItem;
public event RemoveInventoryFolder OnRemoveInventoryFolder;
public event RemoveInventoryItem OnRemoveInventoryItem;
public event RemoveInventoryItem OnPreRemoveInventoryItem;
public event UDPAssetUploadRequest OnAssetUploadRequest;
public event XferReceive OnXferReceive;
public event RequestXfer OnRequestXfer;
public event ConfirmXfer OnConfirmXfer;
public event AbortXfer OnAbortXfer;
public event RezScript OnRezScript;
public event UpdateTaskInventory OnUpdateTaskInventory;
public event MoveTaskInventory OnMoveTaskItem;
public event RemoveTaskInventory OnRemoveTaskItem;
public event RequestAsset OnRequestAsset;
public event UUIDNameRequest OnNameFromUUIDRequest;
public event ParcelAccessListRequest OnParcelAccessListRequest;
public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest;
public event ParcelPropertiesRequest OnParcelPropertiesRequest;
public event ParcelDivideRequest OnParcelDivideRequest;
public event ParcelJoinRequest OnParcelJoinRequest;
public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest;
public event ParcelSelectObjects OnParcelSelectObjects;
public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest;
public event ParcelAbandonRequest OnParcelAbandonRequest;
public event ParcelGodForceOwner OnParcelGodForceOwner;
public event ParcelReclaim OnParcelReclaim;
public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest;
public event ParcelDeedToGroup OnParcelDeedToGroup;
public event RegionInfoRequest OnRegionInfoRequest;
public event EstateCovenantRequest OnEstateCovenantRequest;
public event FriendActionDelegate OnApproveFriendRequest;
public event FriendActionDelegate OnDenyFriendRequest;
public event FriendshipTermination OnTerminateFriendship;
public event MoneyTransferRequest OnMoneyTransferRequest;
public event EconomyDataRequest OnEconomyDataRequest;
public event MoneyBalanceRequest OnMoneyBalanceRequest;
public event UpdateAvatarProperties OnUpdateAvatarProperties;
public event AvatarInterestsUpdate OnAvatarInterestsUpdate;
public event ParcelBuy OnParcelBuy;
public event RequestPayPrice OnRequestPayPrice;
public event ObjectSaleInfo OnObjectSaleInfo;
public event ObjectBuy OnObjectBuy;
public event BuyObjectInventory OnBuyObjectInventory;
public event RequestTerrain OnRequestTerrain;
public event RequestTerrain OnUploadTerrain;
public event ObjectIncludeInSearch OnObjectIncludeInSearch;
public event UUIDNameRequest OnTeleportHomeRequest;
public event ScriptAnswer OnScriptAnswer;
public event AgentSit OnUndo;
public event AgentSit OnRedo;
public event LandUndo OnLandUndo;
public event ForceReleaseControls OnForceReleaseControls;
public event GodLandStatRequest OnLandStatRequest;
public event DetailedEstateDataRequest OnDetailedEstateDataRequest;
public event SetEstateFlagsRequest OnSetEstateFlagsRequest;
public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture;
public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture;
public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights;
public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest;
public event SetRegionTerrainSettings OnSetRegionTerrainSettings;
public event EstateRestartSimRequest OnEstateRestartSimRequest;
public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest;
public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest;
public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest;
public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest;
public event EstateDebugRegionRequest OnEstateDebugRegionRequest;
public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest;
public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest;
public event UUIDNameRequest OnUUIDGroupNameRequest;
public event RegionHandleRequest OnRegionHandleRequest;
public event ParcelInfoRequest OnParcelInfoRequest;
public event RequestObjectPropertiesFamily OnObjectGroupRequest;
public event ScriptReset OnScriptReset;
public event GetScriptRunning OnGetScriptRunning;
public event SetScriptRunning OnSetScriptRunning;
public event UpdateVector OnAutoPilotGo;
public event TerrainUnacked OnUnackedTerrain;
public event ActivateGestures OnActivateGestures;
public event DeactivateGestures OnDeactivateGestures;
public event ObjectOwner OnObjectOwner;
public event DirPlacesQuery OnDirPlacesQuery;
public event DirFindQuery OnDirFindQuery;
public event DirLandQuery OnDirLandQuery;
public event DirPopularQuery OnDirPopularQuery;
public event DirClassifiedQuery OnDirClassifiedQuery;
public event EventInfoRequest OnEventInfoRequest;
public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime;
public event MapItemRequest OnMapItemRequest;
public event OfferCallingCard OnOfferCallingCard;
public event AcceptCallingCard OnAcceptCallingCard;
public event DeclineCallingCard OnDeclineCallingCard;
public event SoundTrigger OnSoundTrigger;
public event StartLure OnStartLure;
public event TeleportLureRequest OnTeleportLureRequest;
public event NetworkStats OnNetworkStatsUpdate;
public event ClassifiedInfoRequest OnClassifiedInfoRequest;
public event ClassifiedInfoUpdate OnClassifiedInfoUpdate;
public event ClassifiedDelete OnClassifiedDelete;
public event ClassifiedDelete OnClassifiedGodDelete;
public event EventNotificationAddRequest OnEventNotificationAddRequest;
public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest;
public event EventGodDelete OnEventGodDelete;
public event ParcelDwellRequest OnParcelDwellRequest;
public event UserInfoRequest OnUserInfoRequest;
public event UpdateUserInfo OnUpdateUserInfo;
public event RetrieveInstantMessages OnRetrieveInstantMessages;
public event PickDelete OnPickDelete;
public event PickGodDelete OnPickGodDelete;
public event PickInfoUpdate OnPickInfoUpdate;
public event AvatarNotesUpdate OnAvatarNotesUpdate;
public event MuteListRequest OnMuteListRequest;
public event MuteListEntryUpdate OnUpdateMuteListEntry;
public event MuteListEntryRemove OnRemoveMuteListEntry;
public event PlacesQuery OnPlacesQuery;
public event GrantUserRights OnGrantUserRights;
public event FreezeUserUpdate OnParcelFreezeUser;
public event EjectUserUpdate OnParcelEjectUser;
public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest;
public event GroupAccountDetailsRequest OnGroupAccountDetailsRequest;
public event GroupAccountSummaryRequest OnGroupAccountSummaryRequest;
public event GroupAccountTransactionsRequest OnGroupAccountTransactionsRequest;
public event AgentCachedTextureRequest OnAgentCachedTextureRequest;
public event ActivateGroup OnActivateGroup;
public event GodlikeMessage OnGodlikeMessage;
public event GodlikeMessage OnEstateTelehubRequest;
#pragma warning restore 0067
public System.Net.IPEndPoint RemoteEndPoint
{
get { return new IPEndPoint(IPAddress.Loopback, 0); }
}
public bool IsLoggingOut
{
get;
set;
}
public void SetDebugPacketLevel(int newDebug)
{
}
public void ProcessInPacket(OpenMetaverse.Packets.Packet NewPack)
{
}
public void Kick(string message)
{
}
public void Start()
{
}
public void SendWearables(AvatarWearable[] wearables, int serial)
{
}
public void SendAppearance(AvatarAppearance app, Vector3 hover)
{
}
public void SendStartPingCheck(byte seq)
{
}
public void SendKillObject(ulong regionHandle, uint localID)
{
}
public void SendKillObjects(ulong regionHandle, uint[] localIDs)
{
}
public void SendNonPermanentKillObject(ulong regionHandle, uint localID)
{
}
public void SendNonPermanentKillObjects(ulong regionHandle, uint[] localIDs)
{
}
public void SendAnimations(OpenMetaverse.UUID[] animID, int[] seqs, OpenMetaverse.UUID sourceAgentId, OpenMetaverse.UUID[] objectIDs)
{
}
public void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args)
{
}
public void SendInstantMessage(GridInstantMessage im)
{
}
public void SendGenericMessage(string method, List<string> message)
{
}
public void SendLayerData(float[] map)
{
}
public void SendLayerData(int px, int py, float[] map)
{
}
public void SendWindData(OpenMetaverse.Vector2[] windSpeeds)
{
}
public void SendCloudData(float[] cloudCover)
{
}
public void MoveAgentIntoRegion(RegionInfo regInfo, OpenMetaverse.Vector3 pos, OpenMetaverse.Vector3 look)
{
}
public void InformClientOfNeighbour(ulong neighbourHandle, System.Net.IPEndPoint neighbourExternalEndPoint)
{
}
public AgentCircuitData RequestClientInfo()
{
AgentCircuitData agentData = new AgentCircuitData();
agentData.AgentID = AgentId;
// agentData.Appearance
// agentData.BaseFolder
agentData.CapsPath = String.Empty;
agentData.child = false;
agentData.CircuitCode = m_circuitCode;
agentData.ClientVersion = "Bot";
agentData.FirstName = m_firstName;
// agentData.InventoryFolder
agentData.LastName = m_lastName;
agentData.SecureSessionID = SecureSessionId;
agentData.SessionID = m_sessionId;
// agentData.startpos
return agentData;
}
public void SendMapBlock(List<MapBlockData> mapBlocks, uint flag)
{
}
public void SendLocalTeleport(OpenMetaverse.Vector3 position, OpenMetaverse.Vector3 lookAt, uint flags)
{
}
public void SendTeleportFailed(string reason)
{
}
public void SendTeleportLocationStart()
{
}
public void SendMoneyBalance(UUID transaction, bool success, string description, int balance, TransactionInfoBlock transInfo)
{
}
public void SendPayPrice(OpenMetaverse.UUID objectID, int[] payPrice)
{
}
public void SendAvatarData(ulong regionHandle, string firstName, string lastName, string grouptitle, OpenMetaverse.UUID avatarID, uint avatarLocalID,
OpenMetaverse.Vector3 Pos, byte[] textureEntry, uint parentID, OpenMetaverse.Quaternion rotation, OpenMetaverse.Vector4 collisionPlane,
OpenMetaverse.Vector3 velocity, bool immediate)
{
}
public void SendAvatarTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, OpenMetaverse.Vector3 position, OpenMetaverse.Vector3 velocity, OpenMetaverse.Vector3 acceleration, OpenMetaverse.Quaternion rotation, OpenMetaverse.UUID agentid, OpenMetaverse.Vector4 collisionPlane)
{
}
public void SendCoarseLocationUpdate(List<OpenMetaverse.UUID> users, List<OpenMetaverse.Vector3> CoarseLocations)
{
}
public void AttachObject(uint localID, OpenMetaverse.Quaternion rotation, byte attachPoint, OpenMetaverse.UUID ownerID)
{
}
public void SetChildAgentThrottle(byte[] throttle)
{
}
public void SendPrimitiveToClient(object sop, uint clientFlags, OpenMetaverse.Vector3 lpos, PrimUpdateFlags updateFlags)
{
}
public void SendPrimitiveToClientImmediate(object sop, uint clientFlags, OpenMetaverse.Vector3 lpos)
{
}
public void SendPrimTerseUpdate(object sop)
{
}
public void SendInventoryFolderDetails(OpenMetaverse.UUID ownerID, InventoryFolderBase folder, List<InventoryItemBase> items, List<InventoryFolderBase> folders, bool fetchFolders, bool fetchItems)
{
}
public void FlushPrimUpdates()
{
}
public void SendInventoryItemDetails(OpenMetaverse.UUID ownerID, InventoryItemBase item)
{
}
public void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackId)
{
}
public void SendRemoveInventoryItem(OpenMetaverse.UUID itemID)
{
}
public void SendTakeControls(int controls, bool TakeControls, bool passToAgent)
{
}
public void SendTakeControls2(int controls1, bool takeControls1, bool passToAgent1,
int controls2, bool takeControls2, bool passToAgent2)
{
}
public void SendTaskInventory(OpenMetaverse.UUID taskID, short serial, byte[] fileName)
{
}
public void SendBulkUpdateInventory(InventoryNodeBase node)
{
}
public void SendXferPacket(ulong xferID, uint packet, byte[] data)
{
}
public void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit, int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor, int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay, int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent)
{
}
public void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data)
{
}
public void SendAgentDataUpdate(OpenMetaverse.UUID agentid, OpenMetaverse.UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle)
{
}
public void SendPreLoadSound(OpenMetaverse.UUID objectID, OpenMetaverse.UUID ownerID, OpenMetaverse.UUID soundID)
{
}
public void SendPlayAttachedSound(OpenMetaverse.UUID soundID, OpenMetaverse.UUID objectID, OpenMetaverse.UUID ownerID, float gain, byte flags)
{
}
public void SendTriggeredSound(OpenMetaverse.UUID soundID, OpenMetaverse.UUID ownerID, OpenMetaverse.UUID objectID, OpenMetaverse.UUID parentID, ulong handle, OpenMetaverse.Vector3 position, float gain)
{
}
public void SendAttachedSoundGainChange(OpenMetaverse.UUID objectID, float gain)
{
}
public void SendNameReply(OpenMetaverse.UUID profileId, string firstname, string lastname)
{
}
public void SendAlertMessage(string message)
{
}
public void SendAlertMessage(string message, string infoMessage, OSD extraParams)
{
/* no op */
}
public void SendAgentAlertMessage(string message, bool modal)
{
}
public void SendLoadURL(string objectname, OpenMetaverse.UUID objectID, OpenMetaverse.UUID ownerID, bool groupOwned, string message, string url)
{
}
public void SendDialog(string objectname, OpenMetaverse.UUID objectID, OpenMetaverse.UUID ownerID, string ownerFirstname, string ownerLastname, string msg, OpenMetaverse.UUID textureID, int ch, string[] buttonlabels)
{
}
public void SendSunPos(OpenMetaverse.Vector3 sunPos, OpenMetaverse.Vector3 sunVel, ulong CurrentTime, uint SecondsPerSunCycle, uint SecondsPerYear, float OrbitalPosition)
{
}
public void SendViewerEffect(OpenMetaverse.Packets.ViewerEffectPacket.EffectBlock[] effectBlocks)
{
}
public void SendViewerTime(int phase)
{
}
private void InitDefaultAnimations()
{
try
{
using (XmlTextReader reader = new XmlTextReader("data/avataranimations.xml"))
{
XmlDocument doc = new XmlDocument();
doc.Load(reader);
if (doc.DocumentElement != null)
foreach (XmlNode nod in doc.DocumentElement.ChildNodes)
{
if (nod.Attributes["name"] != null)
{
string name = nod.Attributes["name"].Value.ToLower();
string id = nod.InnerText;
m_defaultAnimations.Add(name, (UUID)id);
}
}
}
}
catch (Exception)
{
}
}
public OpenMetaverse.UUID GetDefaultAnimation(string name)
{
if (m_defaultAnimations.ContainsKey(name.ToLower()))
return m_defaultAnimations[name.ToLower()];
return UUID.Zero;
}
public void SendAvatarProperties(OpenMetaverse.UUID avatarID, string aboutText, string bornOn, byte[] charterMember, string flAbout, uint flags, OpenMetaverse.UUID flImageID, OpenMetaverse.UUID imageID, string profileURL, OpenMetaverse.UUID partnerID)
{
}
public void SendAvatarInterests(OpenMetaverse.UUID avatarID, uint skillsMask, string skillsText, uint wantToMask, string wantToText, string languagesText)
{
}
public void SendScriptQuestion(OpenMetaverse.UUID taskID, string taskName, string ownerName, OpenMetaverse.UUID itemID, int question)
{
}
public void SendHealth(float health)
{
}
public void SendEstateUUIDList(OpenMetaverse.UUID invoice, int whichList, OpenMetaverse.UUID[] UUIDList, uint estateID)
{
}
public void SendBannedUserList(OpenMetaverse.UUID invoice, EstateBan[] banlist, uint estateID)
{
}
public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args)
{
}
public void SendEstateCovenantInformation(OpenMetaverse.UUID covenant, uint lastUpdated)
{
}
public void SendDetailedEstateData(OpenMetaverse.UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, OpenMetaverse.UUID covenant, uint covenantLastUpdated, string abuseEmail, OpenMetaverse.UUID estateOwner)
{
}
public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, LandData landData, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags)
{
}
public void SendLandAccessListData(List<OpenMetaverse.UUID> avatars, uint accessFlag, int localLandID)
{
}
public void SendForceClientSelectObjects(List<uint> objectIDs)
{
}
public void SendLandObjectOwners(LandData land, List<OpenMetaverse.UUID> groups, Dictionary<OpenMetaverse.UUID, int> ownersAndCount)
{
}
public void SendLandParcelOverlay(byte[] data, int sequence_id)
{
}
public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time)
{
}
public void SendParcelMediaUpdate(string mediaUrl, OpenMetaverse.UUID mediaTextureID, byte autoScale, string mediaType, string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop)
{
}
public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, OpenMetaverse.UUID AssetFullID)
{
}
public void SendConfirmXfer(ulong xferID, uint PacketID)
{
}
public void SendXferRequest(ulong XferID, short AssetType, OpenMetaverse.UUID vFileID, byte FilePath, byte[] FileName)
{
}
public void SendInitiateDownload(string simFileName, string clientFileName)
{
}
public void SendImageFirstPart(ushort numParts, OpenMetaverse.UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec)
{
}
public void SendImageNextPart(ushort partNumber, OpenMetaverse.UUID imageUuid, byte[] imageData)
{
}
public void SendImageNotFound(OpenMetaverse.UUID imageid)
{
}
public void SendDisableSimulator()
{
}
public void SendSimStats(SimStats stats)
{
}
public void SendObjectPropertiesFamilyData(uint RequestFlags, OpenMetaverse.UUID ObjectUUID, OpenMetaverse.UUID OwnerID, OpenMetaverse.UUID GroupID, uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, uint Category, OpenMetaverse.UUID LastOwnerID, string ObjectName, string Description)
{
}
public void SendObjectPropertiesReply(OpenMetaverse.UUID ItemID, ulong CreationDate, OpenMetaverse.UUID CreatorUUID, OpenMetaverse.UUID FolderUUID, OpenMetaverse.UUID FromTaskUUID, OpenMetaverse.UUID GroupUUID, short InventorySerial, OpenMetaverse.UUID LastOwnerUUID, OpenMetaverse.UUID ObjectUUID, OpenMetaverse.UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, uint BaseMask, uint FoldedOwnerMask, uint FoldedNextOwnerMask, byte saleType, int salePrice)
{
}
public void SendAgentOffline(OpenMetaverse.UUID[] agentIDs)
{
}
public void SendAgentOnline(OpenMetaverse.UUID[] agentIDs)
{
}
public void SendSitResponse(OpenMetaverse.UUID TargetID, OpenMetaverse.Vector3 OffsetPos, OpenMetaverse.Quaternion SitOrientation, bool autopilot, OpenMetaverse.Vector3 CameraAtOffset, OpenMetaverse.Vector3 CameraEyeOffset, bool ForceMouseLook)
{
}
public void SendAdminResponse(OpenMetaverse.UUID Token, uint AdminLevel)
{
}
public void SendGroupMembership(GroupMembershipData[] GroupMembership)
{
}
public void SendGroupNameReply(OpenMetaverse.UUID groupLLUID, string GroupName)
{
}
public void SendJoinGroupReply(OpenMetaverse.UUID groupID, bool success)
{
}
public void SendEjectGroupMemberReply(OpenMetaverse.UUID agentID, OpenMetaverse.UUID groupID, bool success)
{
}
public void SendLeaveGroupReply(OpenMetaverse.UUID groupID, bool success)
{
}
public void SendCreateGroupReply(OpenMetaverse.UUID groupID, bool success, string message)
{
}
public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, List<LandStatReportItem> lsrpl)
{
}
public void SendScriptRunningReply(OpenMetaverse.UUID objectID, OpenMetaverse.UUID itemID, bool running)
{
}
public void SendAsset(AssetBase asset, AssetRequestInfo req)
{
}
public void SendTexture(AssetBase TextureAsset)
{
}
public byte[] GetThrottlesPacked(float multiplier)
{
return new byte[0];
}
public event ViewerEffectEventHandler OnViewerEffect;
public event Action<IClientAPI> OnLogout;
public event Action<IClientAPI> OnConnectionClosed;
public void SendBlueBoxMessage(OpenMetaverse.UUID FromAvatarID, string FromAvatarName, string Message)
{
}
public void SendLogoutPacket()
{
}
public void SetClientInfo(ClientInfo info)
{
}
public void SetClientOption(string option, string value)
{
}
public string GetClientOption(string option)
{
return String.Empty;
}
public void SendSetFollowCamProperties(OpenMetaverse.UUID objectID, Dictionary<int, float> parameters)
{
}
public void SendClearFollowCamProperties(OpenMetaverse.UUID objectID)
{
}
public void SendRegionHandle(OpenMetaverse.UUID regoinID, ulong handle)
{
}
public void SendParcelInfo(RegionInfo info, LandData land, OpenMetaverse.UUID parcelID, uint x, uint y)
{
}
public void SendScriptTeleportRequest(string objName, string simName, OpenMetaverse.Vector3 pos, OpenMetaverse.Vector3 lookAt)
{
}
public void SendDirPlacesReply(OpenMetaverse.UUID queryID, DirPlacesReplyData[] data)
{
}
public void SendDirPeopleReply(OpenMetaverse.UUID queryID, DirPeopleReplyData[] data)
{
}
public void SendDirEventsReply(OpenMetaverse.UUID queryID, DirEventsReplyData[] data)
{
}
public void SendDirGroupsReply(OpenMetaverse.UUID queryID, DirGroupsReplyData[] data)
{
}
public void SendDirClassifiedReply(OpenMetaverse.UUID queryID, DirClassifiedReplyData[] data)
{
}
public void SendDirLandReply(OpenMetaverse.UUID queryID, DirLandReplyData[] data)
{
}
public void SendDirPopularReply(OpenMetaverse.UUID queryID, DirPopularReplyData[] data)
{
}
public void SendEventInfoReply(EventData info)
{
}
public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags)
{
}
public void SendAvatarGroupsReply(OpenMetaverse.UUID avatarID, GroupMembershipData[] data)
{
}
public void SendOfferCallingCard(OpenMetaverse.UUID srcID, OpenMetaverse.UUID transactionID)
{
}
public void SendAcceptCallingCard(OpenMetaverse.UUID transactionID)
{
}
public void SendDeclineCallingCard(OpenMetaverse.UUID transactionID)
{
}
public void SendTerminateFriend(OpenMetaverse.UUID exFriendID)
{
}
public void SendAvatarClassifiedReply(OpenMetaverse.UUID targetID, OpenMetaverse.UUID[] classifiedID, string[] name)
{
}
public void SendAvatarInterestsReply(OpenMetaverse.UUID avatarID, uint skillsMask, string skillsText, uint wantToMask, string wantToTask, string languagesText)
{
}
public void SendClassifiedInfoReply(OpenMetaverse.UUID classifiedID, OpenMetaverse.UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, OpenMetaverse.UUID parcelID, uint parentEstate, OpenMetaverse.UUID snapshotID, string simName, OpenMetaverse.Vector3 globalPos, string parcelName, byte classifiedFlags, int price)
{
}
public void SendAgentDropGroup(OpenMetaverse.UUID groupID)
{
}
public void RefreshGroupMembership()
{
}
public void SendAvatarNotesReply(OpenMetaverse.UUID targetID, string text)
{
}
public void SendAvatarPicksReply(OpenMetaverse.UUID targetID, Dictionary<OpenMetaverse.UUID, string> picks)
{
}
public void SendPickInfoReply(OpenMetaverse.UUID pickID, OpenMetaverse.UUID creatorID, bool topPick, OpenMetaverse.UUID parcelID, string name, string desc, OpenMetaverse.UUID snapshotID, string user, string originalName, string simName, OpenMetaverse.Vector3 posGlobal, int sortOrder, bool enabled)
{
}
public void SendAvatarClassifiedReply(OpenMetaverse.UUID targetID, Dictionary<OpenMetaverse.UUID, string> classifieds)
{
}
public void SendParcelDwellReply(int localID, OpenMetaverse.UUID parcelID, float dwell)
{
}
public void SendUserInfoReply(bool imViaEmail, bool visible, string email)
{
}
public void SendUseCachedMuteList()
{
}
public void SendMuteListUpdate(string filename)
{
}
public void KillEndDone()
{
}
public bool AddGenericPacketHandler(string MethodName, GenericMessage handler)
{
return false;
}
public void SendChangeUserRights(OpenMetaverse.UUID agent, OpenMetaverse.UUID agentRelated, int relatedRights)
{
}
public void SendTextBoxRequest(string message, int chatChannel, string objectname, OpenMetaverse.UUID ownerID, string firstName, string lastName, OpenMetaverse.UUID objectId)
{
}
public void FreezeMe(uint flags, OpenMetaverse.UUID whoKey, string whoName)
{
bool freeze = ((flags & 1) == 0);
if (freeze != m_frozenUser)
{
m_frozenUser = freeze;
if (m_frozenUser)
{
SendAgentAlertMessage(whoName + " has frozen you in place. You will be unable to move or interact until you log off and start a new session, or until " + whoName + " unfreezes you.", true);
m_log.WarnFormat("{0} has frozen {1} [{2}].", this.Name, whoName, whoKey);
}
else
{
SendAgentAlertMessage(whoName + " has unfrozen you. You are free to move and interact again.", true);
m_log.WarnFormat("{0} has unfrozen {1} [{2}].", this.Name, whoName, whoKey);
}
}
}
public void SendAbortXfer(ulong id, int result)
{
}
public void RunAttachmentOperation(Action action)
{
action();
}
public void SendAgentCachedTexture(List<CachedAgentArgs> args)
{
}
public void SendTelehubInfo(OpenMetaverse.Vector3 TelehubPos, OpenMetaverse.Quaternion TelehubRot, List<OpenMetaverse.Vector3> SpawnPoint, OpenMetaverse.UUID ObjectID, string nameT)
{
}
#endregion
public void HandleWithInventoryWriteThread(Action toHandle)
{
}
public System.Threading.Tasks.Task PauseUpdatesAndFlush()
{
return null;
}
public void ResumeUpdates(IEnumerable<uint> excludeObjectIds)
{
}
public void WaitForClose()
{
}
public void AfterAttachedToConnection(OpenSim.Framework.AgentCircuitData c)
{
}
public List<AgentGroupData> GetAllGroupPowers()
{
return new List<AgentGroupData>();
}
public void SetGroupPowers(IEnumerable<AgentGroupData> groupPowers)
{
}
public int GetThrottleTotal()
{
return 0;
}
public void SetActiveGroupInfo(AgentGroupData activeGroup)
{
}
}
}
| |
// 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Resource usage statistics for a <see cref="CloudJobSchedule"/>.
/// </summary>
public partial class JobScheduleStatistics : IPropertyMetadata
{
private readonly long failedTaskCount;
private readonly TimeSpan kernelCpuTime;
private readonly DateTime lastUpdateTime;
private readonly double readIOGiB;
private readonly long readIOps;
private readonly DateTime startTime;
private readonly long succeededTaskCount;
private readonly long taskRetryCount;
private readonly string url;
private readonly TimeSpan userCpuTime;
private readonly TimeSpan waitTime;
private readonly TimeSpan wallClockTime;
private readonly double writeIOGiB;
private readonly long writeIOps;
#region Constructors
internal JobScheduleStatistics(Models.JobScheduleStatistics protocolObject)
{
this.failedTaskCount = protocolObject.NumFailedTasks;
this.kernelCpuTime = protocolObject.KernelCPUTime;
this.lastUpdateTime = protocolObject.LastUpdateTime;
this.readIOGiB = protocolObject.ReadIOGiB;
this.readIOps = protocolObject.ReadIOps;
this.startTime = protocolObject.StartTime;
this.succeededTaskCount = protocolObject.NumSucceededTasks;
this.taskRetryCount = protocolObject.NumTaskRetries;
this.url = protocolObject.Url;
this.userCpuTime = protocolObject.UserCPUTime;
this.waitTime = protocolObject.WaitTime;
this.wallClockTime = protocolObject.WallClockTime;
this.writeIOGiB = protocolObject.WriteIOGiB;
this.writeIOps = protocolObject.WriteIOps;
}
#endregion Constructors
#region JobScheduleStatistics
/// <summary>
/// Gets the total number of tasks in the job that failed during the given time range.
/// </summary>
public long FailedTaskCount
{
get { return this.failedTaskCount; }
}
/// <summary>
/// Gets the total kernel mode CPU time (per core) consumed by all tasks in the job schedule.
/// </summary>
public TimeSpan KernelCpuTime
{
get { return this.kernelCpuTime; }
}
/// <summary>
/// Gets the time at which the statistics were last updated. All statistics are limited to the range between <see
/// cref="StartTime"/> and this value.
/// </summary>
public DateTime LastUpdateTime
{
get { return this.lastUpdateTime; }
}
/// <summary>
/// Gets the total gibibytes of I/O read from disk by all tasks in the job schedule.
/// </summary>
public double ReadIOGiB
{
get { return this.readIOGiB; }
}
/// <summary>
/// Gets the total number of disk read operations made by all tasks in the job schedule.
/// </summary>
public long ReadIOps
{
get { return this.readIOps; }
}
/// <summary>
/// Gets the start time of the time range covered by the statistics.
/// </summary>
public DateTime StartTime
{
get { return this.startTime; }
}
/// <summary>
/// Gets the total number of tasks successfully completed in the job schedule.
/// </summary>
public long SucceededTaskCount
{
get { return this.succeededTaskCount; }
}
/// <summary>
/// Gets the total number of retries that occurred on all tasks in the job schedule.
/// </summary>
public long TaskRetryCount
{
get { return this.taskRetryCount; }
}
/// <summary>
/// Gets the URL of the statistics.
/// </summary>
public string Url
{
get { return this.url; }
}
/// <summary>
/// Gets the total user mode CPU time (per core) consumed by all tasks in the job schedule.
/// </summary>
public TimeSpan UserCpuTime
{
get { return this.userCpuTime; }
}
/// <summary>
/// Gets the total wait time of all tasks in jobs created under the schedule. The wait time for a task is defined
/// as the elapsed time between the creation of the task and the start of task execution. (If the task is retried
/// due to failures, the wait time is the time to the most recent task execution.)
/// </summary>
/// <remarks>
/// This value is only reported in the account lifetime statistics.
/// </remarks>
public TimeSpan WaitTime
{
get { return this.waitTime; }
}
/// <summary>
/// Gets the total wall clock time of all tasks in the job schedule. Note that if any task was retried multiple times,
/// this includes the wall clock time of all the task retries.
/// </summary>
public TimeSpan WallClockTime
{
get { return this.wallClockTime; }
}
/// <summary>
/// Gets the total gibibytes of I/O written to disk by all tasks in the job schedule.
/// </summary>
public double WriteIOGiB
{
get { return this.writeIOGiB; }
}
/// <summary>
/// Gets the total number of disk write operations made by all tasks in the job schedule.
/// </summary>
public long WriteIOps
{
get { return this.writeIOps; }
}
#endregion // JobScheduleStatistics
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
//This class is compile time readonly so it cannot have been modified
get { return false; }
}
bool IReadOnly.IsReadOnly
{
get { return true; }
set
{
// This class is compile time readonly already
}
}
#endregion // IPropertyMetadata
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace SocketHttpListener
{
internal class WebSocketFrame : IEnumerable<byte>
{
#region Private Fields
private byte[] _extPayloadLength;
private Fin _fin;
private Mask _mask;
private byte[] _maskingKey;
private Opcode _opcode;
private PayloadData _payloadData;
private byte _payloadLength;
private Rsv _rsv1;
private Rsv _rsv2;
private Rsv _rsv3;
#endregion
#region Internal Fields
internal static readonly byte[] EmptyUnmaskPingData;
#endregion
#region Static Constructor
static WebSocketFrame()
{
EmptyUnmaskPingData = CreatePingFrame(Mask.Unmask).ToByteArray();
}
#endregion
#region Private Constructors
private WebSocketFrame()
{
}
#endregion
#region Internal Constructors
internal WebSocketFrame(Opcode opcode, PayloadData payload)
: this(Fin.Final, opcode, Mask.Mask, payload, false)
{
}
internal WebSocketFrame(Opcode opcode, Mask mask, PayloadData payload)
: this(Fin.Final, opcode, mask, payload, false)
{
}
internal WebSocketFrame(Fin fin, Opcode opcode, Mask mask, PayloadData payload)
: this(fin, opcode, mask, payload, false)
{
}
internal WebSocketFrame(
Fin fin, Opcode opcode, Mask mask, PayloadData payload, bool compressed)
{
_fin = fin;
_rsv1 = isData(opcode) && compressed ? Rsv.On : Rsv.Off;
_rsv2 = Rsv.Off;
_rsv3 = Rsv.Off;
_opcode = opcode;
_mask = mask;
var len = payload.Length;
if (len < 126)
{
_payloadLength = (byte)len;
_extPayloadLength = new byte[0];
}
else if (len < 0x010000)
{
_payloadLength = (byte)126;
_extPayloadLength = ((ushort)len).ToByteArrayInternally(ByteOrder.Big);
}
else
{
_payloadLength = (byte)127;
_extPayloadLength = len.ToByteArrayInternally(ByteOrder.Big);
}
if (mask == Mask.Mask)
{
_maskingKey = createMaskingKey();
payload.Mask(_maskingKey);
}
else
{
_maskingKey = new byte[0];
}
_payloadData = payload;
}
#endregion
#region Public Properties
public byte[] ExtendedPayloadLength
{
get
{
return _extPayloadLength;
}
}
public Fin Fin
{
get
{
return _fin;
}
}
public bool IsBinary
{
get
{
return _opcode == Opcode.Binary;
}
}
public bool IsClose
{
get
{
return _opcode == Opcode.Close;
}
}
public bool IsCompressed
{
get
{
return _rsv1 == Rsv.On;
}
}
public bool IsContinuation
{
get
{
return _opcode == Opcode.Cont;
}
}
public bool IsControl
{
get
{
return _opcode == Opcode.Close || _opcode == Opcode.Ping || _opcode == Opcode.Pong;
}
}
public bool IsData
{
get
{
return _opcode == Opcode.Binary || _opcode == Opcode.Text;
}
}
public bool IsFinal
{
get
{
return _fin == Fin.Final;
}
}
public bool IsFragmented
{
get
{
return _fin == Fin.More || _opcode == Opcode.Cont;
}
}
public bool IsMasked
{
get
{
return _mask == Mask.Mask;
}
}
public bool IsPerMessageCompressed
{
get
{
return (_opcode == Opcode.Binary || _opcode == Opcode.Text) && _rsv1 == Rsv.On;
}
}
public bool IsPing
{
get
{
return _opcode == Opcode.Ping;
}
}
public bool IsPong
{
get
{
return _opcode == Opcode.Pong;
}
}
public bool IsText
{
get
{
return _opcode == Opcode.Text;
}
}
public ulong Length
{
get
{
return 2 + (ulong)(_extPayloadLength.Length + _maskingKey.Length) + _payloadData.Length;
}
}
public Mask Mask
{
get
{
return _mask;
}
}
public byte[] MaskingKey
{
get
{
return _maskingKey;
}
}
public Opcode Opcode
{
get
{
return _opcode;
}
}
public PayloadData PayloadData
{
get
{
return _payloadData;
}
}
public byte PayloadLength
{
get
{
return _payloadLength;
}
}
public Rsv Rsv1
{
get
{
return _rsv1;
}
}
public Rsv Rsv2
{
get
{
return _rsv2;
}
}
public Rsv Rsv3
{
get
{
return _rsv3;
}
}
#endregion
#region Private Methods
private static byte[] createMaskingKey()
{
var key = new byte[4];
var rand = new Random();
rand.NextBytes(key);
return key;
}
private static string dump(WebSocketFrame frame)
{
var len = frame.Length;
var cnt = (long)(len / 4);
var rem = (int)(len % 4);
int cntDigit;
string cntFmt;
if (cnt < 10000)
{
cntDigit = 4;
cntFmt = "{0,4}";
}
else if (cnt < 0x010000)
{
cntDigit = 4;
cntFmt = "{0,4:X}";
}
else if (cnt < 0x0100000000)
{
cntDigit = 8;
cntFmt = "{0,8:X}";
}
else
{
cntDigit = 16;
cntFmt = "{0,16:X}";
}
var spFmt = String.Format("{{0,{0}}}", cntDigit);
var headerFmt = String.Format(
@"{0} 01234567 89ABCDEF 01234567 89ABCDEF
{0}+--------+--------+--------+--------+\n", spFmt);
var lineFmt = String.Format("{0}|{{1,8}} {{2,8}} {{3,8}} {{4,8}}|\n", cntFmt);
var footerFmt = String.Format("{0}+--------+--------+--------+--------+", spFmt);
var output = new StringBuilder(64);
Func<Action<string, string, string, string>> linePrinter = () =>
{
long lineCnt = 0;
return (arg1, arg2, arg3, arg4) =>
output.AppendFormat(lineFmt, ++lineCnt, arg1, arg2, arg3, arg4);
};
output.AppendFormat(headerFmt, String.Empty);
var printLine = linePrinter();
var frameAsBytes = frame.ToByteArray();
for (long i = 0; i <= cnt; i++)
{
var j = i * 4;
if (i < cnt)
printLine(
Convert.ToString(frameAsBytes[j], 2).PadLeft(8, '0'),
Convert.ToString(frameAsBytes[j + 1], 2).PadLeft(8, '0'),
Convert.ToString(frameAsBytes[j + 2], 2).PadLeft(8, '0'),
Convert.ToString(frameAsBytes[j + 3], 2).PadLeft(8, '0'));
else if (rem > 0)
printLine(
Convert.ToString(frameAsBytes[j], 2).PadLeft(8, '0'),
rem >= 2 ? Convert.ToString(frameAsBytes[j + 1], 2).PadLeft(8, '0') : String.Empty,
rem == 3 ? Convert.ToString(frameAsBytes[j + 2], 2).PadLeft(8, '0') : String.Empty,
String.Empty);
}
output.AppendFormat(footerFmt, String.Empty);
return output.ToString();
}
private static bool isControl(Opcode opcode)
{
return opcode == Opcode.Close || opcode == Opcode.Ping || opcode == Opcode.Pong;
}
private static bool isData(Opcode opcode)
{
return opcode == Opcode.Text || opcode == Opcode.Binary;
}
private static string print(WebSocketFrame frame)
{
/* Opcode */
var opcode = frame._opcode.ToString();
/* Payload Length */
var payloadLen = frame._payloadLength;
/* Extended Payload Length */
var ext = frame._extPayloadLength;
var size = ext.Length;
var extPayloadLen = size == 2
? ext.ToUInt16(ByteOrder.Big).ToString()
: size == 8
? ext.ToUInt64(ByteOrder.Big).ToString()
: String.Empty;
/* Masking Key */
var masked = frame.IsMasked;
var maskingKey = masked ? BitConverter.ToString(frame._maskingKey) : String.Empty;
/* Payload Data */
var payload = payloadLen == 0
? String.Empty
: size > 0
? String.Format("A {0} frame.", opcode.ToLower())
: !masked && !frame.IsFragmented && frame.IsText
? Encoding.UTF8.GetString(frame._payloadData.ApplicationData)
: frame._payloadData.ToString();
var fmt =
@" FIN: {0}
RSV1: {1}
RSV2: {2}
RSV3: {3}
Opcode: {4}
MASK: {5}
Payload Length: {6}
Extended Payload Length: {7}
Masking Key: {8}
Payload Data: {9}";
return String.Format(
fmt,
frame._fin,
frame._rsv1,
frame._rsv2,
frame._rsv3,
opcode,
frame._mask,
payloadLen,
extPayloadLen,
maskingKey,
payload);
}
private static WebSocketFrame read(byte[] header, Stream stream, bool unmask)
{
/* Header */
// FIN
var fin = (header[0] & 0x80) == 0x80 ? Fin.Final : Fin.More;
// RSV1
var rsv1 = (header[0] & 0x40) == 0x40 ? Rsv.On : Rsv.Off;
// RSV2
var rsv2 = (header[0] & 0x20) == 0x20 ? Rsv.On : Rsv.Off;
// RSV3
var rsv3 = (header[0] & 0x10) == 0x10 ? Rsv.On : Rsv.Off;
// Opcode
var opcode = (Opcode)(header[0] & 0x0f);
// MASK
var mask = (header[1] & 0x80) == 0x80 ? Mask.Mask : Mask.Unmask;
// Payload Length
var payloadLen = (byte)(header[1] & 0x7f);
// Check if correct frame.
var incorrect = isControl(opcode) && fin == Fin.More
? "A control frame is fragmented."
: !isData(opcode) && rsv1 == Rsv.On
? "A non data frame is compressed."
: null;
if (incorrect != null)
throw new WebSocketException(CloseStatusCode.IncorrectData, incorrect);
// Check if consistent frame.
if (isControl(opcode) && payloadLen > 125)
throw new WebSocketException(
CloseStatusCode.InconsistentData,
"The length of payload data of a control frame is greater than 125 bytes.");
var frame = new WebSocketFrame();
frame._fin = fin;
frame._rsv1 = rsv1;
frame._rsv2 = rsv2;
frame._rsv3 = rsv3;
frame._opcode = opcode;
frame._mask = mask;
frame._payloadLength = payloadLen;
/* Extended Payload Length */
var size = payloadLen < 126
? 0
: payloadLen == 126
? 2
: 8;
var extPayloadLen = size > 0 ? stream.ReadBytes(size) : new byte[0];
if (size > 0 && extPayloadLen.Length != size)
throw new WebSocketException(
"The 'Extended Payload Length' of a frame cannot be read from the data source.");
frame._extPayloadLength = extPayloadLen;
/* Masking Key */
var masked = mask == Mask.Mask;
var maskingKey = masked ? stream.ReadBytes(4) : new byte[0];
if (masked && maskingKey.Length != 4)
throw new WebSocketException(
"The 'Masking Key' of a frame cannot be read from the data source.");
frame._maskingKey = maskingKey;
/* Payload Data */
ulong len = payloadLen < 126
? payloadLen
: payloadLen == 126
? extPayloadLen.ToUInt16(ByteOrder.Big)
: extPayloadLen.ToUInt64(ByteOrder.Big);
byte[] data = null;
if (len > 0)
{
// Check if allowable payload data length.
if (payloadLen > 126 && len > PayloadData.MaxLength)
throw new WebSocketException(
CloseStatusCode.TooBig,
"The length of 'Payload Data' of a frame is greater than the allowable length.");
data = payloadLen > 126
? stream.ReadBytes((long)len, 1024)
: stream.ReadBytes((int)len);
if (data.LongLength != (long)len)
throw new WebSocketException(
"The 'Payload Data' of a frame cannot be read from the data source.");
}
else
{
data = new byte[0];
}
var payload = new PayloadData(data, masked);
if (masked && unmask)
{
payload.Mask(maskingKey);
frame._mask = Mask.Unmask;
frame._maskingKey = new byte[0];
}
frame._payloadData = payload;
return frame;
}
#endregion
#region Internal Methods
internal static WebSocketFrame CreateCloseFrame(Mask mask, byte[] data)
{
return new WebSocketFrame(Opcode.Close, mask, new PayloadData(data));
}
internal static WebSocketFrame CreateCloseFrame(Mask mask, PayloadData payload)
{
return new WebSocketFrame(Opcode.Close, mask, payload);
}
internal static WebSocketFrame CreateCloseFrame(Mask mask, CloseStatusCode code, string reason)
{
return new WebSocketFrame(
Opcode.Close, mask, new PayloadData(((ushort)code).Append(reason)));
}
internal static WebSocketFrame CreatePingFrame(Mask mask)
{
return new WebSocketFrame(Opcode.Ping, mask, new PayloadData());
}
internal static WebSocketFrame CreatePingFrame(Mask mask, byte[] data)
{
return new WebSocketFrame(Opcode.Ping, mask, new PayloadData(data));
}
internal static WebSocketFrame CreatePongFrame(Mask mask, PayloadData payload)
{
return new WebSocketFrame(Opcode.Pong, mask, payload);
}
internal static WebSocketFrame CreateWebSocketFrame(
Fin fin, Opcode opcode, Mask mask, byte[] data, bool compressed)
{
return new WebSocketFrame(fin, opcode, mask, new PayloadData(data), compressed);
}
internal static WebSocketFrame Read(Stream stream)
{
return Read(stream, true);
}
internal static WebSocketFrame Read(Stream stream, bool unmask)
{
var header = stream.ReadBytes(2);
if (header.Length != 2)
throw new WebSocketException(
"The header part of a frame cannot be read from the data source.");
return read(header, stream, unmask);
}
internal static void ReadAsync(
Stream stream, Action<WebSocketFrame> completed, Action<Exception> error)
{
ReadAsync(stream, true, completed, error);
}
internal static void ReadAsync(
Stream stream, bool unmask, Action<WebSocketFrame> completed, Action<Exception> error)
{
stream.ReadBytesAsync(
2,
header =>
{
if (header.Length != 2)
throw new WebSocketException(
"The header part of a frame cannot be read from the data source.");
var frame = read(header, stream, unmask);
if (completed != null)
completed(frame);
},
error);
}
#endregion
#region Public Methods
public IEnumerator<byte> GetEnumerator()
{
foreach (var b in ToByteArray())
yield return b;
}
public void Print(bool dumped)
{
Console.WriteLine(dumped ? dump(this) : print(this));
}
public string PrintToString(bool dumped)
{
return dumped
? dump(this)
: print(this);
}
public byte[] ToByteArray()
{
using (var buff = new MemoryStream())
{
var header = (int)_fin;
header = (header << 1) + (int)_rsv1;
header = (header << 1) + (int)_rsv2;
header = (header << 1) + (int)_rsv3;
header = (header << 4) + (int)_opcode;
header = (header << 1) + (int)_mask;
header = (header << 7) + (int)_payloadLength;
buff.Write(((ushort)header).ToByteArrayInternally(ByteOrder.Big), 0, 2);
if (_payloadLength > 125)
buff.Write(_extPayloadLength, 0, _extPayloadLength.Length);
if (_mask == Mask.Mask)
buff.Write(_maskingKey, 0, _maskingKey.Length);
if (_payloadLength > 0)
{
var payload = _payloadData.ToByteArray();
if (_payloadLength < 127)
buff.Write(payload, 0, payload.Length);
else
buff.WriteBytes(payload);
}
buff.Close();
return buff.ToArray();
}
}
public override string ToString()
{
return BitConverter.ToString(ToByteArray());
}
#endregion
#region Explicitly Implemented Interface Members
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
| |
/*
* Copyright (c) 2007-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
namespace OpenMetaverse
{
/// <summary>
/// The InternalDictionary class is used through the library for storing key/value pairs.
/// It is intended to be a replacement for the generic Dictionary class and should
/// be used in its place. It contains several methods for allowing access to the data from
/// outside the library that are read only and thread safe.
///
/// </summary>
/// <typeparam name="TKey">Key <see langword="Tkey"/></typeparam>
/// <typeparam name="TValue">Value <see langword="TValue"/></typeparam>
public class InternalDictionary<TKey, TValue>
{
/// <summary>Internal dictionary that this class wraps around. Do not
/// modify or enumerate the contents of this dictionary without locking
/// on this member</summary>
internal Dictionary<TKey, TValue> Dictionary;
public Dictionary<TKey,TValue> Copy()
{
lock (Dictionary)
return new Dictionary<TKey, TValue>(Dictionary);
}
/// <summary>
/// Gets the number of Key/Value pairs contained in the <seealso cref="T:InternalDictionary"/>
/// </summary>
public int Count { get { return Dictionary.Count; } }
/// <summary>
/// Initializes a new instance of the <seealso cref="T:InternalDictionary"/> Class
/// with the specified key/value, has the default initial capacity.
/// </summary>
/// <example>
/// <code>
/// // initialize a new InternalDictionary named testDict with a string as the key and an int as the value.
/// public InternalDictionary<string, int> testDict = new InternalDictionary<string, int>();
/// </code>
/// </example>
public InternalDictionary()
{
Dictionary = new Dictionary<TKey, TValue>();
}
/// <summary>
/// Initializes a new instance of the <seealso cref="T:InternalDictionary"/> Class
/// with the specified key/value, has its initial valies copied from the specified
/// <seealso cref="T:System.Collections.Generic.Dictionary"/>
/// </summary>
/// <param name="dictionary"><seealso cref="T:System.Collections.Generic.Dictionary"/>
/// to copy initial values from</param>
/// <example>
/// <code>
/// // initialize a new InternalDictionary named testAvName with a UUID as the key and an string as the value.
/// // populates with copied values from example KeyNameCache Dictionary.
///
/// // create source dictionary
/// Dictionary<UUID, string> KeyNameCache = new Dictionary<UUID, string>();
/// KeyNameCache.Add("8300f94a-7970-7810-cf2c-fc9aa6cdda24", "Jack Avatar");
/// KeyNameCache.Add("27ba1e40-13f7-0708-3e98-5819d780bd62", "Jill Avatar");
///
/// // Initialize new dictionary.
/// public InternalDictionary<UUID, string> testAvName = new InternalDictionary<UUID, string>(KeyNameCache);
/// </code>
/// </example>
public InternalDictionary(IDictionary<TKey, TValue> dictionary)
{
Dictionary = new Dictionary<TKey, TValue>(dictionary);
}
/// <summary>
/// Initializes a new instance of the <seealso cref="T:OpenMetaverse.InternalDictionary"/> Class
/// with the specified key/value, With its initial capacity specified.
/// </summary>
/// <param name="capacity">Initial size of dictionary</param>
/// <example>
/// <code>
/// // initialize a new InternalDictionary named testDict with a string as the key and an int as the value,
/// // initially allocated room for 10 entries.
/// public InternalDictionary<string, int> testDict = new InternalDictionary<string, int>(10);
/// </code>
/// </example>
public InternalDictionary(int capacity)
{
Dictionary = new Dictionary<TKey, TValue>(capacity);
}
/// <summary>
/// Try to get entry from <seealso cref="T:OpenMetaverse.InternalDictionary"/> with specified key
/// </summary>
/// <param name="key">Key to use for lookup</param>
/// <param name="value">Value returned</param>
/// <returns><see langword="true"/> if specified key exists, <see langword="false"/> if not found</returns>
/// <example>
/// <code>
/// // find your avatar using the Simulator.ObjectsAvatars InternalDictionary:
/// Avatar av;
/// if (Client.Network.CurrentSim.ObjectsAvatars.TryGetValue(Client.Self.AgentID, out av))
/// Console.WriteLine("Found Avatar {0}", av.Name);
/// </code>
/// <seealso cref="Simulator.ObjectsAvatars"/>
/// </example>
public bool TryGetValue(TKey key, out TValue value)
{
lock (Dictionary)
{
return Dictionary.TryGetValue(key, out value);
}
}
/// <summary>
/// Finds the specified match.
/// </summary>
/// <param name="match">The match.</param>
/// <returns>Matched value</returns>
/// <example>
/// <code>
/// // use a delegate to find a prim in the ObjectsPrimitives InternalDictionary
/// // with the ID 95683496
/// uint findID = 95683496;
/// Primitive findPrim = sim.ObjectsPrimitives.Find(
/// delegate(Primitive prim) { return prim.ID == findID; });
/// </code>
/// </example>
public TValue Find(Predicate<TValue> match)
{
lock (Dictionary)
{
foreach (TValue value in Dictionary.Values)
{
if (match(value))
return value;
}
}
return default(TValue);
}
/// <summary>Find All items in an <seealso cref="T:InternalDictionary"/></summary>
/// <param name="match">return matching items.</param>
/// <returns>a <seealso cref="T:System.Collections.Generic.List"/> containing found items.</returns>
/// <example>
/// Find All prims within 20 meters and store them in a List
/// <code>
/// int radius = 20;
/// List<Primitive> prims = Client.Network.CurrentSim.ObjectsPrimitives.FindAll(
/// delegate(Primitive prim) {
/// Vector3 pos = prim.Position;
/// return ((prim.ParentID == 0) && (pos != Vector3.Zero) && (Vector3.Distance(pos, location) < radius));
/// }
/// );
///</code>
///</example>
public List<TValue> FindAll(Predicate<TValue> match)
{
List<TValue> found = new List<TValue>();
lock (Dictionary)
{
foreach (KeyValuePair<TKey, TValue> kvp in Dictionary)
{
if (match(kvp.Value))
found.Add(kvp.Value);
}
}
return found;
}
/// <summary>Find All items in an <seealso cref="T:InternalDictionary"/></summary>
/// <param name="match">return matching keys.</param>
/// <returns>a <seealso cref="T:System.Collections.Generic.List"/> containing found keys.</returns>
/// <example>
/// Find All keys which also exist in another dictionary
/// <code>
/// List<UUID> matches = myDict.FindAll(
/// delegate(UUID id) {
/// return myOtherDict.ContainsKey(id);
/// }
/// );
///</code>
///</example>
public List<TKey> FindAll(Predicate<TKey> match)
{
List<TKey> found = new List<TKey>();
lock (Dictionary)
{
foreach (KeyValuePair<TKey, TValue> kvp in Dictionary)
{
if (match(kvp.Key))
found.Add(kvp.Key);
}
}
return found;
}
/// <summary>Perform an <seealso cref="T:System.Action"/> on each entry in an <seealso cref="T:OpenMetaverse.InternalDictionary"/></summary>
/// <param name="action"><seealso cref="T:System.Action"/> to perform</param>
/// <example>
/// <code>
/// // Iterates over the ObjectsPrimitives InternalDictionary and prints out some information.
/// Client.Network.CurrentSim.ObjectsPrimitives.ForEach(
/// delegate(Primitive prim)
/// {
/// if (prim.Text != null)
/// {
/// Console.WriteLine("NAME={0} ID = {1} TEXT = '{2}'",
/// prim.PropertiesFamily.Name, prim.ID, prim.Text);
/// }
/// });
///</code>
///</example>
public void ForEach(Action<TValue> action)
{
lock (Dictionary)
{
foreach (TValue value in Dictionary.Values)
{
action(value);
}
}
}
/// <summary>Perform an <seealso cref="T:System.Action"/> on each key of an <seealso cref="T:OpenMetaverse.InternalDictionary"/></summary>
/// <param name="action"><seealso cref="T:System.Action"/> to perform</param>
public void ForEach(Action<TKey> action)
{
lock (Dictionary)
{
foreach (TKey key in Dictionary.Keys)
{
action(key);
}
}
}
/// <summary>
/// Perform an <seealso cref="T:System.Action"/> on each KeyValuePair of an <seealso cref="T:OpenMetaverse.InternalDictionary"/>
/// </summary>
/// <param name="action"><seealso cref="T:System.Action"/> to perform</param>
public void ForEach(Action<KeyValuePair<TKey, TValue>> action)
{
lock (Dictionary)
{
foreach (KeyValuePair<TKey, TValue> entry in Dictionary)
{
action(entry);
}
}
}
/// <summary>Check if Key exists in Dictionary</summary>
/// <param name="key">Key to check for</param>
/// <returns><see langword="true"/> if found, <see langword="false"/> otherwise</returns>
public bool ContainsKey(TKey key)
{
return Dictionary.ContainsKey(key);
}
/// <summary>Check if Value exists in Dictionary</summary>
/// <param name="value">Value to check for</param>
/// <returns><see langword="true"/> if found, <see langword="false"/> otherwise</returns>
public bool ContainsValue(TValue value)
{
return Dictionary.ContainsValue(value);
}
/// <summary>
/// Adds the specified key to the dictionary, dictionary locking is not performed,
/// <see cref="SafeAdd"/>
/// </summary>
/// <param name="key">The key</param>
/// <param name="value">The value</param>
internal void Add(TKey key, TValue value)
{
lock (Dictionary)
Dictionary.Add(key, value);
}
/// <summary>
/// Removes the specified key, dictionary locking is not performed
/// </summary>
/// <param name="key">The key.</param>
/// <returns><see langword="true"/> if successful, <see langword="false"/> otherwise</returns>
internal bool Remove(TKey key)
{
lock (Dictionary)
return Dictionary.Remove(key);
}
/// <summary>
/// Indexer for the dictionary
/// </summary>
/// <param name="key">The key</param>
/// <returns>The value</returns>
public TValue this[TKey key]
{
get
{
lock (Dictionary)
return Dictionary[key];
}
internal set
{
lock (Dictionary)
Dictionary[key] = value;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using NuGet.Packaging.Core;
using NuGet.Versioning;
namespace Sleet
{
/// <summary>
/// Package registrations are an index to the catalog.
/// </summary>
public class Registrations : ISleetService, IPackageIdLookup, IAddRemovePackages
{
private readonly SleetContext _context;
public string Name { get; } = nameof(Registrations);
public Registrations(SleetContext context)
{
_context = context;
}
public Task AddPackageAsync(PackageInput package)
{
return AddPackagesAsync(new[] { package });
}
public Task RemovePackageAsync(PackageIdentity package)
{
return RemovePackagesAsync(new[] { package });
}
private void DeletePackagePage(PackageIdentity package)
{
// Delete package page
var packageUri = GetPackageUri(package);
var packageFile = _context.Source.Get(packageUri);
packageFile.Delete(_context.Log, _context.Token);
}
public Task AddPackagesAsync(IEnumerable<PackageInput> packageInputs)
{
var byId = SleetUtility.GetPackageSetsById(packageInputs, e => e.Identity.Id);
var tasks = new List<Func<Task>>();
// Create page details pages and index pages in parallel.
tasks.AddRange(byId.Select(e => new Func<Task>(() => CreatePackageIndexAsync(e.Key, e.Value))));
tasks.AddRange(packageInputs.Select(e => new Func<Task>(() => CreatePackagePageAsync(e))));
return TaskUtils.RunAsync(tasks);
}
private async Task CreatePackageIndexAsync(string packageId, List<PackageInput> packageInputs)
{
// Retrieve index
var rootUri = GetIndexUri(packageId);
var rootFile = _context.Source.Get(rootUri);
using (var timer = PerfEntryWrapper.CreateModifyTimer(rootFile, _context))
{
var packages = new List<JObject>();
var json = await rootFile.GetJsonOrNull(_context.Log, _context.Token);
if (json != null)
{
// Get all entries
packages = await GetPackageDetails(json);
}
// Remove any duplicates from the file
var newPackageVersions = new HashSet<NuGetVersion>(packageInputs.Select(e => e.Identity.Version));
foreach (var existingPackage in packages.ToArray())
{
var existingVersion = GetPackageVersion(existingPackage);
if (newPackageVersions.Contains(existingVersion))
{
packages.Remove(existingPackage);
_context.Log.LogWarning($"Removed duplicate registration entry for: {new PackageIdentity(packageId, existingVersion)}");
}
}
// Add package entries
foreach (var package in packageInputs)
{
// Add entry
var newEntry = CreateItem(package);
packages.Add(newEntry);
}
// Create index
var newIndexJson = await CreateIndexAsync(rootUri, packages);
// Write
await rootFile.Write(newIndexJson, _context.Log, _context.Token);
}
}
/// <summary>
/// Create a package details page for a package id/version.
/// </summary>
private async Task CreatePackagePageAsync(PackageInput package)
{
// Create package page
var packageUri = GetPackageUri(package.Identity);
var packageFile = _context.Source.Get(packageUri);
using (var timer = PerfEntryWrapper.CreateModifyTimer(packageFile, _context))
{
var packageJson = await CreatePackageBlobAsync(package);
// Write package page
await packageFile.Write(packageJson, _context.Log, _context.Token);
}
}
public Task RemovePackagesAsync(IEnumerable<PackageIdentity> packagesToDelete)
{
var byId = SleetUtility.GetPackageSetsById(packagesToDelete, e => e.Id);
var tasks = new List<Func<Task>>();
foreach (var pair in byId)
{
var packageId = pair.Key;
var versions = new HashSet<NuGetVersion>(pair.Value.Select(e => e.Version));
tasks.Add(new Func<Task>(() => RemovePackagesFromIndexAsync(packageId, versions)));
}
return TaskUtils.RunAsync(tasks);
}
/// <summary>
/// Remove packages from index and remove details pages if they exist.
/// </summary>
private async Task RemovePackagesFromIndexAsync(string packageId, HashSet<NuGetVersion> versions)
{
// Retrieve index
var rootUri = GetIndexUri(packageId);
var rootFile = _context.Source.Get(rootUri);
using (var timer = PerfEntryWrapper.CreateModifyTimer(rootFile, _context))
{
var modified = false;
var packages = new List<JObject>();
var json = await rootFile.GetJsonOrNull(_context.Log, _context.Token);
if (json != null)
{
// Get all entries
packages = await GetPackageDetails(json);
foreach (var entry in packages.ToArray())
{
var version = GetPackageVersion(entry);
if (versions.Contains(version))
{
modified = true;
packages.Remove(entry);
// delete details page
DeletePackagePage(new PackageIdentity(packageId, version));
}
}
}
if (modified)
{
if (packages.Count > 0)
{
// Create index
var newIndexJson = await CreateIndexAsync(rootUri, packages);
// Write
await rootFile.Write(newIndexJson, _context.Log, _context.Token);
}
else
{
// This package id been completely removed
rootFile.Delete(_context.Log, _context.Token);
}
}
}
}
/// <summary>
/// Get all package details from all pages
/// </summary>
public Task<List<JObject>> GetPackageDetails(JObject json)
{
var pages = GetItems(json);
return Task.FromResult(pages.SelectMany(GetItems).ToList());
}
public async Task<JObject> CreateIndexAsync(Uri indexUri, List<JObject> packageDetails)
{
var json = JsonUtility.Create(indexUri,
new string[] {
"catalog:CatalogRoot",
"PackageRegistration",
"catalog:Permalink"
});
json.Add("commitId", _context.CommitId.ToString().ToLowerInvariant());
json.Add("commitTimeStamp", DateTimeOffset.UtcNow.GetDateString());
var itemsArray = new JArray();
json.Add("items", itemsArray);
json.Add("count", 1);
// Add everything to a single page
var pageJson = CreatePage(indexUri, packageDetails);
itemsArray.Add(pageJson);
var context = await JsonUtility.GetContextAsync("Registration");
json.Add("@context", context);
// Avoid formatting all package details again since this file could be very large.
return JsonLDTokenComparer.Format(json, recurse: false);
}
public JObject CreatePage(Uri indexUri, List<JObject> packageDetails)
{
var versionSet = new HashSet<NuGetVersion>(packageDetails.Select(GetPackageVersion));
var lower = versionSet.Min().ToIdentityString().ToLowerInvariant();
var upper = versionSet.Max().ToIdentityString().ToLowerInvariant();
var json = JsonUtility.Create(indexUri, $"page/{lower}/{upper}", "catalog:CatalogPage");
json.Add("commitId", _context.CommitId.ToString().ToLowerInvariant());
json.Add("commitTimeStamp", DateTimeOffset.UtcNow.GetDateString());
json.Add("count", packageDetails.Count);
json.Add("parent", indexUri.AbsoluteUri);
json.Add("lower", lower);
json.Add("upper", upper);
// Order and add all items
var itemsArray = new JArray(packageDetails.OrderBy(GetPackageVersion));
json.Add("items", itemsArray);
return JsonLDTokenComparer.Format(json, recurse: false);
}
public static NuGetVersion GetPackageVersion(JObject packageDetails)
{
var catalogEntry = (JObject)packageDetails["catalogEntry"];
var version = NuGetVersion.Parse(catalogEntry.Property("version").Value.ToString());
return version;
}
/// <summary>
/// Get items from a page or index page.
/// </summary>
public static List<JObject> GetItems(JObject json)
{
var result = new List<JObject>();
if (json["items"] is JArray items)
{
foreach (var item in items)
{
result.Add((JObject)item);
}
}
return result;
}
public Uri GetIndexUri(PackageIdentity package)
{
return GetIndexUri(package.Id);
}
public Uri GetIndexUri(string packageId)
{
return UriUtility.CreateUri($"{_context.Source.BaseURI}registration/{packageId.ToLowerInvariant()}/index.json");
}
public static Uri GetIndexUri(Uri sourceRoot, string packageId)
{
return UriUtility.CreateUri($"{sourceRoot.AbsoluteUri}registration/{packageId.ToLowerInvariant()}/index.json");
}
public Uri GetPackageUri(PackageIdentity package)
{
return UriUtility.CreateUri($"{_context.Source.BaseURI}registration/{package.Id.ToLowerInvariant()}/{package.Version.ToIdentityString().ToLowerInvariant()}.json");
}
public static Uri GetPackageUri(Uri sourceRoot, PackageIdentity package)
{
return UriUtility.CreateUri($"{sourceRoot.AbsoluteUri}registration/{package.Id.ToLowerInvariant()}/{package.Version.ToIdentityString().ToLowerInvariant()}.json");
}
/// <summary>
/// Retrieve the PackageDetails from a package blob.
/// </summary>
public async Task<JObject> GetCatalogEntryFromPackageBlob(PackageIdentity package)
{
var uri = GetPackageUri(package);
var file = _context.Source.Get(uri);
var json = await file.GetJsonOrNull(_context.Log, _context.Token);
if (json != null)
{
return json["sleet:catalogEntry"] as JObject;
}
return null;
}
public async Task<JObject> CreatePackageBlobAsync(PackageInput packageInput)
{
var rootUri = GetPackageUri(packageInput.Identity);
var json = JsonUtility.Create(rootUri, new string[] { "Package", "http://schema.nuget.org/catalog#Permalink" });
json.Add("catalogEntry", packageInput.PackageDetails.GetIdUri().AbsoluteUri);
json.Add("packageContent", packageInput.PackageDetails["packageContent"].ToString());
json.Add("registration", GetIndexUri(packageInput.Identity));
var copyProperties = new List<string>()
{
"listed",
"published",
};
JsonUtility.CopyProperties(packageInput.PackageDetails, json, copyProperties, skipEmpty: true);
// Copy the catalog entry into the package blob. This allows the feed to
// save this info even if the catalog is disabled.
// Note that this is different from NuGet.org, so the sleet: namespace is used.
var catalogEntry = (JObject)packageInput.PackageDetails.DeepClone();
// Clear packageEntries, this can be very large in some cases.
catalogEntry.Remove("packageEntries");
json.Add("sleet:catalogEntry", catalogEntry);
var context = await JsonUtility.GetContextAsync("Package");
json.Add("@context", context);
return JsonLDTokenComparer.Format(json);
}
/// <summary>
/// Create a package item entry.
/// </summary>
public JObject CreateItem(PackageInput packageInput)
{
var rootUri = GetPackageUri(packageInput.Identity);
var json = JsonUtility.Create(rootUri, "Package");
json.Add("commitId", _context.CommitId.ToString().ToLowerInvariant());
json.Add("commitTimeStamp", DateTimeOffset.UtcNow.GetDateString());
json.Add("packageContent", packageInput.PackageDetails["packageContent"].ToString());
json.Add("registration", GetIndexUri(packageInput.Identity));
var copyProperties = new List<string>()
{
"@id",
"@type",
"authors",
"dependencyGroups",
"description",
"iconUrl",
"id",
"language",
"licenseUrl",
"listed",
"minClientVersion",
"packageContent",
"projectUrl",
"published",
"requireLicenseAcceptance",
"summary",
"tags",
"title",
"version"
};
var catalogEntry = new JObject();
JsonUtility.CopyProperties(packageInput.PackageDetails, catalogEntry, copyProperties, skipEmpty: true);
json.Add("catalogEntry", catalogEntry);
// Format package details at creation time, and avoid doing it again later to improve perf.
return JsonLDTokenComparer.Format(json);
}
/// <summary>
/// Find all versions of a package.
/// </summary>
public async Task<ISet<PackageIdentity>> GetPackagesByIdAsync(string packageId)
{
var results = new HashSet<PackageIdentity>();
// Retrieve index
var rootUri = GetIndexUri(_context.Source.BaseURI, packageId);
var rootFile = _context.Source.Get(rootUri);
var json = await rootFile.GetJsonOrNull(_context.Log, _context.Token);
if (json != null)
{
// Get all entries
var packages = await GetPackageDetails(json);
var versions = packages.Select(GetPackageVersion);
foreach (var version in versions)
{
results.Add(new PackageIdentity(packageId, version));
}
}
return results;
}
public Task ApplyOperationsAsync(SleetOperations operations)
{
return OperationsUtility.ApplyAddRemoveAsync(this, operations);
}
public Task PreLoadAsync(SleetOperations operations)
{
// Retrieve the index pages for all ids we will later modify.
return TaskUtils.RunAsync(operations.GetChangedIds().Select(e => new Func<Task>(() => FetchPageAsync(e))));
}
/// <summary>
/// Fetch a root page for a package without loading it up.
/// </summary>
private Task FetchPageAsync(string packageId)
{
var rootUri = GetIndexUri(packageId);
var rootFile = _context.Source.Get(rootUri);
return rootFile.FetchAsync(_context.Log, _context.Token);
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public sealed class InteractiveConsole : ConsoleBase
{
#region FB.ActivateApp() example
private void CallFBActivateApp()
{
FB.ActivateApp();
Callback(new FBResult("Check Insights section for your app in the App Dashboard under \"Mobile App Installs\""));
}
#endregion
#region FB.AppRequest() Friend Selector
public string FriendSelectorTitle = "";
public string FriendSelectorMessage = "Derp";
private string[] FriendFilterTypes = new string[] { "None (default)", "app_users", "app_non_users" };
private int FriendFilterSelection = 0;
private List<string> FriendFilterGroupNames = new List<string>();
private List<string> FriendFilterGroupIDs = new List<string>();
private int NumFriendFilterGroups = 0;
public string FriendSelectorData = "{}";
public string FriendSelectorExcludeIds = "";
public string FriendSelectorMax = "";
private void CallAppRequestAsFriendSelector()
{
// If there's a Max Recipients specified, include it
int? maxRecipients = null;
if (FriendSelectorMax != "")
{
try
{
maxRecipients = Int32.Parse(FriendSelectorMax);
}
catch (Exception e)
{
status = e.Message;
}
}
// include the exclude ids
string[] excludeIds = (FriendSelectorExcludeIds == "") ? null : FriendSelectorExcludeIds.Split(',');
// Filter groups
List<object> FriendSelectorFilters = new List<object>();
if (FriendFilterSelection > 0)
{
FriendSelectorFilters.Add(FriendFilterTypes[FriendFilterSelection]);
}
if (NumFriendFilterGroups > 0)
{
for (int i = 0; i < NumFriendFilterGroups; i++)
{
FriendSelectorFilters.Add(
new FBAppRequestsFilterGroup(
FriendFilterGroupNames[i],
FriendFilterGroupIDs[i].Split(',').ToList()
)
);
}
}
FB.AppRequest(
FriendSelectorMessage,
null,
(FriendSelectorFilters.Count > 0) ? FriendSelectorFilters : null,
excludeIds,
maxRecipients,
FriendSelectorData,
FriendSelectorTitle,
Callback
);
}
#endregion
#region FB.AppRequest() Direct Request
public string DirectRequestTitle = "";
public string DirectRequestMessage = "Herp";
private string DirectRequestTo = "";
private void CallAppRequestAsDirectRequest()
{
if (DirectRequestTo == "")
{
throw new ArgumentException("\"To Comma Ids\" must be specificed", "to");
}
FB.AppRequest(
DirectRequestMessage,
DirectRequestTo.Split(','),
null,
null,
null,
"",
DirectRequestTitle,
Callback
);
}
#endregion
#region FB.Feed() example
public string FeedToId = "";
public string FeedLink = "";
public string FeedLinkName = "";
public string FeedLinkCaption = "";
public string FeedLinkDescription = "";
public string FeedPicture = "";
public string FeedMediaSource = "";
public string FeedActionName = "";
public string FeedActionLink = "";
public string FeedReference = "";
public bool IncludeFeedProperties = false;
private Dictionary<string, string[]> FeedProperties = new Dictionary<string, string[]>();
private void CallFBFeed()
{
Dictionary<string, string[]> feedProperties = null;
if (IncludeFeedProperties)
{
feedProperties = FeedProperties;
}
FB.Feed(
toId: FeedToId,
link: FeedLink,
linkName: FeedLinkName,
linkCaption: FeedLinkCaption,
linkDescription: FeedLinkDescription,
picture: FeedPicture,
mediaSource: FeedMediaSource,
actionName: FeedActionName,
actionLink: FeedActionLink,
reference: FeedReference,
properties: feedProperties,
callback: Callback
);
}
#endregion
#region FB.Canvas.Pay() example
public string PayProduct = "";
private void CallFBPay()
{
FB.Canvas.Pay(PayProduct);
}
#endregion
#region FB.API() example
public string ApiQuery = "";
private void CallFBAPI()
{
FB.API(ApiQuery, Facebook.HttpMethod.GET, Callback);
}
#endregion
#region FB.GetDeepLink() example
private void CallFBGetDeepLink()
{
FB.GetDeepLink(Callback);
}
#endregion
#region FB.AppEvent.LogEvent example
public void CallAppEventLogEvent()
{
FB.AppEvents.LogEvent(
Facebook.FBAppEventName.UnlockedAchievement,
null,
new Dictionary<string,object>() {
{ Facebook.FBAppEventParameterName.Description, "Clicked 'Log AppEvent' button" }
}
);
Callback(new FBResult(
"You may see results showing up at https://www.facebook.com/insights/" +
FB.AppId +
"?section=AppEvents"
)
);
}
#endregion
#region FB.Canvas.SetResolution example
public string Width = "800";
public string Height = "600";
public bool CenterHorizontal = true;
public bool CenterVertical = false;
public string Top = "10";
public string Left = "10";
public void CallCanvasSetResolution()
{
int width;
if (!Int32.TryParse(Width, out width))
{
width = 800;
}
int height;
if (!Int32.TryParse(Height, out height))
{
height = 600;
}
float top;
if (!float.TryParse(Top, out top))
{
top = 0.0f;
}
float left;
if (!float.TryParse(Left, out left))
{
left = 0.0f;
}
if (CenterHorizontal && CenterVertical)
{
FB.Canvas.SetResolution(width, height, false, 0, FBScreen.CenterVertical(), FBScreen.CenterHorizontal());
}
else if (CenterHorizontal)
{
FB.Canvas.SetResolution(width, height, false, 0, FBScreen.Top(top), FBScreen.CenterHorizontal());
}
else if (CenterVertical)
{
FB.Canvas.SetResolution(width, height, false, 0, FBScreen.CenterVertical(), FBScreen.Left(left));
}
else
{
FB.Canvas.SetResolution(width, height, false, 0, FBScreen.Top(top), FBScreen.Left(left));
}
}
#endregion
#region GUI
override protected void Awake()
{
base.Awake();
FeedProperties.Add("key1", new[] { "valueString1" });
FeedProperties.Add("key2", new[] { "valueString2", "http://www.facebook.com" });
}
private void FriendFilterArea() {
#if UNITY_WEBPLAYER
GUILayout.BeginHorizontal();
#endif
GUILayout.Label("Filters:");
FriendFilterSelection =
GUILayout.SelectionGrid(FriendFilterSelection,
FriendFilterTypes,
3,
GUILayout.MinHeight(buttonHeight));
#if UNITY_WEBPLAYER
GUILayout.EndHorizontal();
// Filter groups are not supported on mobile so no need to display
// these buttons if not in web player.
if (NumFriendFilterGroups > 0)
{
GUILayout.BeginVertical();
GUILayout.BeginHorizontal();
GUILayout.Label("Filter group name:", GUILayout.MaxWidth(150));
GUILayout.Label("IDs (comma separated):");
GUILayout.EndHorizontal();
int deleteGroup = -1;
for (int i = 0; i < FriendFilterGroupNames.Count(); i++)
{
GUILayout.BeginHorizontal();
FriendFilterGroupNames[i] = GUILayout.TextField(FriendFilterGroupNames[i], GUILayout.MaxWidth(150));
FriendFilterGroupIDs[i] = GUILayout.TextField(FriendFilterGroupIDs[i]);
if (GUILayout.Button("del", GUILayout.ExpandWidth(false)))
{
deleteGroup = i;
}
GUILayout.EndHorizontal();
}
if (deleteGroup >= 0)
{
NumFriendFilterGroups--;
FriendFilterGroupNames.RemoveAt(deleteGroup);
FriendFilterGroupIDs.RemoveAt(deleteGroup);
}
GUILayout.EndVertical();
}
if (Button("Add filter group..."))
{
FriendFilterGroupNames.Add("");
FriendFilterGroupIDs.Add("");
NumFriendFilterGroups++;
}
#endif
}
void OnGUI()
{
AddCommonHeader ();
if (Button("Publish Install"))
{
CallFBActivateApp();
status = "Install Published";
}
GUI.enabled = FB.IsLoggedIn;
GUILayout.Space(10);
LabelAndTextField("Title (optional): ", ref FriendSelectorTitle);
LabelAndTextField("Message: ", ref FriendSelectorMessage);
LabelAndTextField("Exclude Ids (optional): ", ref FriendSelectorExcludeIds);
FriendFilterArea();
LabelAndTextField("Max Recipients (optional): ", ref FriendSelectorMax);
LabelAndTextField("Data (optional): ", ref FriendSelectorData);
if (Button("Open Friend Selector"))
{
try
{
CallAppRequestAsFriendSelector();
status = "Friend Selector called";
}
catch (Exception e)
{
status = e.Message;
}
}
GUILayout.Space(10);
LabelAndTextField("Title (optional): ", ref DirectRequestTitle);
LabelAndTextField("Message: ", ref DirectRequestMessage);
LabelAndTextField("To Comma Ids: ", ref DirectRequestTo);
if (Button("Open Direct Request"))
{
try
{
CallAppRequestAsDirectRequest();
status = "Direct Request called";
}
catch (Exception e)
{
status = e.Message;
}
}
GUILayout.Space(10);
LabelAndTextField("To Id (optional): ", ref FeedToId);
LabelAndTextField("Link (optional): ", ref FeedLink);
LabelAndTextField("Link Name (optional): ", ref FeedLinkName);
LabelAndTextField("Link Desc (optional): ", ref FeedLinkDescription);
LabelAndTextField("Link Caption (optional): ", ref FeedLinkCaption);
LabelAndTextField("Picture (optional): ", ref FeedPicture);
LabelAndTextField("Media Source (optional): ", ref FeedMediaSource);
LabelAndTextField("Action Name (optional): ", ref FeedActionName);
LabelAndTextField("Action Link (optional): ", ref FeedActionLink);
LabelAndTextField("Reference (optional): ", ref FeedReference);
GUILayout.BeginHorizontal();
GUILayout.Label("Properties (optional)", GUILayout.Width(150));
IncludeFeedProperties = GUILayout.Toggle(IncludeFeedProperties, "Include");
GUILayout.EndHorizontal();
if (Button("Open Feed Dialog"))
{
try
{
CallFBFeed();
status = "Feed dialog called";
}
catch (Exception e)
{
status = e.Message;
}
}
GUILayout.Space(10);
#if UNITY_WEBPLAYER
LabelAndTextField("Product: ", ref PayProduct);
if (Button("Call Pay"))
{
CallFBPay();
}
GUILayout.Space(10);
#endif
LabelAndTextField("API: ", ref ApiQuery);
if (Button("Call API"))
{
status = "API called";
CallFBAPI();
}
GUILayout.Space(10);
if (Button("Take & upload screenshot"))
{
status = "Take screenshot";
StartCoroutine(TakeScreenshot());
}
if (Button("Get Deep Link"))
{
CallFBGetDeepLink();
}
GUI.enabled = true;
if (Button("Log FB App Event"))
{
status = "Logged FB.AppEvent";
CallAppEventLogEvent();
}
#if UNITY_WEBPLAYER
GUI.enabled = FB.IsInitialized;
GUILayout.Space(10);
LabelAndTextField("Game Width: ", ref Width);
LabelAndTextField("Game Height: ", ref Height);
GUILayout.BeginHorizontal();
GUILayout.Label("Center Game:", GUILayout.Width(150));
CenterVertical = GUILayout.Toggle(CenterVertical, "Vertically");
CenterHorizontal = GUILayout.Toggle(CenterHorizontal, "Horizontally");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
LabelAndTextField("or set Padding Top: ", ref Top);
LabelAndTextField("set Padding Left: ", ref Left);
GUILayout.EndHorizontal();
if (Button("Set Resolution"))
{
status = "Set to new Resolution";
CallCanvasSetResolution();
}
GUI.enabled = true;
#endif
GUILayout.Space(10);
GUILayout.EndVertical();
GUILayout.EndScrollView();
if (IsHorizontalLayout())
{
GUILayout.EndVertical();
}
AddCommonFooter();
if (IsHorizontalLayout())
{
GUILayout.EndHorizontal();
}
}
private IEnumerator TakeScreenshot()
{
yield return new WaitForEndOfFrame();
var width = Screen.width;
var height = Screen.height;
var tex = new Texture2D(width, height, TextureFormat.RGB24, false);
// Read screen contents into the texture
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
tex.Apply();
byte[] screenshot = tex.EncodeToPNG();
var wwwForm = new WWWForm();
wwwForm.AddBinaryData("image", screenshot, "InteractiveConsole.png");
wwwForm.AddField("message", "herp derp. I did a thing! Did I do this right?");
FB.API("me/photos", Facebook.HttpMethod.POST, Callback, wwwForm);
}
#endregion
}
| |
/*
Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
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.
*/
// C5 example: bipartite matching 2006-02-04
// Compile with
// csc /r:C5.dll BipartiteMatching.cs
using System;
using System.Diagnostics;
// StreamReader, TextReader
// Encoding
// Regex
using C5;
using SCG = System.Collections.Generic;
namespace BipartiteMatching
{
class MyTest
{
public static void Main(String[] args)
{
BipartiteMatching<int, char> bmi = new BipartiteMatching<int, char>(generateGraph(args));
HashDictionary<int, char> res = new HashDictionary<int, char>();
foreach (Rec<int,char> rec in bmi.Result)
{
res.Add(rec.X1, rec.X2);
}
for (int i = 0; i < args.Length; i++)
{
char c;
if (!res.Find(i,out c))
c='-';
Console.WriteLine(@"""{0}"" -> '{1}'", args[i], c);
}
}
static SCG.IEnumerable<Rec<int, char>> generateGraph(string[] words)
{
int i = 0;
foreach (string s in words)
{
foreach (char c in s)
{
yield return new Rec<int, char>(i, c);
}
i++;
}
}
/// <summary>
/// Implements Hopcroft and Karps algorithm for Maximum bipartite matching.
///
/// Input (to the constructor): the edges of the graph as a collection of pairs
/// of labels of left and right nodes.
///
/// Output (from Result property): a maximum matching as a collection of pairs
/// of labels of left and right nodes.
///
/// The algorithm uses natural equality on the label types to identify nodes.
///
/// </summary>
/// <typeparam name="TLeftLabel"></typeparam>
/// <typeparam name="TRightLabel"></typeparam>
public class BipartiteMatching<TLeftLabel, TRightLabel>
{
LeftNode[] leftNodes;
RightNode[] rightNodes;
class LeftNode
{
public TLeftLabel label;
public RightNode match;
public RightNode[] edges;
public LeftNode(TLeftLabel label, params RightNode[] edges)
{
this.label = label;
this.edges = (RightNode[])edges.Clone();
}
public override string ToString()
{
return string.Format(@"""{0}"" -> '{1}'", label, match);
}
}
class RightNode
{
public TRightLabel label;
public LeftNode match;
public LeftNode backref;
public LeftNode origin;
public RightNode(TRightLabel label)
{
this.label = label;
}
public override string ToString()
{
return string.Format(@"'{0}'", label);
}
}
public BipartiteMatching(SCG.IEnumerable<Rec<TLeftLabel, TRightLabel>> graph)
{
HashDictionary<TRightLabel, RightNode> rdict = new HashDictionary<TRightLabel, RightNode>();
HashDictionary<TLeftLabel, HashSet<RightNode>> edges = new HashDictionary<TLeftLabel, HashSet<RightNode>>();
HashSet<RightNode> newrnodes = new HashSet<RightNode>();
foreach (Rec<TLeftLabel, TRightLabel> edge in graph)
{
RightNode rnode;
if (!rdict.Find(edge.X2, out rnode))
rdict.Add(edge.X2, rnode = new RightNode(edge.X2));
HashSet<RightNode> ledges = newrnodes;
if (!edges.FindOrAdd(edge.X1, ref ledges))
newrnodes = new HashSet<RightNode>();
ledges.Add(rnode);
}
rightNodes = rdict.Values.ToArray();
leftNodes = new LeftNode[edges.Count];
int li = 0;
foreach (KeyValuePair<TLeftLabel, HashSet<RightNode>> les in edges)
{
leftNodes[li++] = new LeftNode(les.Key, les.Value.ToArray());
}
Compute();
}
public SCG.IEnumerable<Rec<TLeftLabel, TRightLabel>> Result
{
get
{
foreach (LeftNode l in leftNodes)
{
if (l.match != null)
{
yield return new Rec<TLeftLabel, TRightLabel>(l.label, l.match.label);
}
}
}
}
HashSet<RightNode> endPoints;
bool foundAugmentingPath;
void Compute()
{
HashSet<LeftNode> unmatchedLeftNodes = new HashSet<LeftNode>();
unmatchedLeftNodes.AddAll(leftNodes);
foundAugmentingPath = true;
Debug.Print("Compute start");
while (foundAugmentingPath)
{
Debug.Print("Start outer");
foundAugmentingPath = false;
endPoints = new HashSet<RightNode>();
foreach (RightNode rightNode in rightNodes)
rightNode.backref = null;
foreach (LeftNode l in unmatchedLeftNodes)
{
Debug.Print("Unmatched: {0}", l);
search(l, l);
}
while (!foundAugmentingPath && endPoints.Count > 0)
{
HashSet<RightNode> oldLayer = endPoints;
endPoints = new HashSet<RightNode>();
foreach (RightNode rb in oldLayer)
search(rb.match, rb.origin);
}
if (endPoints.Count == 0)
return;
//Flip
Debug.Print("Flip");
foreach (RightNode r in endPoints)
{
if (r.match == null && unmatchedLeftNodes.Contains(r.origin))
{
RightNode nextR = r;
LeftNode nextL = null;
while (nextR != null)
{
nextL = nextR.match = nextR.backref;
RightNode rSwap = nextL.match;
nextL.match = nextR;
nextR = rSwap;
}
unmatchedLeftNodes.Remove(nextL);
}
}
}
}
void search(LeftNode l, LeftNode origin)
{
foreach (RightNode r in l.edges)
{
if (r.backref == null)
{
r.backref = l;
r.origin = origin;
endPoints.Add(r);
if (r.match == null)
foundAugmentingPath = true;
//First round should be greedy
if (l == origin)
return;
}
}
}
}
}
}
| |
/*
* SubSonic - http://subsonicproject.com
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*/
using System;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SubSonic
{
/// <summary>
/// Summary description for CalendarControl.
/// </summary>
public class CalendarControl : TextBox
{
private const string DEFAULT_FORMAT = "MM/dd/yyyy";
private const string DEFAULT_INVALID_DATE = "Please enter a valid date.";
private const string DEFAULT_JAVASCRIPT_FORMAT = "%m/%d/%Y %I:%M %p";
private const string DEFAULT_LANGUAGE = "en";
private string displayFormat;
private Image imgCalendar;
private string javaScriptFormat;
private string language;
private DateTime? selectedDate;
private bool showTime = true;
/// <summary>
/// Initializes a new instance of the <see cref="CalendarControl"/> class.
/// </summary>
public CalendarControl()
{
DisplayFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
if(!String.IsNullOrEmpty(DisplayFormat))
{
char splitter = CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator[0];
string[] format = DisplayFormat.Split(new char[] {splitter});
StringBuilder sbFormat = new StringBuilder();
for(int i = 0; i < format.Length; i++)
{
sbFormat.Append("%");
sbFormat.Append(format[i][0]);
if(i + 1 != format.Length)
sbFormat.Append(splitter);
}
JavaScriptFormat = sbFormat.ToString().ToLower() + " %I:%M %p";
}
else
{
DisplayFormat = DEFAULT_FORMAT;
JavaScriptFormat = DEFAULT_JAVASCRIPT_FORMAT;
}
Language = CultureInfo.CurrentCulture.TwoLetterISOLanguageName;
}
/// <summary>
/// Gets the calendar image.
/// </summary>
/// <value>The calendar image.</value>
private Image CalendarImage
{
get
{
if(imgCalendar == null)
{
imgCalendar = new Image();
imgCalendar.ID = "imgCalendar" + ClientID;
imgCalendar.ImageAlign = ImageAlign.AbsMiddle;
imgCalendar.ImageUrl = Page.ClientScript.GetWebResourceUrl(GetType(), "SubSonic.Controls.Calendar.skin.calendar.gif");
imgCalendar.Style.Add("margin-left", "5px");
}
return imgCalendar;
}
}
/// <summary>
/// Gets or sets the display format.
/// </summary>
/// <value>The display format.</value>
[DefaultValue(DEFAULT_FORMAT)]
public string DisplayFormat
{
get { return displayFormat; }
set { displayFormat = value; }
}
/// <summary>
/// Gets or sets the java script format.
/// </summary>
/// <value>The java script format.</value>
[DefaultValue(DEFAULT_JAVASCRIPT_FORMAT)]
public string JavaScriptFormat
{
get { return javaScriptFormat; }
set { javaScriptFormat = value; }
}
/// <summary>
/// Gets or sets the language.
/// </summary>
/// <value>The language.</value>
[DefaultValue(DEFAULT_LANGUAGE)]
public string Language
{
get { return language; }
set { language = value; }
}
/// <summary>
/// Gets or sets a value indicating whether [show time].
/// </summary>
/// <value><c>true</c> if [show time]; otherwise, <c>false</c>.</value>
public bool ShowTime
{
get { return showTime; }
set { showTime = value; }
}
/// <summary>
/// Gets or sets the selected date.
/// </summary>
/// <value>The selected date.</value>
public DateTime? SelectedDate
{
get
{
string selDate = Text.Trim();
if(!String.IsNullOrEmpty(selDate))
{
DateTime parseDate;
if(DateTime.TryParse(selDate, out parseDate))
selectedDate = parseDate;
}
else
selectedDate = null;
return selectedDate;
}
set
{
selectedDate = value;
if(selectedDate.HasValue)
{
DateTime dt = selectedDate.Value;
Text = dt.ToString(DisplayFormat);
}
else
Text = String.Empty;
}
}
/// <summary>
/// Registers client script for generating postback events prior to rendering on the client, if <see cref="P:System.Web.UI.WebControls.TextBox.AutoPostBack"/> is true.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
protected override void OnPreRender(EventArgs e)
{
string csslink = "<link href='" + Page.ClientScript.GetWebResourceUrl(GetType(), "SubSonic.Controls.Calendar.skin.theme.css") + "' rel='stylesheet' type='text/css' />";
Page.Header.Controls.Add(new LiteralControl(csslink));
Page.ClientScript.RegisterClientScriptInclude("CalendarMain", Page.ClientScript.GetWebResourceUrl(GetType(), "SubSonic.Controls.Calendar.calendar.js"));
Page.ClientScript.RegisterClientScriptInclude("CalendarSetup", Page.ClientScript.GetWebResourceUrl(GetType(), "SubSonic.Controls.Calendar.calendar-setup.js"));
const string langPrefix = "SubSonic.Controls.Calendar.lang.calendar-";
if(String.IsNullOrEmpty(Language))
Language = DEFAULT_LANGUAGE;
if(Assembly.GetExecutingAssembly().GetManifestResourceStream(langPrefix + Language + ".js") == null)
Page.ClientScript.RegisterClientScriptInclude("CalendarLanguage", Page.ClientScript.GetWebResourceUrl(GetType(), langPrefix + DEFAULT_LANGUAGE + ".js"));
else
Page.ClientScript.RegisterClientScriptInclude("CalendarLanguage", Page.ClientScript.GetWebResourceUrl(GetType(), langPrefix + Language + ".js"));
base.OnPreRender(e);
}
/// <summary>
/// Renders the <see cref="T:System.Web.UI.WebControls.TextBox"/> control to the specified <see cref="T:System.Web.UI.HtmlTextWriter"/> object.
/// </summary>
/// <param name="writer">The <see cref="T:System.Web.UI.HtmlTextWriter"/> that receives the rendered output.</param>
protected override void Render(HtmlTextWriter writer)
{
if(SelectedDate == DateTime.MinValue)
SelectedDate = DateTime.Now;
writer.WriteLine("<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">");
writer.WriteLine("<tr>");
writer.WriteLine("<td>");
base.Render(writer);
writer.WriteLine("</td><td>");
if(Enabled)
CalendarImage.RenderControl(writer); // render CalendarButton object
writer.WriteLine("</td>");
writer.WriteLine("</tr>");
writer.WriteLine("</table>");
if(Enabled)
{
Page.ClientScript.RegisterStartupScript(typeof(Page), "Calendar" + ClientID,
"<script type=\"text/javascript\">" +
"Calendar.setup( { " +
"inputField: \"" + ClientID + "\", " +
"ifFormat: \"" + JavaScriptFormat + "\", " +
"button: \"" + CalendarImage.ClientID + "\", " +
"date: \"" + SelectedDate + "\", " +
"showsTime: " + (ShowTime ? "true" : "false") + " " +
"} );" +
"</script>");
}
}
}
}
| |
using AIM.Web.ClientApp.Models.EntityModels;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using TrackableEntities;
using TrackableEntities.Client;
namespace AIM.Web.ClientApp.Models.EntityModels
{
[JsonObject(IsReference = true)]
[DataContract(IsReference = true, Namespace = "http://schemas.datacontract.org/2004/07/TrackableEntities.Models")]
public partial class Hour : ModelBase<Hour>, IEquatable<Hour>, ITrackable
{
public Hour()
{
this.Jobs = new ChangeTrackingCollection<Job>();
}
[DataMember]
public int HoursId
{
get { return _HoursId; }
set
{
if (Equals(value, _HoursId)) return;
_HoursId = value;
NotifyPropertyChanged(m => m.HoursId);
}
}
private int _HoursId;
[DataMember]
public int? ApplicantId
{
get { return _ApplicantId; }
set
{
if (Equals(value, _ApplicantId)) return;
_ApplicantId = value;
NotifyPropertyChanged(m => m.ApplicantId);
}
}
private int? _ApplicantId;
[DataMember]
public Nullable<System.TimeSpan> MonOpen
{
get { return _MonOpen; }
set
{
if (Equals(value, _MonOpen)) return;
_MonOpen = value;
NotifyPropertyChanged(m => m.MonOpen);
}
}
private Nullable<System.TimeSpan> _MonOpen;
[DataMember]
public Nullable<System.TimeSpan> MonClose
{
get { return _MonClose; }
set
{
if (Equals(value, _MonClose)) return;
_MonClose = value;
NotifyPropertyChanged(m => m.MonClose);
}
}
private Nullable<System.TimeSpan> _MonClose;
[DataMember]
public Nullable<System.TimeSpan> TueOpen
{
get { return _TueOpen; }
set
{
if (Equals(value, _TueOpen)) return;
_TueOpen = value;
NotifyPropertyChanged(m => m.TueOpen);
}
}
private Nullable<System.TimeSpan> _TueOpen;
[DataMember]
public Nullable<System.TimeSpan> TueClose
{
get { return _TueClose; }
set
{
if (Equals(value, _TueClose)) return;
_TueClose = value;
NotifyPropertyChanged(m => m.TueClose);
}
}
private Nullable<System.TimeSpan> _TueClose;
[DataMember]
public Nullable<System.TimeSpan> WedOpen
{
get { return _WedOpen; }
set
{
if (Equals(value, _WedOpen)) return;
_WedOpen = value;
NotifyPropertyChanged(m => m.WedOpen);
}
}
private Nullable<System.TimeSpan> _WedOpen;
[DataMember]
public Nullable<System.TimeSpan> WedClose
{
get { return _WedClose; }
set
{
if (Equals(value, _WedClose)) return;
_WedClose = value;
NotifyPropertyChanged(m => m.WedClose);
}
}
private Nullable<System.TimeSpan> _WedClose;
[DataMember]
public Nullable<System.TimeSpan> ThursOpen
{
get { return _ThursOpen; }
set
{
if (Equals(value, _ThursOpen)) return;
_ThursOpen = value;
NotifyPropertyChanged(m => m.ThursOpen);
}
}
private Nullable<System.TimeSpan> _ThursOpen;
[DataMember]
public Nullable<System.TimeSpan> ThursClose
{
get { return _ThursClose; }
set
{
if (Equals(value, _ThursClose)) return;
_ThursClose = value;
NotifyPropertyChanged(m => m.ThursClose);
}
}
private Nullable<System.TimeSpan> _ThursClose;
[DataMember]
public Nullable<System.TimeSpan> FriOpen
{
get { return _FriOpen; }
set
{
if (Equals(value, _FriOpen)) return;
_FriOpen = value;
NotifyPropertyChanged(m => m.FriOpen);
}
}
private Nullable<System.TimeSpan> _FriOpen;
[DataMember]
public Nullable<System.TimeSpan> FriClose
{
get { return _FriClose; }
set
{
if (Equals(value, _FriClose)) return;
_FriClose = value;
NotifyPropertyChanged(m => m.FriClose);
}
}
private Nullable<System.TimeSpan> _FriClose;
[DataMember]
public Nullable<System.TimeSpan> SatOpen
{
get { return _SatOpen; }
set
{
if (Equals(value, _SatOpen)) return;
_SatOpen = value;
NotifyPropertyChanged(m => m.SatOpen);
}
}
private Nullable<System.TimeSpan> _SatOpen;
[DataMember]
public Nullable<System.TimeSpan> SatClose
{
get { return _SatClose; }
set
{
if (Equals(value, _SatClose)) return;
_SatClose = value;
NotifyPropertyChanged(m => m.SatClose);
}
}
private Nullable<System.TimeSpan> _SatClose;
[DataMember]
public Nullable<System.TimeSpan> SunOpen
{
get { return _SunOpen; }
set
{
if (Equals(value, _SunOpen)) return;
_SunOpen = value;
NotifyPropertyChanged(m => m.SunOpen);
}
}
private Nullable<System.TimeSpan> _SunOpen;
[DataMember]
public Nullable<System.TimeSpan> SunClose
{
get { return _SunClose; }
set
{
if (Equals(value, _SunClose)) return;
_SunClose = value;
NotifyPropertyChanged(m => m.SunClose);
}
}
private Nullable<System.TimeSpan> _SunClose;
[DataMember]
public Applicant Applicant
{
get { return _Applicant; }
set
{
if (Equals(value, _Applicant)) return;
_Applicant = value;
ApplicantChangeTracker = _Applicant == null ? null
: new ChangeTrackingCollection<Applicant> { _Applicant };
NotifyPropertyChanged(m => m.Applicant);
}
}
private Applicant _Applicant;
private ChangeTrackingCollection<Applicant> ApplicantChangeTracker { get; set; }
[DataMember]
public ChangeTrackingCollection<Job> Jobs
{
get { return _Jobs; }
set
{
if (Equals(value, _Jobs)) return;
_Jobs = value;
NotifyPropertyChanged(m => m.Jobs);
}
}
private ChangeTrackingCollection<Job> _Jobs;
#region Change Tracking
[DataMember]
public TrackingState TrackingState { get; set; }
[DataMember]
public ICollection<string> ModifiedProperties { get; set; }
[JsonProperty, DataMember]
private Guid EntityIdentifier { get; set; }
#pragma warning disable 414
[JsonProperty, DataMember]
private Guid _entityIdentity = default(Guid);
#pragma warning restore 414
bool IEquatable<Hour>.Equals(Hour other)
{
if (EntityIdentifier != default(Guid))
return EntityIdentifier == other.EntityIdentifier;
return false;
}
#endregion Change Tracking
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// 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.Diagnostics;
using Alachisoft.NCache.Common.Interop;
using Microsoft.Win32;
using System.IO;
using System.Threading;
using Alachisoft.NCache.Common.Logger;
#if NETCORE
using System.Runtime.InteropServices;
#endif
using Alachisoft.NCache.Common.Util;
namespace Alachisoft.NCache.Common
{
/// <summary>
/// Utility class to help with common tasks.
/// </summary>
public class AppUtil
{
public const int MAX_BUCKETS = 1000;
static bool isRunningAsWow64 = false;
static string installDir = null;
public readonly static string DeployedAssemblyDir = "deploy" + Path.DirectorySeparatorChar;
public readonly static string serviceLogsPath = "log-files" + Path.DirectorySeparatorChar + "service.log";
static int s_logLevel = 7;
static string javaLibDir = null;
static int _bucketSize;
static string logDir = null;
private static int counter = 0;
static Random random = new Random();
private static NCacheLogger _nCacheEventLogger = null;
static AppUtil()
{
try
{
_bucketSize = (int)Math.Ceiling(((long)int.MinValue * -1) / (double)MAX_BUCKETS);
#if NETCORE
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
#endif
isRunningAsWow64 = Win32.InternalCheckIsWow64();
}
catch (Exception ex)
{
LogEvent("Win32.InternalCheckIsWow64() Error " + ex.Message, EventLogEntryType.Error);
}
installDir = GetInstallDir();
logDir = GetLogDir();
javaLibDir = GetJavaLibDir();
DeployedAssemblyDir = Path.Combine(installDir, DeployedAssemblyDir);
if (ServiceConfiguration.EventLogLevel != null && ServiceConfiguration.EventLogLevel != "")
{
string logLevel = ServiceConfiguration.EventLogLevel.ToLower();
switch (logLevel)
{
case "error":
s_logLevel = 1;
break;
case "warning":
s_logLevel = 3;
break;
case "all":
s_logLevel = 7;
break;
}
}
}
public static bool IsRunningAsWow64
{
get { return isRunningAsWow64; }
}
public static bool IsNew { get { return true; } }
private static string GetInstallDir()
{
string installPath = System.Configuration.ConfigurationSettings.AppSettings["InstallDir"];
if (installPath != null && installPath != string.Empty)
{
return installPath;
}
string path = System.Environment.CurrentDirectory + Path.DirectorySeparatorChar;
try
{
#if NETCORE
if (!System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
{
NCache.Licensing.NetCore.RegistryUtil.RegUtil.LoadRegistry();
if (NCache.Licensing.NetCore.RegistryUtil.RegUtil.LicenseProperties != null ||
NCache.Licensing.NetCore.RegistryUtil.RegUtil.LicenseProperties.Product != null ||
!string.IsNullOrEmpty(NCache.Licensing.NetCore.RegistryUtil.RegUtil.LicenseProperties.Product.InstallDir))
path = NCache.Licensing.NetCore.RegistryUtil.RegUtil.LicenseProperties.Product.InstallDir;
}
else
#endif
path = GetAppSetting("InstallDir");
}
catch (Exception e)
{
//ignore this exception as in case of Nuget client package, nclicense.dll is not shipped with
}
if (path == null || path.Length == 0)
path = System.Environment.CurrentDirectory + Path.DirectorySeparatorChar;
return path;
}
private static string GetLogDir()
{
string installPath = System.Configuration.ConfigurationSettings.AppSettings["NCache.LogPath"];
if (installPath != null && installPath != string.Empty)
{
return installPath;
}
string path = System.Environment.CurrentDirectory + Path.DirectorySeparatorChar;
try
{
#if !NETCORE
path = GetAppSetting("InstallDir");
#endif
}
catch (Exception)
{
#if CLIENT
//ignore this exception as in case of Nuget client package, nclicense.dll is not shipped with
#else
throw;
#endif
}
if (path == null || path.Length == 0)
path = System.Environment.CurrentDirectory + Path.DirectorySeparatorChar;
return path;
}
/// <summary>
/// Reads the value/data pair from the NCache registry key.
/// Automatically caters for wow64/win32.
/// </summary>
/// <param name="key">Name of the value to be read.</param>
/// <returns>Data of the value.</returns>
public static string GetAppSetting(string key)
{
return GetAppSetting("", key);
}
/// <summary>
/// Reads the value/data pair from the NCache registry key.
/// Automatically caters for wow64/win32.
/// </summary>
/// <param name="section">Section from which key is to be read.</param>
/// <param name="key">Name of the value to be read.</param>
/// <returns>Data of the value.</returns>
public static string GetAppSetting(string section, string key)
{
if (!IsRunningAsWow64)
section = RegHelper.ROOT_KEY + section;
object tempVal = RegHelper.GetRegValue(section, key, 0);
if (!(tempVal is string))
{
return Convert.ToString(tempVal);
}
return (string)tempVal;
}
/// <summary>
/// Get decrypted value from section.
/// Automatically caters for wow64/win32.
/// </summary>
/// <param name="section">">Section from which key is to be read.</param>
/// <param name="key">key</param>
/// <returns>value retrieved</returns>
public static string GetDecryptedAppSetting(string section, string key)
{
section = RegHelper.ROOT_KEY + section;
return (string)RegHelper.GetDecryptedRegValue(section, key, 0);
}
/// <summary>
/// Write the value to the NCache registry key.
/// Automatically caters for wow64/win32.
/// </summary>
/// <param name="section">">Section from which key is to be read.</param>
/// <param name="key">Name of the value to be write.</param>
/// <param name="value">New value of key</param>
public static void SetAppSetting(string section, string key, string value, short prodId)
{
section = RegHelper.ROOT_KEY + section;
RegHelper.SetRegValue(section, key, value, prodId);
}
/// <summary>
/// Write the value to the NCache registry key after encrypting it.
/// Automatically caters for wow64/win32.
/// </summary>
/// <param name="section">">Section from which key is to be read.</param>
/// <param name="key">Name of the value to be write.</param>
/// <param name="value">New value of key</param>
public static void SetEncryptedAppSetting(string section, string key, string value)
{
section = RegHelper.ROOT_KEY + section;
RegHelper.SetEncryptedRegValue(section, key, value);
}
/// <summary>
/// Check if the section has preceeding \. If not then append one
/// </summary>
/// <param name="section">Section</param>
/// <returns>Checked and completed section</returns>
private static string CompleteSection(string section)
{
return section.StartsWith("\\") ? section : "\\" + section;
}
/// <summary>
/// Gets the install directory of NCache.
/// Returns null if registry key does not exist.
/// </summary>
public static string InstallDir
{
get { return installDir; }
}
public static string ModulesDir
{
get
{
var bin = Path.Combine(installDir, "bin");
var modules = Path.Combine(bin, "modules");
return modules;
}
}
public static string LogDir
{
get { return logDir; }
}
private static string GetJavaLibDir()
{
return AppUtil.InstallDir + "Java\\Lib\\";
}
public static string JavaLibDir
{
get { return javaLibDir; }
}
/// <summary>
/// Writes an error, warning, information, success audit, or failure audit
/// entry with the given message text to the event log.
/// </summary>
/// <param name="msg">The string to write to the event log.</param>
/// <param name="type">One of the <c>EventLogEntryType</c> values.</param>
public static void LogEvent(string source, string msg, EventLogEntryType type, short category, int eventId)
{
try
{
OSInfo currentOS = OSInfo.Windows;
#if NETCORE
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
currentOS = OSInfo.Linux;
#endif
if (currentOS == OSInfo.Windows)
{
try
{
int level = (int)type;
if ((level & s_logLevel) == level)
{
using (EventLog ncLog = new EventLog("Application"))
{
ncLog.Source = source;
ncLog.WriteEntry(msg, type, eventId);
}
}
}
catch (Exception) { }
}
else // For Linux
{
if (_nCacheEventLogger == null)
{
_nCacheEventLogger = new NCacheLogger();
_nCacheEventLogger.InitializeEventsLogging();
}
_nCacheEventLogger.EventLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss, fff"), source, eventId.ToString(), type.ToString(), msg);
}
}
catch { }
}
/// <summary>
/// Writes an error, warning, information, success audit, or failure audit
/// entry with the given message text to the event log.
/// </summary>
/// <param name="msg">The string to write to the event log.</param>
/// <param name="type">One of the <c>EventLogEntryType</c> values.</param>
public static void LogEvent(string msg, EventLogEntryType type, int eventId)
{
string cacheserver = "NCache";
LogEvent(cacheserver, msg, type, (short)type, eventId);
}
/// <summary>
/// Writes an error, warning, information, success audit, or failure audit
/// entry with the given message text to the event log.
/// </summary>
/// <param name="msg">The string to write to the event log.</param>
/// <param name="type">One of the <c>EventLogEntryType</c> values.</param>
public static void LogEvent(string msg, EventLogEntryType type)
{
string cacheserver = "NCache";
if (type == EventLogEntryType.Information)
LogEvent(cacheserver, msg, type, EventCategories.Information, EventID.GeneralInformation);
else
LogEvent(cacheserver, msg, type, EventCategories.Warning, EventID.GeneralError);
}
/// <summary>
/// Returns lg(Log2) of a number.
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static byte Lg(int val)
{
byte i = 0;
while (val > 1)
{
val >>= 1;
i++;
}
return i;
}
/// <summary>
/// Store all date time values as a difference to this time
/// </summary>
//private static DateTime START_DT = new DateTime(2004, 12, 31).ToUniversalTime();
private static DateTime START_DT = new DateTime(2004, 12, 31, 0, 0, 0, 0, DateTimeKind.Utc);
private static Process s_currentProcess;
/// <summary>
/// Convert DateTime to integer taking 31-12-2004 as base
/// and removing millisecond information
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static int DiffSeconds(DateTime dt)
{
dt = dt.ToUniversalTime();
TimeSpan interval = dt - START_DT;
return (int)interval.TotalSeconds;
}
public static int DiffMilliseconds(DateTime dt)
{
dt = dt.ToUniversalTime();
TimeSpan interval = dt - START_DT;
return (int)interval.Milliseconds;
}
public static long DiffTicks(DateTime dt)
{
dt = dt.ToUniversalTime();
TimeSpan interval = dt - START_DT;
return interval.Ticks;
}
/// <summary>
/// Convert DateTime to integer taking 31-12-2004 as base
/// and removing millisecond information
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static DateTime GetDateTime(int absoluteTime)
{
DateTime dt = new DateTime(START_DT.Ticks, DateTimeKind.Utc);
return dt.AddSeconds(absoluteTime);
}
public static int DiffMinutes(DateTime dt)
{
dt = dt.ToUniversalTime();
TimeSpan interval = dt - START_DT;
return (int)interval.TotalMinutes;
}
/// <summary>
/// Convert DateTime to integer taking 31-12-2004 as base
/// and removing millisecond information
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static DateTime AddMinutes(int minutes)
{
DateTime dt = new DateTime(START_DT.Ticks, DateTimeKind.Utc);
return dt.AddMinutes(minutes);
}
/// <summary>
/// Checks environment to verify if there is 'Any' version of Visual Studio installed.
/// and removing millisecond information
/// </summary>
public static bool IsVSIdeInstalled()
{
return false;
}
/// <summary>
/// Hashcode algorithm returning same hash code for both 32bit and 64 bit apps.
/// Used for data distribution under por/partitioned topologies.
/// </summary>
/// <param name="strArg"></param>
/// <returns></returns>
public static unsafe int GetHashCode(string strArg)
{
strArg = GetLocationAffinityKey(strArg);
fixed (void* str = strArg)
{
char* chPtr = (char*)str;
int num = 0x15051505;
int num2 = num;
int* numPtr = (int*)chPtr;
for (int i = strArg.Length; i > 0; i -= 4)
{
num = (((num << 5) + num) + (num >> 0x1b)) ^ numPtr[0];
if (i <= 2)
{
break;
}
num2 = (((num2 << 5) + num2) + (num2 >> 0x1b)) ^ numPtr[1];
numPtr += 2;
}
return (num + (num2 * 0x5d588b65));
}
}
public static int GetBucketId(string key)
{
int hashCode = GetHashCode(key);
int bucketId = hashCode / _bucketSize;
if (bucketId < 0)
bucketId *= -1;
return bucketId;
}
/// <summary>
/// This method returns the cache key with whom the cache item is to be associated with;
/// provided that this is specified in the provided cache key.
/// </summary>
/// <remarks>
/// The rules for parsing location affinity key are the same as for Keys Hash tags in Redis.
/// They are as follows,
///
/// - IF the key contains a '{' character.
/// - AND IF there is a '}' character to the right of '{'
/// - AND IF there are one or more characters between the first occurrence of '{' and the first
/// occurrence of '}'.
///
/// Then instead of the key, only what is between the first occurrence of '{' and the following
/// first occurrence of '}' is returned.
///
/// Examples,
///
/// - The two keys '{Affinity}.Key001' and '{Affinity}.Key002' will go to the same bucket since the
/// hash code will be generated from 'Affinity' only.
/// - For the key 'Key{}{Affinity}' the whole key will be hashed as usually since the first
/// occurrence of '{' is followed by '}' on the right without characters in the middle.
/// - For the key 'Key{{Affinity}}Part' the substring '{Affinity' will be hashed, because it is the
/// substring between the first occurrence of '{' and the first occurrence of '}' on its right.
/// - For the key 'Key{Affinity}{Part}' the substring 'Affinity' will be hashed, since the algorithm
/// works with the first valid or invalid (without characters inside) match of '{' and '}'.
/// - What follows from the algorithm is that if the key starts with '{}', it is guaranteed to be
/// hashed as a whole.
/// </remarks>
/// <param name="key">The key containing cache key for associated cache item following the
/// '{Affinity}CacheKey', 'CacheKey{Affinity}' or 'Cache{Affinity}Key' pattern.</param>
/// <returns>The associated cache item's cache extracted from the key passed to the method.</returns>
private static string GetLocationAffinityKey(string key)
{
int indexStart = key.IndexOf('{');
int indexEnd = key.IndexOf('}');
if (indexStart != -1 && indexEnd != -1 && (indexStart + 1) < indexEnd)
{
return key.Substring(indexStart + 1, indexEnd - indexStart - 1);
}
return key;
}
public static string GenerateMessageID(string key,string uniqueId)
{
string messageID;
if (key.Contains("{") && key.Contains("}"))
{
messageID = key + uniqueId;
}
else
{
messageID = "{" + key.ToString() + "}" + uniqueId;
}
return messageID;
}
public static DateTime GetRandomNonMaintenanceTime()
{
DateTime start = DateTime.Now.AddSeconds(5);// must not start within 5 seconds to avoid any issues
DateTime end = DateTime.Now.AddHours(24); //new DateTime(start.Year, start.Month, start.Day, 23, 59, 59);
DateTime randomTime = GetRandomDate(start, end);
while (IsInDownTimeRange(randomTime))
{
randomTime = GetRandomDate(DateTime.Now, end);
}
//convert to local time.
TimeZone zone = TimeZone.CurrentTimeZone;
randomTime = zone.ToLocalTime(randomTime);
//make sure that the random time is always a future time.
if (randomTime <= DateTime.Now)
randomTime = DateTime.Now.AddSeconds(10);
return randomTime;
}
public static double GetRandomMonthlyTime(DateTime start, DateTime end)
{
try
{
DateTime randomTime = GetRandomDate(start, end);
//convert to local time.
TimeZone zone = TimeZone.CurrentTimeZone;
randomTime = zone.ToLocalTime(randomTime);
var millisec = (randomTime - DateTime.Now).TotalMilliseconds;
if (millisec < 0 || millisec >= Double.MaxValue)
millisec = 1000 * 60 * 30;
return Convert.ToDouble(millisec);
}
catch (Exception)
{
return 1000 * 60 * 30;
}
}
static bool IsInDownTimeRange(DateTime time)
{
TimeSpan start = new TimeSpan(5, 0, 0); //10 AM time (GMT 5+)
TimeSpan end = new TimeSpan(9, 0, 0); //2 PM time (GMT 5+)
TimeSpan now = time.TimeOfDay;
return now > start && now < end;
}
static DateTime GetRandomDate(DateTime startDate, DateTime endDate)
{
TimeZone zone = TimeZone.CurrentTimeZone;
DateTime gmtEndDate = zone.ToUniversalTime(endDate);
DateTime gmtStartDate = zone.ToUniversalTime(startDate);
TimeSpan timeSpan = gmtEndDate - gmtStartDate;
TimeSpan newSpan = new TimeSpan(0, random.Next(0, (int)timeSpan.TotalMinutes), 0);
DateTime newDate = gmtStartDate + newSpan;
return newDate;
}
public static Process CurrentProcess
{
get
{
if (s_currentProcess == null)
s_currentProcess = Process.GetCurrentProcess();
return s_currentProcess;
}
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using TestExtensions;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
using Xunit;
using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils;
namespace DefaultCluster.Tests
{
using Microsoft.Extensions.DependencyInjection;
public class GrainReferenceCastTests : HostedTestClusterEnsureDefaultStarted
{
private readonly IInternalGrainFactory internalGrainFactory;
public GrainReferenceCastTests(DefaultClusterFixture fixture) : base(fixture)
{
var client = this.HostedCluster.Client;
this.internalGrainFactory = client.ServiceProvider.GetRequiredService<IInternalGrainFactory>();
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastGrainRefCastFromMyType()
{
GrainReference grain = (GrainReference)this.GrainFactory.GetGrain<ISimpleGrain>(random.Next(), SimpleGrain.SimpleGrainNamePrefix);
GrainReference cast = (GrainReference)grain.AsReference<ISimpleGrain>();
Assert.IsAssignableFrom(grain.GetType(), cast);
Assert.IsAssignableFrom<ISimpleGrain>(cast);
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastGrainRefCastFromMyTypePolymorphic()
{
// MultifacetTestGrain implements IMultifacetReader
// MultifacetTestGrain implements IMultifacetWriter
IAddressable grain = this.GrainFactory.GetGrain<IMultifacetTestGrain>(0);
Assert.IsAssignableFrom<IMultifacetWriter>(grain);
Assert.IsAssignableFrom<IMultifacetReader>(grain);
IAddressable cast = grain.AsReference<IMultifacetReader>();
Assert.IsAssignableFrom(grain.GetType(), cast);
Assert.IsAssignableFrom<IMultifacetWriter>(cast);
Assert.IsAssignableFrom<IMultifacetReader>(grain);
IAddressable cast2 = grain.AsReference<IMultifacetWriter>();
Assert.IsAssignableFrom(grain.GetType(), cast2);
Assert.IsAssignableFrom<IMultifacetReader>(cast2);
Assert.IsAssignableFrom<IMultifacetWriter>(grain);
}
// Test case currently fails intermittently
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastMultifacetRWReference()
{
// MultifacetTestGrain implements IMultifacetReader
// MultifacetTestGrain implements IMultifacetWriter
int newValue = 3;
IMultifacetWriter writer = this.GrainFactory.GetGrain<IMultifacetWriter>(1);
// No Wait in this test case
IMultifacetReader reader = writer.AsReference<IMultifacetReader>(); // --> Test case intermittently fails here
// Error: System.InvalidCastException: Grain reference MultifacetGrain.MultifacetWriterFactory+MultifacetWriterReference service interface mismatch: expected interface id=[1947430462] received interface name=[MultifacetGrain.IMultifacetWriter] id=[62435819] in grainRef=[GrainReference:*std/b198f19f]
writer.SetValue(newValue).Wait();
Task<int> readAsync = reader.GetValue();
readAsync.Wait();
int result = readAsync.Result;
Assert.Equal(newValue, result);
}
// Test case currently fails
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastMultifacetRWReferenceWaitForResolve()
{
// MultifacetTestGrain implements IMultifacetReader
// MultifacetTestGrain implements IMultifacetWriter
//Interface Id values for debug:
// IMultifacetWriter = 62435819
// IMultifacetReader = 1947430462
// IMultifacetTestGrain = 222717230 (also compatable with 1947430462 or 62435819)
int newValue = 4;
IMultifacetWriter writer = this.GrainFactory.GetGrain<IMultifacetWriter>(2);
IMultifacetReader reader = writer.AsReference<IMultifacetReader>(); // --> Test case fails here
// Error: System.InvalidCastException: Grain reference MultifacetGrain.MultifacetWriterFactory+MultifacetWriterReference service interface mismatch: expected interface id=[1947430462] received interface name=[MultifacetGrain.IMultifacetWriter] id=[62435819] in grainRef=[GrainReference:*std/8408c2bc]
writer.SetValue(newValue).Wait();
int result = reader.GetValue().Result;
Assert.Equal(newValue, result);
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void ConfirmServiceInterfacesListContents()
{
// GeneratorTestDerivedDerivedGrainReference extends GeneratorTestDerivedGrain2Reference
// GeneratorTestDerivedGrain2Reference extends GeneratorTestGrainReference
Type t1 = typeof(IGeneratorTestDerivedDerivedGrain);
Type t2 = typeof(IGeneratorTestDerivedGrain2);
Type t3 = typeof(IGeneratorTestGrain);
int id1 = GrainInterfaceUtils.GetGrainInterfaceId(t1);
int id2 = GrainInterfaceUtils.GetGrainInterfaceId(t2);
int id3 = GrainInterfaceUtils.GetGrainInterfaceId(t3);
var interfaces = GrainInterfaceUtils.GetRemoteInterfaces(typeof(IGeneratorTestDerivedDerivedGrain));
Assert.NotNull(interfaces);
Assert.Equal(3, interfaces.Keys.Count);
Assert.True(interfaces.Keys.Contains(id1), "id1 is present");
Assert.True(interfaces.Keys.Contains(id2), "id2 is present");
Assert.True(interfaces.Keys.Contains(id3), "id3 is present");
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastCheckExpectedCompatIds2()
{
// GeneratorTestDerivedDerivedGrainReference extends GeneratorTestDerivedGrain2Reference
// GeneratorTestDerivedGrain2Reference extends GeneratorTestGrainReference
Type t1 = typeof(IGeneratorTestDerivedDerivedGrain);
Type t2 = typeof(IGeneratorTestDerivedGrain2);
Type t3 = typeof(IGeneratorTestGrain);
int id1 = GrainInterfaceUtils.GetGrainInterfaceId(t1);
int id2 = GrainInterfaceUtils.GetGrainInterfaceId(t2);
int id3 = GrainInterfaceUtils.GetGrainInterfaceId(t3);
GrainReference grain = (GrainReference) this.GrainFactory.GetGrain<IGeneratorTestDerivedDerivedGrain>(GetRandomGrainId());
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastFailInternalCastFromBadType()
{
var grain = this.GrainFactory.GetGrain<ISimpleGrain>(
random.Next(),
SimpleGrain.SimpleGrainNamePrefix);
// Attempting to cast a grain to a non-grain type should fail.
Assert.Throws<ArgumentException>(() => this.internalGrainFactory.Cast(grain, typeof(bool)));
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastInternalCastFromMyType()
{
var serviceName = typeof(SimpleGrain).FullName;
GrainReference grain = (GrainReference)this.GrainFactory.GetGrain<ISimpleGrain>(random.Next(), SimpleGrain.SimpleGrainNamePrefix);
// This cast should be a no-op, since the interface matches the initial reference's exactly.
IAddressable cast = grain.Cast<ISimpleGrain>();
Assert.Same(grain, cast);
Assert.IsAssignableFrom<ISimpleGrain>(cast);
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastInternalCastUpFromChild()
{
// GeneratorTestDerivedGrain1Reference extends GeneratorTestGrainReference
GrainReference grain = (GrainReference)this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain1>(GetRandomGrainId());
// This cast should be a no-op, since the interface is implemented by the initial reference's interface.
IAddressable cast = grain.Cast<IGeneratorTestGrain>();
Assert.Same(grain, cast);
Assert.IsAssignableFrom<IGeneratorTestGrain>(cast);
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastGrainRefUpCastFromChild()
{
// GeneratorTestDerivedGrain1Reference extends GeneratorTestGrainReference
GrainReference grain = (GrainReference) this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain1>(GetRandomGrainId());
GrainReference cast = (GrainReference) grain.AsReference<IGeneratorTestGrain>();
Assert.IsAssignableFrom<IGeneratorTestDerivedGrain1>(cast);
Assert.IsAssignableFrom<IGeneratorTestGrain>(cast);
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public async Task FailSideCastAfterResolve()
{
// GeneratorTestDerivedGrain1Reference extends GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference extends GeneratorTestGrainReference
IGeneratorTestDerivedGrain1 grain = this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain1>(GetRandomGrainId());
Assert.True(grain.StringIsNullOrEmpty().Result);
// Fails the next line as grain reference is already resolved
IGeneratorTestDerivedGrain2 cast = grain.AsReference<IGeneratorTestDerivedGrain2>();
await Assert.ThrowsAsync<InvalidCastException>(() => cast.StringConcat("a", "b", "c"));
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public async Task FailOperationAfterSideCast()
{
// GeneratorTestDerivedGrain1Reference extends GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference extends GeneratorTestGrainReference
IGeneratorTestDerivedGrain1 grain = this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain1>(GetRandomGrainId());
// Cast works optimistically when the grain reference is not already resolved
IGeneratorTestDerivedGrain2 cast = grain.AsReference<IGeneratorTestDerivedGrain2>();
// Operation fails when grain reference is completely resolved
await Assert.ThrowsAsync<InvalidCastException>(() => cast.StringConcat("a", "b", "c"));
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void FailSideCastAfterContinueWith()
{
Assert.Throws<InvalidCastException>(() =>
{
// GeneratorTestDerivedGrain1Reference extends GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference extends GeneratorTestGrainReference
try
{
IGeneratorTestDerivedGrain1 grain = this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain1>(GetRandomGrainId());
IGeneratorTestDerivedGrain2 cast = null;
Task<bool> av = grain.StringIsNullOrEmpty();
Task<bool> av2 = av.ContinueWith((Task<bool> t) => Assert.True(t.Result)).ContinueWith((_AppDomain) =>
{
cast = grain.AsReference<IGeneratorTestDerivedGrain2>();
}).ContinueWith((_) => cast.StringConcat("a", "b", "c")).ContinueWith((_) => cast.StringIsNullOrEmpty().Result);
Assert.False(av2.Result);
}
catch (AggregateException ae)
{
Exception ex = ae.InnerException;
while (ex is AggregateException) ex = ex.InnerException;
throw ex;
}
Assert.True(false, "Exception should have been raised");
});
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastGrainRefUpCastFromGrandchild()
{
// GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference
GrainReference cast;
GrainReference grain = (GrainReference)this.GrainFactory.GetGrain<IGeneratorTestDerivedDerivedGrain>(GetRandomGrainId());
// Parent
cast = (GrainReference) grain.AsReference<IGeneratorTestDerivedGrain2>();
Assert.IsAssignableFrom<IGeneratorTestDerivedDerivedGrain>(cast);
Assert.IsAssignableFrom<IGeneratorTestDerivedGrain2>(cast);
Assert.IsAssignableFrom<IGeneratorTestGrain>(cast);
// Cross-cast outside the inheritance hierarchy should not work
Assert.False(cast is IGeneratorTestDerivedGrain1);
// Grandparent
cast = (GrainReference) grain.AsReference<IGeneratorTestGrain>();
Assert.IsAssignableFrom<IGeneratorTestDerivedDerivedGrain>(cast);
Assert.IsAssignableFrom<IGeneratorTestGrain>(cast);
// Cross-cast outside the inheritance hierarchy should not work
Assert.False(cast is IGeneratorTestDerivedGrain1);
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastGrainRefUpCastFromDerivedDerivedChild()
{
// GeneratorTestDerivedDerivedGrainReference extends GeneratorTestDerivedGrain2Reference
// GeneratorTestDerivedGrain2Reference extends GeneratorTestGrainReference
GrainReference grain = (GrainReference) this.GrainFactory.GetGrain<IGeneratorTestDerivedDerivedGrain>(GetRandomGrainId());
GrainReference cast = (GrainReference) grain.AsReference<IGeneratorTestDerivedGrain2>();
Assert.IsAssignableFrom<IGeneratorTestDerivedDerivedGrain>(cast);
Assert.IsAssignableFrom<IGeneratorTestDerivedGrain2>(cast);
Assert.IsAssignableFrom<IGeneratorTestGrain>(cast);
Assert.False(cast is IGeneratorTestDerivedGrain1);
}
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastAsyncGrainRefCastFromSelf()
{
IAddressable grain = this.GrainFactory.GetGrain<ISimpleGrain>(random.Next(), SimpleGrain.SimpleGrainNamePrefix); ;
ISimpleGrain cast = grain.AsReference<ISimpleGrain>();
Task<int> successfulCallPromise = cast.GetA();
successfulCallPromise.Wait();
Assert.Equal(TaskStatus.RanToCompletion, successfulCallPromise.Status);
}
// todo: implement white box access
#if TODO
[Fact]
public void CastAsyncGrainRefUpCastFromChild()
{
// GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference
//GrainReference grain = GeneratorTestDerivedGrain1Reference.GetGrain(GetRandomGrainId());
var lookupPromise = GrainReference.CreateGrain(
"",
"GeneratorTestGrain.GeneratorTestDerivedGrain1" );
GrainReference grain = new GrainReference(lookupPromise);
GrainReference cast = (GrainReference) GeneratorTestGrainFactory.Cast(grain);
Assert.NotNull(cast);
//Assert.Same(typeof(IGeneratorTestGrain), cast.GetType());
if (!cast.IsResolved)
{
cast.Wait(100); // Resolve the grain reference
}
Assert.True(cast.IsResolved);
Assert.True(grain.IsResolved);
}
[Fact]
public void CastAsyncGrainRefUpCastFromGrandchild()
{
// GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference
//GrainReference grain = GeneratorTestDerivedDerivedGrainReference.GetGrain(GetRandomGrainId());
var lookupPromise = GrainReference.CreateGrain(
"",
"GeneratorTestGrain.GeneratorTestDerivedDerivedGrain"
);
GrainReference grain = new GrainReference(lookupPromise);
GrainReference cast = (GrainReference) GeneratorTestGrainFactory.Cast(grain);
Assert.NotNull(cast);
//Assert.Same(typeof(IGeneratorTestGrain), cast.GetType());
if (!cast.IsResolved)
{
cast.Wait(100); // Resolve the grain reference
}
Assert.True(cast.IsResolved);
Assert.True(grain.IsResolved);
}
[Fact]
[ExpectedExceptionAttribute(typeof(InvalidCastException))]
public void CastAsyncGrainRefFailSideCastToPeer()
{
// GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference
//GrainReference grain = GeneratorTestDerivedGrain1Reference.GetGrain(GetRandomGrainId());
var lookupPromise = GrainReference.CreateGrain(
"",
"GeneratorTestGrain.GeneratorTestDerivedGrain1"
);
GrainReference grain = new GrainReference(lookupPromise);
GrainReference cast = (GrainReference) GeneratorTestDerivedGrain2Factory.Cast(grain);
if (!cast.IsResolved)
{
cast.Wait(100); // Resolve the grain reference
}
Assert.True(false, "Exception should have been raised");
}
[Fact]
[ExpectedExceptionAttribute(typeof(InvalidCastException))]
public void CastAsyncGrainRefFailDownCastToChild()
{
// GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference
//GrainReference grain = GeneratorTestGrainReference.GetGrain(GetRandomGrainId());
var lookupPromise = GrainReference.CreateGrain(
"",
"GeneratorTestGrain.GeneratorTestGrain");
GrainReference grain = new GrainReference(lookupPromise);
GrainReference cast = (GrainReference) GeneratorTestDerivedGrain1Factory.Cast(grain);
if (!cast.IsResolved)
{
cast.Wait(100); // Resolve the grain reference
}
Assert.True(false, "Exception should have been raised");
}
[Fact]
[ExpectedExceptionAttribute(typeof(InvalidCastException))]
public void CastAsyncGrainRefFailDownCastToGrandchild()
{
// GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference
//GrainReference grain = GeneratorTestGrainReference.GetGrain(GetRandomGrainId());
var lookupPromise = GrainReference.CreateGrain(
"",
"GeneratorTestGrain.GeneratorTestGrain");
GrainReference grain = new GrainReference(lookupPromise);
GrainReference cast = (GrainReference) GeneratorTestDerivedDerivedGrainFactory.Cast(grain);
if (!cast.IsResolved)
{
cast.Wait(100); // Resolve the grain reference
}
Assert.True(false, "Exception should have been raised");
}
#endif
[Fact, TestCategory("BVT"), TestCategory("Cast")]
public void CastCallMethodInheritedFromBaseClass()
{
// GeneratorTestDerivedGrain1Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedGrain2Reference derives from GeneratorTestGrainReference
// GeneratorTestDerivedDerivedGrainReference derives from GeneratorTestDerivedGrain2Reference
Task<bool> isNullStr;
IGeneratorTestDerivedGrain1 grain = this.GrainFactory.GetGrain<IGeneratorTestDerivedGrain1>(GetRandomGrainId());
isNullStr = grain.StringIsNullOrEmpty();
Assert.True(isNullStr.Result, "Value should be null initially");
isNullStr = grain.StringSet("a").ContinueWith((_) => grain.StringIsNullOrEmpty()).Unwrap();
Assert.False(isNullStr.Result, "Value should not be null after SetString(a)");
isNullStr = grain.StringSet(null).ContinueWith((_) => grain.StringIsNullOrEmpty()).Unwrap();
Assert.True(isNullStr.Result, "Value should be null after SetString(null)");
IGeneratorTestGrain cast = grain.AsReference<IGeneratorTestGrain>();
isNullStr = cast.StringSet("b").ContinueWith((_) => grain.StringIsNullOrEmpty()).Unwrap();
Assert.False(isNullStr.Result, "Value should not be null after cast.SetString(b)");
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Network.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
// Parts of this task are based on code from (http://sedodream.codeplex.com). It is used here with permission.
//-----------------------------------------------------------------------
namespace MSBuild.ExtensionPack.Computer
{
using System;
using System.Globalization;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>GetDnsHostName</i> (<b>Required: HostName</b> <b>Output:</b> DnsHostName)</para>
/// <para><i>GetFreePort</i> (<b>Output:</b> Port)</para>
/// <para><i>GetInternalIP</i> (<b>Output:</b> Ip)</para>
/// <para><i>GetRemoteIP</i> (<b>Required: </b>HostName <b>Output:</b> Ip)</para>
/// <para><i>Ping</i> (<b>Required: </b> HostName <b>Optional: </b>Timeout, PingCount <b>Output:</b> Exists)</para>
/// <para><b>Remote Execution Support:</b> NA</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <Target Name="Default">
/// <!-- Get the Machine IP Addresses -->
/// <MSBuild.ExtensionPack.Computer.Network TaskAction="GetInternalIP">
/// <Output TaskParameter="IP" ItemName="TheIP"/>
/// </MSBuild.ExtensionPack.Computer.Network>
/// <Message Text="The IP: %(TheIP.Identity)"/>
/// <!-- Get Remote IP Addresses -->
/// <MSBuild.ExtensionPack.Computer.Network TaskAction="GetRemoteIP" HostName="www.freetodev.com">
/// <Output TaskParameter="IP" ItemName="TheRemoteIP"/>
/// </MSBuild.ExtensionPack.Computer.Network>
/// <Message Text="The Remote IP: %(TheRemoteIP.Identity)"/>
/// <!-- Ping a host -->
/// <MSBuild.ExtensionPack.Computer.Network TaskAction="Ping" HostName="www.freetodev.com">
/// <Output TaskParameter="Exists" PropertyName="DoesExist"/>
/// </MSBuild.ExtensionPack.Computer.Network>
/// <Message Text="Exists: $(DoesExist)"/>
/// <!-- Gets the fully-qualified domain name for a hostname. -->
/// <MSBuild.ExtensionPack.Computer.Network TaskAction="GetDnsHostName" HostName="192.168.0.15">
/// <Output TaskParameter="DnsHostName" PropertyName="HostEntryName" />
/// </MSBuild.ExtensionPack.Computer.Network>
/// <Message Text="Host Entry name: $(HostEntryName)" />
/// <!-- Get free port details -->
/// <MSBuild.ExtensionPack.Computer.Network TaskAction="GetFreePort">
/// <Output TaskParameter="Port" ItemName="FreePort"/>
/// </MSBuild.ExtensionPack.Computer.Network>
/// <Message Text="Free Port Address: %(FreePort.Address)"/>
/// <Message Text="Free Port AddressFamily: %(FreePort.AddressFamily)"/>
/// <Message Text="Free Port Port: %(FreePort.Port)"/>
/// <Message Text="Free Port ToString: %(FreePort.ToString)"/>
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
public class Network : BaseTask
{
private const string GetDnsHostNameTaskAction = "GetDnsHostName";
private const string GetFreePortTaskAction = "GetFreePort";
private const string GetInternalIPTaskAction = "GetInternalIP";
private const string GetRemoteIPTaskAction = "GetRemoteIP";
private const string PingTaskAction = "Ping";
private int pingCount = 5;
private int timeout = 3000;
/// <summary>
/// Sets the HostName / IP address
/// </summary>
public string HostName { get; set; }
/// <summary>
/// Gets whether the Host Exists
/// </summary>
[Output]
public bool Exists { get; private set; }
/// <summary>
/// Sets the number of pings to attempt. Default is 5.
/// </summary>
public int PingCount
{
get { return this.pingCount; }
set { this.pingCount = value; }
}
/// <summary>
/// Sets the timeout in ms for a Ping. Default is 3000
/// </summary>
public int Timeout
{
get { return this.timeout; }
set { this.timeout = value; }
}
/// <summary>
/// Gets the IP's
/// </summary>
[Output]
public ITaskItem[] IP { get; set; }
/// <summary>
/// Gets the free port. ItemSpec is Port. Metadata includes Address, AddressFamily, Port and ToString
/// </summary>
[Output]
public ITaskItem Port { get; set; }
/// <summary>
/// Gets the DnsHostName
/// </summary>
[Output]
public string DnsHostName { get; set; }
/// <summary>
/// Performs the action of this task.
/// </summary>
protected override void InternalExecute()
{
if (!this.TargetingLocalMachine())
{
return;
}
switch (this.TaskAction)
{
case PingTaskAction:
this.Ping();
break;
case GetFreePortTaskAction:
this.GetFreePort();
break;
case GetInternalIPTaskAction:
this.GetInternalIP();
break;
case GetRemoteIPTaskAction:
this.GetRemoteIP();
break;
case GetDnsHostNameTaskAction:
this.GetDnsHostName();
break;
default:
Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
private void GetFreePort()
{
this.LogTaskMessage("Getting Free Port");
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var ipEndPoint = (IPEndPoint)listener.LocalEndpoint;
listener.Stop();
ITaskItem portItem = new TaskItem("Port");
portItem.SetMetadata("Address", ipEndPoint.Address.ToString());
portItem.SetMetadata("AddressFamily", ipEndPoint.AddressFamily.ToString());
portItem.SetMetadata("Port", ipEndPoint.Port.ToString(CultureInfo.InvariantCulture));
portItem.SetMetadata("ToString", ipEndPoint.ToString());
this.Port = portItem;
}
private void GetDnsHostName()
{
if (string.IsNullOrEmpty(this.HostName))
{
Log.LogError("HostName is required");
return;
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Getting host entry name for: {0}", this.HostName));
var hostEntry = Dns.GetHostEntry(this.HostName);
this.DnsHostName = hostEntry.HostName;
}
private void GetRemoteIP()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Get Remote IP for: {0}", this.HostName));
IPAddress[] addresslist = Dns.GetHostAddresses(this.HostName);
this.IP = new ITaskItem[addresslist.Length];
for (int i = 0; i < addresslist.Length; i++)
{
ITaskItem newItem = new TaskItem(addresslist[i].ToString());
this.IP[i] = newItem;
}
}
private void GetInternalIP()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Get Internal IP for: {0}", Environment.MachineName));
string hostName = Dns.GetHostName();
if (string.IsNullOrEmpty(hostName))
{
this.LogTaskWarning("Trying to determine IP addresses but Dns.GetHostName() returned an empty value");
return;
}
IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
if (hostEntry.AddressList == null || hostEntry.AddressList.Length <= 0)
{
this.LogTaskWarning("Trying to determine internal IP addresses but address list is empty");
return;
}
this.IP = new ITaskItem[hostEntry.AddressList.Length];
for (int i = 0; i < hostEntry.AddressList.Length; i++)
{
ITaskItem newItem = new TaskItem(hostEntry.AddressList[i].ToString());
this.IP[i] = newItem;
}
}
private void Ping()
{
const int BufferSize = 32;
const int TimeToLive = 128;
byte[] buffer = new byte[BufferSize];
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = unchecked((byte)i);
}
using (System.Net.NetworkInformation.Ping pinger = new System.Net.NetworkInformation.Ping())
{
PingOptions options = new PingOptions(TimeToLive, false);
for (int i = 0; i < this.PingCount; i++)
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Pinging {0}", this.HostName));
PingReply response = pinger.Send(this.HostName, this.Timeout, buffer, options);
if (response != null && response.Status == IPStatus.Success)
{
this.Exists = true;
return;
}
if (response != null)
{
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Response Status {0}", response.Status));
}
System.Threading.Thread.Sleep(1000);
}
this.Exists = false;
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//==========================================================================
// File: HttpChannelHelper.cs
//
// Summary: Implements helper methods for http client and server channels.
//
//==========================================================================
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Globalization;
namespace System.Runtime.Remoting.Channels.Http
{
internal static class HttpChannelHelper
{
private const String _http = "http://";
#if !FEATURE_PAL
private const String _https = "https://";
#endif
private static char[] s_semicolonSeparator = new char[]{';'};
// Determine if the url starts with "http://"
#if !FEATURE_PAL
// or "https://"
#endif
internal static int StartsWithHttp(String url)
{
int urlLength = url.Length;
if (StringHelper.StartsWithAsciiIgnoreCasePrefixLower(url, _http))
return _http.Length;
#if !FEATURE_PAL
else
if (StringHelper.StartsWithAsciiIgnoreCasePrefixLower(url, _https))
return _https.Length;
#endif
else
return -1;
} // StartsWithHttp
// Used by http channels to implement IChannel::Parse.
// It returns the channel uri and places object uri into out parameter.
internal static String ParseURL(String url, out String objectURI)
{
// Set the out parameters
objectURI = null;
int separator = StartsWithHttp(url);
if (separator == -1)
return null;
// find next slash (after end of scheme)
separator = url.IndexOf('/', separator);
if (-1 == separator)
{
return url; // means that the url is just "tcp://foo:90" or something like that
}
// Extract the channel URI which is the prefix
String channelURI = url.Substring(0, separator);
// Extract the object URI which is the suffix (leave the slash)
objectURI = url.Substring(separator);
InternalRemotingServices.RemotingTrace("HTTPChannel.Parse URI in: " + url);
InternalRemotingServices.RemotingTrace("HTTPChannel.Parse channelURI: " + channelURI);
InternalRemotingServices.RemotingTrace("HTTPChannel.Parse objectURI: " + objectURI);
return channelURI;
} // ParseURL
internal static String GetObjectUriFromRequestUri(String uri)
{
// We assume uri may be in one of the following forms
// http://myhost.com/myobject.rem
#if !FEATURE_PAL
// https://myhost.com/myobject.rem
#endif
// /myobject.rem
// /myobject
// myobject.rem
// In all cases, myobject is considered to be the object URI (.rem might be absent)
int start, end; // range of characters to use
int index;
start = 0;
end = uri.Length;
// first see if uri starts with http://
#if !FEATURE_PAL
// or https://
#endif
// and remove up to next slash if it does
start = StartsWithHttp(uri);
if (start != -1)
{
// remove domain name as well
index = uri.IndexOf('/', start);
if (index != -1)
start = index + 1;
else
start = end; // uri will end up being ""
}
else
{
// remove "/" if this is an absolute path
start = 0;
if (uri[start] == '/')
start++;
}
// remove query string if present ('?' and everything past it)
index = uri.IndexOf('?');
if (index != -1)
end = index;
if (start < end)
return CoreChannel.RemoveApplicationNameFromUri(uri.Substring(start, end - start));
else
return "";
} // GetObjectURIFromRequestURI
internal static void ParseContentType(String contentType,
out String value,
out String charset)
{
charset = null;
if (contentType == null)
{
value = null;
return;
}
String[] parts = contentType.Split(s_semicolonSeparator);
// the actual content-type value is always first
value = parts[0];
// examine name value pairs and look for charset
if (parts.Length > 0)
{
foreach (String part in parts)
{
int index = part.IndexOf('=');
if (index != -1)
{
String key = part.Substring(0, index).Trim();
if (String.Compare(key, "charset", StringComparison.OrdinalIgnoreCase) == 0)
{
if ((index + 1) < part.Length)
{
// we had to make sure there is something after the
// equals sign.
charset = part.Substring(index + 1);
}
else
{
charset = null;
}
return;
}
}
} // foreach
}
} // ParseContentType
internal static String ReplaceChannelUriWithThisString(String url, String channelUri)
{
// NOTE: channelUri is assumed to be scheme://machinename:port
// with NO trailing slash.
String oldChannelUri;
String objUri;
oldChannelUri = HttpChannelHelper.ParseURL(url, out objUri);
InternalRemotingServices.RemotingAssert(oldChannelUri != null, "http url expected.");
InternalRemotingServices.RemotingAssert(objUri != null, "non-null objUri expected.");
return channelUri + objUri;
} // ReplaceChannelUriWithThisString
// returns url with the machine name replaced with the ip address.
internal static String ReplaceMachineNameWithThisString(String url, String newMachineName)
{
String objectUri;
String channelUri = ParseURL(url, out objectUri);
// find bounds of machine name
int index = StartsWithHttp(url);
if (index == -1)
return url;
int colonIndex = channelUri.IndexOf(':', index);
if (colonIndex == -1)
colonIndex = channelUri.Length;
// machine name is between index and up to but not including colonIndex,
// so we will replace those characters with the ip address.
String newUrl = url.Substring(0, index) + newMachineName + url.Substring(colonIndex);
return newUrl;
} // ReplaceMachineNameWithIpAddress
// Decodes a uri while it is in byte array form
internal static void DecodeUriInPlace(byte[] uriBytes, out int length)
{
int percentsFound = 0;
int count = uriBytes.Length;
length = count;
int co = 0;
while (co < count)
{
if (uriBytes[co] == (byte)'%')
{
// determine location to write to (we skip 2 character for each percent)
int writePos = co - (percentsFound * 2);
// decode in place by collapsing bytes "%XY" (actual byte is 16*Dec(X) + Dec(Y))
uriBytes[writePos] = (byte)
(16 * CharacterHexDigitToDecimal(uriBytes[co + 1]) +
CharacterHexDigitToDecimal(uriBytes[co + 2]));
percentsFound++;
length -= 2; // we eliminated 2 characters from the length
co += 3;
}
else
{
if (percentsFound != 0)
{
// we have to copy characters back into place since we will skip some characters
// determine location to write to (we skip 2 character for each percent)
int writePos = co - (percentsFound * 2);
// copy character back into place
uriBytes[writePos] = uriBytes[co];
}
co++;
}
}
} // DecodeUri
// reading helper functions
internal static int CharacterHexDigitToDecimal(byte b)
{
switch ((char)b)
{
case 'F':
case 'f': return 15;
case 'E':
case 'e': return 14;
case 'D':
case 'd': return 13;
case 'C':
case 'c': return 12;
case 'B':
case 'b': return 11;
case 'A':
case 'a': return 10;
default: return b - (byte)'0';
}
} // CharacterHexDigitToDecimal
internal static char DecimalToCharacterHexDigit(int i)
{
switch (i)
{
case 15: return 'F';
case 14: return 'E';
case 13: return 'D';
case 12: return 'C';
case 11: return 'B';
case 10: return 'A';
default: return (char)(i + (byte)'0');
}
} // DecimalToCharacterHexDigit
} // class HttpChannelHelper
internal static class HttpEncodingHelper
{
internal static String EncodeUriAsXLinkHref(String uri)
{
if (uri == null)
return null;
// uses modified encoding rules from xlink href spec for encoding uri's.
// http://www.w3.org/TR/2000/PR-xlink-20001220/#link-locators
byte[] uriBytes = Encoding.UTF8.GetBytes(uri);
StringBuilder sb = new StringBuilder(uri.Length);
// iterate over uri bytes and build up an encoded string.
foreach (byte b in uriBytes)
{
if (!EscapeInXLinkHref(b))
{
sb.Append((char)b);
}
else
{
// the character needs to be encoded as %HH
sb.Append('%');
sb.Append(HttpChannelHelper.DecimalToCharacterHexDigit(b >> 4));
sb.Append(HttpChannelHelper.DecimalToCharacterHexDigit(b & 0xF));
}
}
return sb.ToString();
} // EncodeUriAsXLinkHref
internal static bool EscapeInXLinkHref(byte ch)
{
if ((ch <= 32) || // control characters and space
(ch >= 128) || // non-ascii characters
(ch == (byte)'<') ||
(ch == (byte)'>') ||
(ch == (byte)'"'))
{
return true;
}
return false;
} // EscapeInXLinkHref
internal static String DecodeUri(String uri)
{
byte[] uriBytes = Encoding.UTF8.GetBytes(uri);
int length;
HttpChannelHelper.DecodeUriInPlace(uriBytes, out length);
String newUri = Encoding.UTF8.GetString(uriBytes, 0, length);
return newUri;
} // DecodeUri
} // class HttpEncodingHelper
} // namespace System.Runtime.Remoting.Channels.Http
| |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
namespace AmplifyShaderEditor
{
public enum ToolButtonType
{
Update = 0,
Live,
CleanUnusedNodes,
OpenSourceCode,
//SelectShader,
New,
Open,
Save,
Library,
Options,
Help,
MasterNode,
FocusOnMasterNode,
FocusOnSelection,
ShowInfoWindow
}
public enum ToolbarType
{
File,
Help
}
public class ToolbarMenuTab
{
private Rect m_tabArea;
private GenericMenu m_tabMenu;
public ToolbarMenuTab( float x, float y, float width, float height )
{
m_tabMenu = new GenericMenu();
m_tabArea = new Rect( x, y, width, height );
}
public void ShowMenu()
{
m_tabMenu.DropDown( m_tabArea );
}
public void AddItem( string itemName, GenericMenu.MenuFunction callback )
{
m_tabMenu.AddItem( new GUIContent( itemName ), false, callback );
}
}
[Serializable]
public sealed class ToolsWindow : MenuParent
{
private static readonly Color RightIconsColorOff = new Color( 1f, 1f, 1f, 0.8f );
private static readonly Color LeftIconsColorOff = new Color( 1f, 1f, 1f, 0.5f );
private static readonly Color RightIconsColorOn = new Color( 1f, 1f, 1f, 1.0f );
private static readonly Color LeftIconsColorOn = new Color( 1f, 1f, 1f, 0.8f );
private const float TabY = 9;
private const float TabX = 5;
private const string ShaderFileTitleStr = "Current Shader";
private const string FileToolbarStr = "File";
private const string HelpToolbarStr = "Help";
private const string LiveShaderStr = "Live Shader";
private const string LoadOnSelectionStr = "Load on selection";
private const string CurrentObjectStr = "Current Object: ";
public ToolsMenuButton.ToolButtonPressed ToolButtonPressedEvt;
private GUIStyle m_toolbarButtonStyle;
private GUIStyle m_toggleStyle;
private GUIStyle m_borderStyle;
private ToolsMenuButton[] m_list;
private ToolsMenuButton m_focusOnSelectionButton;
private ToolsMenuButton m_focusOnMasterNodeButton;
private ToolsMenuButton m_showInfoWindowButton;
//Used for collision detection to invalidate inputs on graph area
private Rect m_areaLeft = new Rect( 0, 0, 140, 40 );
private Rect m_areaRight = new Rect( 0, 0, 75, 40 );
private Rect m_boxRect;
private Rect m_borderRect;
private bool m_searchBarVisible = false;
private Rect m_searchBarSize;
private string m_searchBarValue = string.Empty;
private const string SearchBarId = "ASE_SEARCH_BAR";
private List<ParentNode> m_selectedNodes = new List<ParentNode>();
private bool m_refreshList = false;
public const double InactivityRefreshTime = 0.25;
private int m_currentSelected = 0;
// width and height are between [0,1] and represent a percentage of the total screen area
public ToolsWindow( AmplifyShaderEditorWindow parentWindow ) : base( parentWindow, 0, 0, 0, 64, "Tools", MenuAnchor.TOP_LEFT, MenuAutoSize.NONE )
{
m_list = new ToolsMenuButton[ 4 ];
ToolsMenuButton updateButton = new ToolsMenuButton( m_parentWindow, ToolButtonType.Update, 0, 0, -1, -1, IOUtils.UpdateOutdatedGUID, string.Empty, "Create and apply shader to material.", 5 );
updateButton.ToolButtonPressedEvt += OnButtonPressedEvent;
updateButton.AddState( IOUtils.UpdateOFFGUID );
updateButton.AddState( IOUtils.UpdateUpToDatedGUID );
m_list[ ( int ) ToolButtonType.Update ] = updateButton;
ToolsMenuButton liveButton = new ToolsMenuButton( m_parentWindow, ToolButtonType.Live, 0, 0, -1, -1, IOUtils.LiveOffGUID, string.Empty, "Automatically saves shader when canvas is changed.", 50 );
liveButton.ToolButtonPressedEvt += OnButtonPressedEvent;
liveButton.AddState( IOUtils.LiveOnGUID );
liveButton.AddState( IOUtils.LivePendingGUID );
m_list[ ( int ) ToolButtonType.Live ] = liveButton;
ToolsMenuButton cleanUnusedNodesButton = new ToolsMenuButton( m_parentWindow, ToolButtonType.CleanUnusedNodes, 0, 0, -1, -1, IOUtils.CleanupOFFGUID, string.Empty, "Remove all nodes not connected to the master node.", 77 );
cleanUnusedNodesButton.ToolButtonPressedEvt += OnButtonPressedEvent;
cleanUnusedNodesButton.AddState( IOUtils.CleanUpOnGUID );
m_list[ ( int ) ToolButtonType.CleanUnusedNodes ] = cleanUnusedNodesButton;
ToolsMenuButton openSourceCodeButton = new ToolsMenuButton( m_parentWindow, ToolButtonType.OpenSourceCode, 0, 0, -1, -1, IOUtils.OpenSourceCodeOFFGUID, string.Empty, "Open shader file in your default shader editor.", 110, false );
openSourceCodeButton.ToolButtonPressedEvt += OnButtonPressedEvent;
openSourceCodeButton.AddState( IOUtils.OpenSourceCodeONGUID );
m_list[ ( int ) ToolButtonType.OpenSourceCode ] = openSourceCodeButton;
//ToolsMenuButton selectShaderButton = new ToolsMenuButton( eToolButtonType.SelectShader, 0, 0, -1, -1, "UI/Buttons/ShaderSelectOFF", string.Empty, "Select current shader.", 140 );
//selectShaderButton.ToolButtonPressedEvt += OnButtonPressedEvent;
//selectShaderButton.AddState( "UI/Buttons/ShaderSelectON" );
//_list[ ( int ) eToolButtonType.SelectShader ] = selectShaderButton;
m_focusOnMasterNodeButton = new ToolsMenuButton( m_parentWindow, ToolButtonType.FocusOnMasterNode, 0, 0, -1, -1, IOUtils.FocusNodeGUID, string.Empty, "Focus on active master node.", -1, false );
m_focusOnMasterNodeButton.ToolButtonPressedEvt += OnButtonPressedEvent;
m_focusOnSelectionButton = new ToolsMenuButton( m_parentWindow, ToolButtonType.FocusOnSelection, 0, 0, -1, -1, IOUtils.FitViewGUID, string.Empty, "Focus on selection or fit to screen if none selected." );
m_focusOnSelectionButton.ToolButtonPressedEvt += OnButtonPressedEvent;
m_showInfoWindowButton = new ToolsMenuButton( m_parentWindow, ToolButtonType.ShowInfoWindow, 0, 0, -1, -1, IOUtils.ShowInfoWindowGUID, string.Empty, "Open Helper Window." );
m_showInfoWindowButton.ToolButtonPressedEvt += OnButtonPressedEvent;
m_searchBarSize = new Rect( 0, TabY + 4, 110, 60 );
}
void OnShowPortLegend()
{
ParentWindow.ShowPortInfo();
}
override public void Destroy()
{
base.Destroy();
for ( int i = 0; i < m_list.Length; i++ )
{
m_list[ i ].Destroy();
}
m_list = null;
m_selectedNodes.Clear();
m_selectedNodes = null;
m_focusOnMasterNodeButton.Destroy();
m_focusOnMasterNodeButton = null;
m_focusOnSelectionButton.Destroy();
m_focusOnSelectionButton = null;
m_showInfoWindowButton.Destroy();
m_showInfoWindowButton = null;
}
void OnButtonPressedEvent( ToolButtonType type )
{
if ( ToolButtonPressedEvt != null )
ToolButtonPressedEvt( type );
}
public override void Draw( Rect parentPosition, Vector2 mousePosition, int mouseButtonId, bool hasKeyboadFocus )
{
base.Draw( parentPosition, mousePosition, mouseButtonId, hasKeyboadFocus );
Color bufferedColor = GUI.color;
m_areaLeft.x = m_transformedArea.x + TabX;
m_areaRight.x = m_transformedArea.x + m_transformedArea.width - 75 - TabX;
if ( m_toolbarButtonStyle == null )
{
m_toolbarButtonStyle = new GUIStyle( UIUtils.Button );
m_toolbarButtonStyle.fixedWidth = 100;
}
if ( m_toggleStyle == null )
{
m_toggleStyle = UIUtils.Toggle;
}
for ( int i = 0; i < m_list.Length; i++ )
{
GUI.color = m_list[ i ].IsInside( mousePosition ) ? LeftIconsColorOn : LeftIconsColorOff;
m_list[ i ].Draw( TabX + m_transformedArea.x + m_list[ i ].ButtonSpacing, TabY );
}
if ( m_searchBarVisible )
{
if ( Event.current.type == EventType.keyDown )
{
KeyCode keyCode = Event.current.keyCode;
if ( Event.current.shift )
{
if ( keyCode == KeyCode.KeypadEnter ||
keyCode == KeyCode.Return ||
keyCode == KeyCode.F3/*&& GUI.GetNameOfFocusedControl().Equals( SearchBarId )*/ )
SelectPrevious();
}
else
{
if ( keyCode == KeyCode.KeypadEnter ||
keyCode == KeyCode.Return ||
keyCode == KeyCode.F3/*&& GUI.GetNameOfFocusedControl().Equals( SearchBarId )*/ )
SelectNext();
}
}
m_searchBarSize.x = m_transformedArea.x + m_transformedArea.width - 235 - TabX;
EditorGUI.BeginChangeCheck();
{
GUI.SetNextControlName( SearchBarId );
m_searchBarValue = GUI.TextField( m_searchBarSize, m_searchBarValue, UIUtils.ToolbarSearchTextfield );
}
if ( EditorGUI.EndChangeCheck() )
{
m_refreshList = true;
}
m_searchBarSize.x += m_searchBarSize.width;
if ( GUI.Button( m_searchBarSize, string.Empty, UIUtils.ToolbarSearchCancelButton ) )
{
m_searchBarValue = string.Empty;
m_selectedNodes.Clear();
m_currentSelected = -1;
}
if ( Event.current.isKey && Event.current.keyCode == KeyCode.Escape )
{
m_searchBarVisible = false;
m_refreshList = false;
}
if ( m_refreshList && ( m_parentWindow.CurrentInactiveTime > InactivityRefreshTime ) )
{
RefreshList();
}
}
if ( Event.current.control && Event.current.isKey && Event.current.keyCode == KeyCode.F )
{
if ( !m_searchBarVisible )
{
m_searchBarVisible = true;
m_refreshList = false;
}
GUI.FocusControl( SearchBarId );
}
GUI.color = m_focusOnMasterNodeButton.IsInside( mousePosition ) ? RightIconsColorOn : RightIconsColorOff;
m_focusOnMasterNodeButton.Draw( m_transformedArea.x + m_transformedArea.width - 105 - TabX, TabY );
GUI.color = m_focusOnSelectionButton.IsInside( mousePosition ) ? RightIconsColorOn : RightIconsColorOff;
m_focusOnSelectionButton.Draw( m_transformedArea.x + m_transformedArea.width - 70 - TabX, TabY );
GUI.color = m_showInfoWindowButton.IsInside( mousePosition ) ? RightIconsColorOn : RightIconsColorOff;
m_showInfoWindowButton.Draw( m_transformedArea.x + m_transformedArea.width - 35 - TabX, TabY );
GUI.color = bufferedColor;
}
void RefreshList()
{
m_refreshList = false;
m_currentSelected = -1;
m_selectedNodes.Clear();
if ( !string.IsNullOrEmpty( m_searchBarValue ) )
{
List<ParentNode> nodes = m_parentWindow.CurrentGraph.AllNodes;
int count = nodes.Count;
for ( int i = 0; i < count; i++ )
{
if ( nodes[ i ].TitleContent.text.IndexOf( m_searchBarValue , StringComparison.CurrentCultureIgnoreCase ) >= 0 )
{
m_selectedNodes.Add( nodes[ i ] );
}
}
}
}
void SelectNext()
{
if ( m_refreshList )
{
RefreshList();
}
if ( m_selectedNodes.Count > 0 )
{
m_currentSelected = ( m_currentSelected + 1 ) % m_selectedNodes.Count;
m_parentWindow.FocusOnNode( m_selectedNodes[ m_currentSelected ], 1, true );
}
}
void SelectPrevious()
{
if ( m_refreshList )
{
RefreshList();
}
if ( m_selectedNodes.Count > 0 )
{
m_currentSelected = ( m_currentSelected > 1 ) ? ( m_currentSelected - 1 ) : ( m_selectedNodes.Count - 1 );
m_parentWindow.FocusOnNode( m_selectedNodes[ m_currentSelected ], 1, true );
}
}
public void SetStateOnButton( ToolButtonType button, int state, string tooltip )
{
switch ( button )
{
case ToolButtonType.New:
case ToolButtonType.Open:
case ToolButtonType.Save:
case ToolButtonType.Library:
case ToolButtonType.Options:
case ToolButtonType.Help:
case ToolButtonType.MasterNode: break;
case ToolButtonType.OpenSourceCode:
case ToolButtonType.Update:
case ToolButtonType.Live:
case ToolButtonType.CleanUnusedNodes:
//case eToolButtonType.SelectShader:
{
m_list[ ( int ) button ].SetStateOnButton( state, tooltip );
}
break;
case ToolButtonType.FocusOnMasterNode:
{
m_focusOnMasterNodeButton.SetStateOnButton( state, tooltip );
}
break;
case ToolButtonType.FocusOnSelection:
{
m_focusOnSelectionButton.SetStateOnButton( state, tooltip );
}
break;
case ToolButtonType.ShowInfoWindow:
{
m_showInfoWindowButton.SetStateOnButton( state, tooltip );
}
break;
}
}
public void SetStateOnButton( ToolButtonType button, int state )
{
switch ( button )
{
case ToolButtonType.New:
case ToolButtonType.Open:
case ToolButtonType.Save:
case ToolButtonType.Library:
case ToolButtonType.Options:
case ToolButtonType.Help:
case ToolButtonType.MasterNode: break;
case ToolButtonType.OpenSourceCode:
case ToolButtonType.Update:
case ToolButtonType.Live:
case ToolButtonType.CleanUnusedNodes:
//case eToolButtonType.SelectShader:
{
m_list[ ( int ) button ].SetStateOnButton( state );
}
break;
case ToolButtonType.FocusOnMasterNode:
{
m_focusOnMasterNodeButton.SetStateOnButton( state );
}
break;
case ToolButtonType.FocusOnSelection:
{
m_focusOnSelectionButton.SetStateOnButton( state );
}
break;
case ToolButtonType.ShowInfoWindow:
{
m_showInfoWindowButton.SetStateOnButton( state );
}
break;
}
}
public void DrawShaderTitle( MenuParent nodeParametersWindow, MenuParent paletteWindow, float availableCanvasWidth, float graphAreaHeight, string shaderName )
{
float leftAdjust = nodeParametersWindow.IsMaximized ? nodeParametersWindow.RealWidth : 0;
float rightAdjust = paletteWindow.IsMaximized ? 0 : paletteWindow.RealWidth;
m_boxRect = new Rect( leftAdjust + rightAdjust, 0, availableCanvasWidth, 35 );
m_boxRect.x += paletteWindow.IsMaximized ? 0 : -paletteWindow.RealWidth;
m_boxRect.width += nodeParametersWindow.IsMaximized ? 0 : nodeParametersWindow.RealWidth;
m_boxRect.width += paletteWindow.IsMaximized ? 0 : paletteWindow.RealWidth;
m_borderRect = new Rect( m_boxRect );
m_borderRect.height = graphAreaHeight;
if ( m_borderStyle == null )
{
m_borderStyle = ( ParentWindow.CurrentGraph.CurrentMasterNode == null ) ? UIUtils.GetCustomStyle( CustomStyle.ShaderFunctionBorder ) : UIUtils.GetCustomStyle( CustomStyle.ShaderBorder );
}
GUI.Box( m_borderRect, shaderName, m_borderStyle );
GUI.Box( m_boxRect, shaderName, UIUtils.GetCustomStyle( CustomStyle.MainCanvasTitle ) );
}
public override bool IsInside( Vector2 position )
{
if ( !m_isActive )
return false;
return m_boxRect.Contains( position ) || m_areaLeft.Contains( position ) || m_areaRight.Contains( position );
}
public GUIStyle BorderStyle
{
get { return m_borderStyle; }
set { m_borderStyle = value; }
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Services.Connectors.Friends;
using OpenSim.Services.Connectors.Hypergrid;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Server.Base;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using OpenMetaverse;
using log4net;
using Nini.Config;
namespace OpenSim.Services.HypergridService
{
/// <summary>
/// This service is for HG1.5 only, to make up for the fact that clients don't
/// keep any private information in themselves, and that their 'home service'
/// needs to do it for them.
/// Once we have better clients, this shouldn't be needed.
/// </summary>
public class UserAgentService : UserAgentServiceBase, IUserAgentService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
// This will need to go into a DB table
//static Dictionary<UUID, TravelingAgentInfo> m_Database = new Dictionary<UUID, TravelingAgentInfo>();
static bool m_Initialized = false;
protected static IGridUserService m_GridUserService;
protected static IGridService m_GridService;
protected static GatekeeperServiceConnector m_GatekeeperConnector;
protected static IGatekeeperService m_GatekeeperService;
protected static IFriendsService m_FriendsService;
protected static IPresenceService m_PresenceService;
protected static IUserAccountService m_UserAccountService;
protected static IFriendsSimConnector m_FriendsLocalSimConnector; // standalone, points to HGFriendsModule
protected static FriendsSimConnector m_FriendsSimConnector; // grid
protected static string m_GridName;
protected static int m_LevelOutsideContacts;
protected static bool m_ShowDetails;
protected static bool m_BypassClientVerification;
private static Dictionary<int, bool> m_ForeignTripsAllowed = new Dictionary<int, bool>();
private static Dictionary<int, List<string>> m_TripsAllowedExceptions = new Dictionary<int, List<string>>();
private static Dictionary<int, List<string>> m_TripsDisallowedExceptions = new Dictionary<int, List<string>>();
public UserAgentService(IConfigSource config) : this(config, null)
{
}
public UserAgentService(IConfigSource config, IFriendsSimConnector friendsConnector)
: base(config)
{
// Let's set this always, because we don't know the sequence
// of instantiations
if (friendsConnector != null)
m_FriendsLocalSimConnector = friendsConnector;
if (!m_Initialized)
{
m_Initialized = true;
m_log.DebugFormat("[HOME USERS SECURITY]: Starting...");
m_FriendsSimConnector = new FriendsSimConnector();
IConfig serverConfig = config.Configs["UserAgentService"];
if (serverConfig == null)
throw new Exception(String.Format("No section UserAgentService in config file"));
string gridService = serverConfig.GetString("GridService", String.Empty);
string gridUserService = serverConfig.GetString("GridUserService", String.Empty);
string gatekeeperService = serverConfig.GetString("GatekeeperService", String.Empty);
string friendsService = serverConfig.GetString("FriendsService", String.Empty);
string presenceService = serverConfig.GetString("PresenceService", String.Empty);
string userAccountService = serverConfig.GetString("UserAccountService", String.Empty);
m_BypassClientVerification = serverConfig.GetBoolean("BypassClientVerification", false);
if (gridService == string.Empty || gridUserService == string.Empty || gatekeeperService == string.Empty)
throw new Exception(String.Format("Incomplete specifications, UserAgent Service cannot function."));
Object[] args = new Object[] { config };
m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args);
m_GridUserService = ServerUtils.LoadPlugin<IGridUserService>(gridUserService, args);
m_GatekeeperConnector = new GatekeeperServiceConnector();
m_GatekeeperService = ServerUtils.LoadPlugin<IGatekeeperService>(gatekeeperService, args);
m_FriendsService = ServerUtils.LoadPlugin<IFriendsService>(friendsService, args);
m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(presenceService, args);
m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(userAccountService, args);
m_LevelOutsideContacts = serverConfig.GetInt("LevelOutsideContacts", 0);
m_ShowDetails = serverConfig.GetBoolean("ShowUserDetailsInHGProfile", true);
LoadTripPermissionsFromConfig(serverConfig, "ForeignTripsAllowed");
LoadDomainExceptionsFromConfig(serverConfig, "AllowExcept", m_TripsAllowedExceptions);
LoadDomainExceptionsFromConfig(serverConfig, "DisallowExcept", m_TripsDisallowedExceptions);
m_GridName = Util.GetConfigVarFromSections<string>(config, "GatekeeperURI",
new string[] { "Startup", "Hypergrid", "UserAgentService" }, String.Empty);
if (string.IsNullOrEmpty(m_GridName)) // Legacy. Remove soon.
{
m_GridName = serverConfig.GetString("ExternalName", string.Empty);
if (m_GridName == string.Empty)
{
serverConfig = config.Configs["GatekeeperService"];
m_GridName = serverConfig.GetString("ExternalName", string.Empty);
}
}
if (!m_GridName.EndsWith("/"))
m_GridName = m_GridName + "/";
// Finally some cleanup
m_Database.DeleteOld();
}
}
protected void LoadTripPermissionsFromConfig(IConfig config, string variable)
{
foreach (string keyName in config.GetKeys())
{
if (keyName.StartsWith(variable + "_Level_"))
{
int level = 0;
if (Int32.TryParse(keyName.Replace(variable + "_Level_", ""), out level))
m_ForeignTripsAllowed.Add(level, config.GetBoolean(keyName, true));
}
}
}
protected void LoadDomainExceptionsFromConfig(IConfig config, string variable, Dictionary<int, List<string>> exceptions)
{
foreach (string keyName in config.GetKeys())
{
if (keyName.StartsWith(variable + "_Level_"))
{
int level = 0;
if (Int32.TryParse(keyName.Replace(variable + "_Level_", ""), out level) && !exceptions.ContainsKey(level))
{
exceptions.Add(level, new List<string>());
string value = config.GetString(keyName, string.Empty);
string[] parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in parts)
exceptions[level].Add(s.Trim());
}
}
}
}
public GridRegion GetHomeRegion(UUID userID, out Vector3 position, out Vector3 lookAt)
{
position = new Vector3(128, 128, 0); lookAt = Vector3.UnitY;
m_log.DebugFormat("[USER AGENT SERVICE]: Request to get home region of user {0}", userID);
GridRegion home = null;
GridUserInfo uinfo = m_GridUserService.GetGridUserInfo(userID.ToString());
if (uinfo != null)
{
if (uinfo.HomeRegionID != UUID.Zero)
{
home = m_GridService.GetRegionByUUID(UUID.Zero, uinfo.HomeRegionID);
position = uinfo.HomePosition;
lookAt = uinfo.HomeLookAt;
}
if (home == null)
{
List<GridRegion> defs = m_GridService.GetDefaultRegions(UUID.Zero);
if (defs != null && defs.Count > 0)
home = defs[0];
}
}
return home;
}
public bool LoginAgentToGrid(GridRegion source, AgentCircuitData agentCircuit, GridRegion gatekeeper, GridRegion finalDestination, bool fromLogin, out string reason)
{
m_log.DebugFormat("[USER AGENT SERVICE]: Request to login user {0} {1} (@{2}) to grid {3}",
agentCircuit.firstname, agentCircuit.lastname, (fromLogin ? agentCircuit.IPAddress : "stored IP"), gatekeeper.ServerURI);
string gridName = gatekeeper.ServerURI;
UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, agentCircuit.AgentID);
if (account == null)
{
m_log.WarnFormat("[USER AGENT SERVICE]: Someone attempted to lauch a foreign user from here {0} {1}", agentCircuit.firstname, agentCircuit.lastname);
reason = "Forbidden to launch your agents from here";
return false;
}
// Is this user allowed to go there?
if (m_GridName != gridName)
{
if (m_ForeignTripsAllowed.ContainsKey(account.UserLevel))
{
bool allowed = m_ForeignTripsAllowed[account.UserLevel];
if (m_ForeignTripsAllowed[account.UserLevel] && IsException(gridName, account.UserLevel, m_TripsAllowedExceptions))
allowed = false;
if (!m_ForeignTripsAllowed[account.UserLevel] && IsException(gridName, account.UserLevel, m_TripsDisallowedExceptions))
allowed = true;
if (!allowed)
{
reason = "Your world does not allow you to visit the destination";
m_log.InfoFormat("[USER AGENT SERVICE]: Agents not permitted to visit {0}. Refusing service.", gridName);
return false;
}
}
}
// Take the IP address + port of the gatekeeper (reg) plus the info of finalDestination
GridRegion region = new GridRegion(gatekeeper);
region.ServerURI = gatekeeper.ServerURI;
region.ExternalHostName = finalDestination.ExternalHostName;
region.InternalEndPoint = finalDestination.InternalEndPoint;
region.RegionName = finalDestination.RegionName;
region.RegionID = finalDestination.RegionID;
region.RegionLocX = finalDestination.RegionLocX;
region.RegionLocY = finalDestination.RegionLocY;
// Generate a new service session
agentCircuit.ServiceSessionID = region.ServerURI + ";" + UUID.Random();
TravelingAgentInfo old = null;
TravelingAgentInfo travel = CreateTravelInfo(agentCircuit, region, fromLogin, out old);
bool success = false;
string myExternalIP = string.Empty;
m_log.DebugFormat("[USER AGENT SERVICE]: this grid: {0}, desired grid: {1}, desired region: {2}", m_GridName, gridName, region.RegionID);
if (m_GridName == gridName)
{
success = m_GatekeeperService.LoginAgent(source, agentCircuit, finalDestination, out reason);
}
else
{
success = m_GatekeeperConnector.CreateAgent(source, region, agentCircuit, (uint)Constants.TeleportFlags.ViaLogin, out myExternalIP, out reason);
}
if (!success)
{
m_log.DebugFormat("[USER AGENT SERVICE]: Unable to login user {0} {1} to grid {2}, reason: {3}",
agentCircuit.firstname, agentCircuit.lastname, region.ServerURI, reason);
if (old != null)
StoreTravelInfo(old);
else
m_Database.Delete(agentCircuit.SessionID);
return false;
}
// Everything is ok
// Update the perceived IP Address of our grid
m_log.DebugFormat("[USER AGENT SERVICE]: Gatekeeper sees me as {0}", myExternalIP);
travel.MyIpAddress = myExternalIP;
StoreTravelInfo(travel);
return true;
}
public bool LoginAgentToGrid(GridRegion source, AgentCircuitData agentCircuit, GridRegion gatekeeper, GridRegion finalDestination, out string reason)
{
reason = string.Empty;
return LoginAgentToGrid(source, agentCircuit, gatekeeper, finalDestination, false, out reason);
}
TravelingAgentInfo CreateTravelInfo(AgentCircuitData agentCircuit, GridRegion region, bool fromLogin, out TravelingAgentInfo existing)
{
HGTravelingData hgt = m_Database.Get(agentCircuit.SessionID);
existing = null;
if (hgt != null)
{
// Very important! Override whatever this agent comes with.
// UserAgentService always sets the IP for every new agent
// with the original IP address.
existing = new TravelingAgentInfo(hgt);
agentCircuit.IPAddress = existing.ClientIPAddress;
}
TravelingAgentInfo travel = new TravelingAgentInfo(existing);
travel.SessionID = agentCircuit.SessionID;
travel.UserID = agentCircuit.AgentID;
travel.GridExternalName = region.ServerURI;
travel.ServiceToken = agentCircuit.ServiceSessionID;
if (fromLogin)
travel.ClientIPAddress = agentCircuit.IPAddress;
StoreTravelInfo(travel);
return travel;
}
public void LogoutAgent(UUID userID, UUID sessionID)
{
m_log.DebugFormat("[USER AGENT SERVICE]: User {0} logged out", userID);
m_Database.Delete(sessionID);
GridUserInfo guinfo = m_GridUserService.GetGridUserInfo(userID.ToString());
if (guinfo != null)
m_GridUserService.LoggedOut(userID.ToString(), sessionID, guinfo.LastRegionID, guinfo.LastPosition, guinfo.LastLookAt);
}
// We need to prevent foreign users with the same UUID as a local user
public bool IsAgentComingHome(UUID sessionID, string thisGridExternalName)
{
HGTravelingData hgt = m_Database.Get(sessionID);
if (hgt == null)
return false;
TravelingAgentInfo travel = new TravelingAgentInfo(hgt);
return travel.GridExternalName.ToLower() == thisGridExternalName.ToLower();
}
public bool VerifyClient(UUID sessionID, string reportedIP)
{
if (m_BypassClientVerification)
return true;
m_log.DebugFormat("[USER AGENT SERVICE]: Verifying Client session {0} with reported IP {1}.",
sessionID, reportedIP);
HGTravelingData hgt = m_Database.Get(sessionID);
if (hgt == null)
return false;
TravelingAgentInfo travel = new TravelingAgentInfo(hgt);
bool result = travel.ClientIPAddress == reportedIP || travel.MyIpAddress == reportedIP; // NATed
m_log.DebugFormat("[USER AGENT SERVICE]: Comparing {0} with login IP {1} and MyIP {1}; result is {3}",
reportedIP, travel.ClientIPAddress, travel.MyIpAddress, result);
return result;
}
public bool VerifyAgent(UUID sessionID, string token)
{
HGTravelingData hgt = m_Database.Get(sessionID);
if (hgt == null)
{
m_log.DebugFormat("[USER AGENT SERVICE]: Token verification for session {0}: no such session", sessionID);
return false;
}
TravelingAgentInfo travel = new TravelingAgentInfo(hgt);
m_log.DebugFormat("[USER AGENT SERVICE]: Verifying agent token {0} against {1}", token, travel.ServiceToken);
return travel.ServiceToken == token;
}
[Obsolete]
public List<UUID> StatusNotification(List<string> friends, UUID foreignUserID, bool online)
{
if (m_FriendsService == null || m_PresenceService == null)
{
m_log.WarnFormat("[USER AGENT SERVICE]: Unable to perform status notifications because friends or presence services are missing");
return new List<UUID>();
}
List<UUID> localFriendsOnline = new List<UUID>();
m_log.DebugFormat("[USER AGENT SERVICE]: Status notification: foreign user {0} wants to notify {1} local friends", foreignUserID, friends.Count);
// First, let's double check that the reported friends are, indeed, friends of that user
// And let's check that the secret matches
List<string> usersToBeNotified = new List<string>();
foreach (string uui in friends)
{
UUID localUserID;
string secret = string.Empty, tmp = string.Empty;
if (Util.ParseUniversalUserIdentifier(uui, out localUserID, out tmp, out tmp, out tmp, out secret))
{
FriendInfo[] friendInfos = m_FriendsService.GetFriends(localUserID);
foreach (FriendInfo finfo in friendInfos)
{
if (finfo.Friend.StartsWith(foreignUserID.ToString()) && finfo.Friend.EndsWith(secret))
{
// great!
usersToBeNotified.Add(localUserID.ToString());
}
}
}
}
// Now, let's send the notifications
m_log.DebugFormat("[USER AGENT SERVICE]: Status notification: user has {0} local friends", usersToBeNotified.Count);
// First, let's send notifications to local users who are online in the home grid
PresenceInfo[] friendSessions = m_PresenceService.GetAgents(usersToBeNotified.ToArray());
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = null;
foreach (PresenceInfo pinfo in friendSessions)
if (pinfo.RegionID != UUID.Zero) // let's guard against traveling agents
{
friendSession = pinfo;
break;
}
if (friendSession != null)
{
ForwardStatusNotificationToSim(friendSession.RegionID, foreignUserID, friendSession.UserID, online);
usersToBeNotified.Remove(friendSession.UserID.ToString());
UUID id;
if (UUID.TryParse(friendSession.UserID, out id))
localFriendsOnline.Add(id);
}
}
//// Lastly, let's notify the rest who may be online somewhere else
//foreach (string user in usersToBeNotified)
//{
// UUID id = new UUID(user);
// if (m_Database.ContainsKey(id) && m_Database[id].GridExternalName != m_GridName)
// {
// string url = m_Database[id].GridExternalName;
// // forward
// m_log.WarnFormat("[USER AGENT SERVICE]: User {0} is visiting {1}. HG Status notifications still not implemented.", user, url);
// }
//}
// and finally, let's send the online friends
if (online)
{
return localFriendsOnline;
}
else
return new List<UUID>();
}
[Obsolete]
protected void ForwardStatusNotificationToSim(UUID regionID, UUID foreignUserID, string user, bool online)
{
UUID userID;
if (UUID.TryParse(user, out userID))
{
if (m_FriendsLocalSimConnector != null)
{
m_log.DebugFormat("[USER AGENT SERVICE]: Local Notify, user {0} is {1}", foreignUserID, (online ? "online" : "offline"));
m_FriendsLocalSimConnector.StatusNotify(foreignUserID, userID, online);
}
else
{
GridRegion region = m_GridService.GetRegionByUUID(UUID.Zero /* !!! */, regionID);
if (region != null)
{
m_log.DebugFormat("[USER AGENT SERVICE]: Remote Notify to region {0}, user {1} is {2}", region.RegionName, foreignUserID, (online ? "online" : "offline"));
m_FriendsSimConnector.StatusNotify(region, foreignUserID, userID.ToString(), online);
}
}
}
}
public List<UUID> GetOnlineFriends(UUID foreignUserID, List<string> friends)
{
List<UUID> online = new List<UUID>();
if (m_FriendsService == null || m_PresenceService == null)
{
m_log.WarnFormat("[USER AGENT SERVICE]: Unable to get online friends because friends or presence services are missing");
return online;
}
m_log.DebugFormat("[USER AGENT SERVICE]: Foreign user {0} wants to know status of {1} local friends", foreignUserID, friends.Count);
// First, let's double check that the reported friends are, indeed, friends of that user
// And let's check that the secret matches and the rights
List<string> usersToBeNotified = new List<string>();
foreach (string uui in friends)
{
UUID localUserID;
string secret = string.Empty, tmp = string.Empty;
if (Util.ParseUniversalUserIdentifier(uui, out localUserID, out tmp, out tmp, out tmp, out secret))
{
FriendInfo[] friendInfos = m_FriendsService.GetFriends(localUserID);
foreach (FriendInfo finfo in friendInfos)
{
if (finfo.Friend.StartsWith(foreignUserID.ToString()) && finfo.Friend.EndsWith(secret) &&
(finfo.TheirFlags & (int)FriendRights.CanSeeOnline) != 0 && (finfo.TheirFlags != -1))
{
// great!
usersToBeNotified.Add(localUserID.ToString());
}
}
}
}
// Now, let's find out their status
m_log.DebugFormat("[USER AGENT SERVICE]: GetOnlineFriends: user has {0} local friends with status rights", usersToBeNotified.Count);
// First, let's send notifications to local users who are online in the home grid
PresenceInfo[] friendSessions = m_PresenceService.GetAgents(usersToBeNotified.ToArray());
if (friendSessions != null && friendSessions.Length > 0)
{
foreach (PresenceInfo pi in friendSessions)
{
UUID presenceID;
if (UUID.TryParse(pi.UserID, out presenceID))
online.Add(presenceID);
}
}
return online;
}
public Dictionary<string, object> GetUserInfo(UUID userID)
{
Dictionary<string, object> info = new Dictionary<string, object>();
if (m_UserAccountService == null)
{
m_log.WarnFormat("[USER AGENT SERVICE]: Unable to get user flags because user account service is missing");
info["result"] = "fail";
info["message"] = "UserAccountService is missing!";
return info;
}
UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero /*!!!*/, userID);
if (account != null)
{
info.Add("user_firstname", account.FirstName);
info.Add("user_lastname", account.LastName);
info.Add("result", "success");
if (m_ShowDetails)
{
info.Add("user_flags", account.UserFlags);
info.Add("user_created", account.Created);
info.Add("user_title", account.UserTitle);
}
else
{
info.Add("user_flags", 0);
info.Add("user_created", 0);
info.Add("user_title", string.Empty);
}
}
return info;
}
public Dictionary<string, object> GetServerURLs(UUID userID)
{
if (m_UserAccountService == null)
{
m_log.WarnFormat("[USER AGENT SERVICE]: Unable to get server URLs because user account service is missing");
return new Dictionary<string, object>();
}
UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero /*!!!*/, userID);
if (account != null)
return account.ServiceURLs;
return new Dictionary<string, object>();
}
public string LocateUser(UUID userID)
{
HGTravelingData[] hgts = m_Database.GetSessions(userID);
if (hgts == null)
return string.Empty;
foreach (HGTravelingData t in hgts)
if (t.Data.ContainsKey("GridExternalName") && !m_GridName.Equals(t.Data["GridExternalName"]))
return t.Data["GridExternalName"];
return string.Empty;
}
public string GetUUI(UUID userID, UUID targetUserID)
{
// Let's see if it's a local user
UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, targetUserID);
if (account != null)
return targetUserID.ToString() + ";" + m_GridName + ";" + account.FirstName + " " + account.LastName ;
// Let's try the list of friends
FriendInfo[] friends = m_FriendsService.GetFriends(userID);
if (friends != null && friends.Length > 0)
{
foreach (FriendInfo f in friends)
if (f.Friend.StartsWith(targetUserID.ToString()))
{
// Let's remove the secret
UUID id; string tmp = string.Empty, secret = string.Empty;
if (Util.ParseUniversalUserIdentifier(f.Friend, out id, out tmp, out tmp, out tmp, out secret))
return f.Friend.Replace(secret, "0");
}
}
return string.Empty;
}
public UUID GetUUID(String first, String last)
{
// Let's see if it's a local user
UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, first, last);
if (account != null)
{
// check user level
if (account.UserLevel < m_LevelOutsideContacts)
return UUID.Zero;
else
return account.PrincipalID;
}
else
return UUID.Zero;
}
#region Misc
private bool IsException(string dest, int level, Dictionary<int, List<string>> exceptions)
{
if (!exceptions.ContainsKey(level))
return false;
bool exception = false;
if (exceptions[level].Count > 0) // we have exceptions
{
string destination = dest;
if (!destination.EndsWith("/"))
destination += "/";
if (exceptions[level].Find(delegate(string s)
{
if (!s.EndsWith("/"))
s += "/";
return s == destination;
}) != null)
exception = true;
}
return exception;
}
private void StoreTravelInfo(TravelingAgentInfo travel)
{
if (travel == null)
return;
HGTravelingData hgt = new HGTravelingData();
hgt.SessionID = travel.SessionID;
hgt.UserID = travel.UserID;
hgt.Data = new Dictionary<string, string>();
hgt.Data["GridExternalName"] = travel.GridExternalName;
hgt.Data["ServiceToken"] = travel.ServiceToken;
hgt.Data["ClientIPAddress"] = travel.ClientIPAddress;
hgt.Data["MyIPAddress"] = travel.MyIpAddress;
m_Database.Store(hgt);
}
#endregion
}
class TravelingAgentInfo
{
public UUID SessionID;
public UUID UserID;
public string GridExternalName = string.Empty;
public string ServiceToken = string.Empty;
public string ClientIPAddress = string.Empty; // as seen from this user agent service
public string MyIpAddress = string.Empty; // the user agent service's external IP, as seen from the next gatekeeper
public TravelingAgentInfo(HGTravelingData t)
{
if (t.Data != null)
{
SessionID = new UUID(t.SessionID);
UserID = new UUID(t.UserID);
GridExternalName = t.Data["GridExternalName"];
ServiceToken = t.Data["ServiceToken"];
ClientIPAddress = t.Data["ClientIPAddress"];
MyIpAddress = t.Data["MyIPAddress"];
}
}
public TravelingAgentInfo(TravelingAgentInfo old)
{
if (old != null)
{
SessionID = old.SessionID;
UserID = old.UserID;
GridExternalName = old.GridExternalName;
ServiceToken = old.ServiceToken;
ClientIPAddress = old.ClientIPAddress;
MyIpAddress = old.MyIpAddress;
}
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using CrystalDecisions.Shared;
namespace WebApplication2
{
/// <summary>
/// Summary description for frmResourcesInfo.
/// </summary>
public partial class frmProjectsIndT: System.Web.UI.Page
{
/*SqlConnection epsDbConn=new SqlConnection("Server=cp2693-a\\eps1;database=eps1;"+
"uid=tauheed;pwd=tauheed;");*/
private static string strURL =
System.Configuration.ConfigurationSettings.AppSettings["local_url"];
private static string strDB =
System.Configuration.ConfigurationSettings.AppSettings["local_db"];
protected System.Web.UI.WebControls.Label lblContents2;
public SqlConnection epsDbConn=new SqlConnection(strDB);
protected void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
loadForm();
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand);
}
#endregion
private void loadForm()
{
DataGrid1.Columns[1].HeaderText=Session["EventName"].ToString();
if (!IsPostBack)
{
lblMgr.Text=Session["MgrName"].ToString();
lblService.Text="Service: " + Session["ServiceName"].ToString();
lblLocation.Text="Location: " + Session["LocationName"].ToString();
loadData();
}
}
private void loadData()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText="wms_RetrieveProjectsInd";
cmd.Parameters.Add ("@PeopleId",SqlDbType.Int);
cmd.Parameters["@PeopleId"].Value=Int32.Parse(Session["PeopleId"].ToString());
cmd.Parameters.Add ("@PSEventId",SqlDbType.Int);
cmd.Parameters["@PSEventId"].Value=Int32.Parse(Session["PSEventsId"].ToString());
cmd.Parameters.Add ("@OrgLocId",SqlDbType.Int);
cmd.Parameters["@OrgLocId"].Value=Int32.Parse(Session["OrgLocId"].ToString());
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"Projects");
if (ds.Tables["Projects"].Rows.Count == 0)
{
DataGrid1.Visible=false;
lblContents1.ForeColor=System.Drawing.Color.Maroon;
lblContents1.Text="Note: There are no "
+ Session["PJName"].ToString()
+ " activated by the event '"
+ Session["EventName"].ToString()
+ "' that are currently active at this location."
+ " You may identify a new such "
+ Session["PJNameS"].ToString()
+ " at this or some other location by clicking on "
+ " the appropriate button below.";
}
else if (ds.Tables["Projects"].Rows.Count == 1)
{
Session["CT"]="frmProjectsIndT";
Session["ProjectId"]=ds.Tables["Mgr"].Rows[0][0].ToString();
Session["ProjName"]=ds.Tables["Mgr"].Rows[0][1].ToString();
Response.Redirect (strURL + "frmTasks.aspx?");
}
else
{
lblContents1.Text="There are more than one "
+ Session["PJName"].ToString()
+ " of type '"
+ Session["EventName"].ToString()
+ "' that are currently active at this location."
+ " You may now charge time against the appropriate "
+ Session["PJNameS"].ToString()
+ " on this list. ";
Session["ds"] = ds;
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
//refreshGrid();
}
}
protected void btnOK_Click(object sender, System.EventArgs e)
{
Exit();
}
/*private void refreshGrid()
{
foreach (DataGridItem i in DataGrid1.Items)
{
Button cb = (Button)(i.Cells[3].FindControl("btnProj"));
Button cba = (Button)(i.Cells[3].FindControl("btnDeActivate"));
Button cbb = (Button)(i.Cells[4].FindControl("btnCancel"));
cb.Text = Session["PJNameS"].ToString();
if (i.Cells[6].Text == "Planned")
{
cba.Text = "Activate";
cba.CommandName = "Activate";
}
if (i.Cells[5].Text.StartsWith("&") == false)
{
cba.Text = "Remove";
cba.CommandName = "Remove";
cbb.Visible=false;
}
}
}*/
private void Exit()
{
Response.Redirect (strURL + Session["CPI"].ToString() + ".aspx?");
}
private void rpts()
{
Session["cRG"]="frmProjectsIndT";
Response.Redirect (strURL + "frmReportGen.aspx?");
}
private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
Session["ProjName"]=e.Item.Cells[1].Text;
if (e.CommandName == "Timetable")
{
ParameterFields paramFields = new ParameterFields();
ParameterField paramField = new ParameterField();
ParameterDiscreteValue discreteval = new ParameterDiscreteValue();
paramField.ParameterFieldName = "ProjectsId";
discreteval.Value = e.Item.Cells[0].Text;
paramField.CurrentValues.Add (discreteval);
paramFields.Add (paramField);
Session["ReportParameters"] = paramFields;
Session["ReportName"] = "rptTTInd.rpt";
rpts();
}
else if (e.CommandName == "Status")
{
Session["CUpdProject"]="frmProjectsIndT";
Session["ProjectId"]=e.Item.Cells[0].Text;
Response.Redirect (strURL + "frmUpdProject.aspx?");
}
else if (e.CommandName == "Tasks")
{
Session["CT"]="frmProjectsIndT";
Session["ProjectId"]=e.Item.Cells[0].Text;
Session["ProjName"]=e.Item.Cells[1].Text;
Response.Redirect (strURL + "frmTasks.aspx?");
}
/*else if (e.CommandName == "Pay")
{
Session["CPay"]="frmProjectsIndT";
//Session["PSEventsId"] = e.Item.Cells[0].Text;- Session["PSEventsId"]
//Session["EventName"]Session["EventName"]
Session["ProcProcuresId"] = e.Item.Cells[0].Text;
//Session["CPay"]="frmContracts";
//Session["LocName"]=e.Item.Cells[1].Text; - Session["LocationName"]
Session["TaskName"]=e.Item.Cells[2].Text;
Session["SupplierName"]=e.Item.Cells[4].Text;
Session["GSName"]=e.Item.Cells[5].Text;
Response.Redirect (strURL + "frmPayments.aspx?");
}*/
else if (e.CommandName == "Remove")
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText="wms_DeleteProjectPeople";
cmd.Parameters.Add ("@Id", SqlDbType.Int);
cmd.Parameters["@Id"].Value=Int32.Parse(e.Item.Cells[5].Text);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
loadData();
}
else if (e.CommandName == "Cancel")
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText="wms_UpdateProjectC";
cmd.Parameters.Add ("@Id", SqlDbType.Int);
cmd.Parameters["@Id"].Value=Int32.Parse(e.Item.Cells[0].Text);
cmd.Parameters.Add ("@Status", SqlDbType.Int);
cmd.Parameters["@Status"].Value=3;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
loadData();
}
else if (e.CommandName == "DeActivate")
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText="wms_UpdateProjectC";
cmd.Parameters.Add ("@Id", SqlDbType.Int);
cmd.Parameters["@Id"].Value=Int32.Parse(e.Item.Cells[0].Text);
cmd.Parameters.Add ("@Status", SqlDbType.Int);
cmd.Parameters["@Status"].Value=2;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
loadData();
}
else if (e.CommandName == "Activate")
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText="wms_UpdateProjectC";
cmd.Parameters.Add ("@Id", SqlDbType.Int);
cmd.Parameters["@Id"].Value=Int32.Parse(e.Item.Cells[0].Text);
cmd.Parameters.Add ("@Status", SqlDbType.Int);
cmd.Parameters["@Status"].Value=1;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
loadData();
}
}
private void btnAdd_Click(object sender, System.EventArgs e)
{
Session["CPSel"]="frmProjectsIndT";
Response.Redirect (strURL + "frmProjectsSel.aspx?");
}
private void btnAddOth_Click(object sender, System.EventArgs e)
{
Session["CPSel"]="frmProjectsIndT";
Response.Redirect (strURL + "frmProjectsSelO.aspx?");
}
private void btnAddNew_Click(object sender, System.EventArgs e)
{
Session["CUpdProject"]="frmProjectsIndT";
Response.Redirect (strURL + "frmUpdProject.aspx?");
}
}
}
| |
namespace KabMan.Forms
{
partial class DeviceManagerForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule1 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule();
this.CManager = new KabMan.Controls.C_ControlManagerForm();
this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
this.CCondition2 = new DevExpress.XtraEditors.CheckEdit();
this.CCondition1 = new DevExpress.XtraEditors.CheckEdit();
this.CName = new DevExpress.XtraEditors.TextEdit();
this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem();
this.CManagerValidator = new DevExpress.XtraEditors.DXErrorProvider.DXValidationProvider(this.components);
this.CManager.LayoutPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
this.layoutControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.CCondition2.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CCondition1.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CName.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CManagerValidator)).BeginInit();
this.SuspendLayout();
//
// CManager
//
this.CManager.DeleteProcedure = null;
this.CManager.Dock = System.Windows.Forms.DockStyle.Fill;
this.CManager.InsertProcedure = null;
this.CManager.IsCancel = true;
this.CManager.IsEdit = false;
this.CManager.IsNew = true;
//
// CManager.layoutControlPanel
//
this.CManager.LayoutPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.CManager.LayoutPanel.Controls.Add(this.layoutControl1);
this.CManager.LayoutPanel.Location = new System.Drawing.Point(0, 0);
this.CManager.LayoutPanel.MinimumSize = new System.Drawing.Size(400, 20);
this.CManager.LayoutPanel.Name = "layoutControlPanel";
this.CManager.LayoutPanel.Size = new System.Drawing.Size(412, 64);
this.CManager.LayoutPanel.TabIndex = 6;
this.CManager.Location = new System.Drawing.Point(0, 0);
this.CManager.MinimumSize = new System.Drawing.Size(400, 460);
this.CManager.Name = "CManager";
this.CManager.SelectParameters = null;
this.CManager.Size = new System.Drawing.Size(412, 466);
this.CManager.TabIndex = 0;
this.CManager.UpdateProcedure = null;
this.CManager.Load += new System.EventHandler(this.CManager_Load);
//
// layoutControl1
//
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true;
this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true;
this.layoutControl1.Controls.Add(this.CCondition2);
this.layoutControl1.Controls.Add(this.CCondition1);
this.layoutControl1.Controls.Add(this.CName);
this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.layoutControl1.Location = new System.Drawing.Point(0, 0);
this.layoutControl1.Name = "layoutControl1";
this.layoutControl1.Root = this.layoutControlGroup1;
this.layoutControl1.Size = new System.Drawing.Size(412, 64);
this.layoutControl1.TabIndex = 0;
this.layoutControl1.Text = "layoutControl1";
//
// CCondition2
//
this.CCondition2.Location = new System.Drawing.Point(212, 38);
this.CCondition2.Name = "CCondition2";
this.CCondition2.Properties.Caption = "Condition 2";
this.CCondition2.Size = new System.Drawing.Size(194, 19);
this.CCondition2.StyleController = this.layoutControl1;
this.CCondition2.TabIndex = 6;
//
// CCondition1
//
this.CCondition1.Location = new System.Drawing.Point(7, 38);
this.CCondition1.Name = "CCondition1";
this.CCondition1.Properties.Caption = "Condition 1";
this.CCondition1.Size = new System.Drawing.Size(194, 19);
this.CCondition1.StyleController = this.layoutControl1;
this.CCondition1.TabIndex = 5;
//
// CName
//
this.CName.Location = new System.Drawing.Point(39, 7);
this.CName.Name = "CName";
this.CName.Size = new System.Drawing.Size(367, 20);
this.CName.StyleController = this.layoutControl1;
this.CName.TabIndex = 4;
conditionValidationRule1.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank;
conditionValidationRule1.ErrorText = "This value is not valid";
conditionValidationRule1.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning;
this.CManagerValidator.SetValidationRule(this.CName, conditionValidationRule1);
//
// layoutControlGroup1
//
this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1";
this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem1,
this.layoutControlItem2,
this.layoutControlItem3});
this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0);
this.layoutControlGroup1.Name = "layoutControlGroup1";
this.layoutControlGroup1.Size = new System.Drawing.Size(412, 64);
this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0);
this.layoutControlGroup1.Text = "layoutControlGroup1";
this.layoutControlGroup1.TextVisible = false;
//
// layoutControlItem1
//
this.layoutControlItem1.Control = this.CName;
this.layoutControlItem1.CustomizationFormText = "Name";
this.layoutControlItem1.Location = new System.Drawing.Point(0, 0);
this.layoutControlItem1.Name = "layoutControlItem1";
this.layoutControlItem1.Size = new System.Drawing.Size(410, 31);
this.layoutControlItem1.Text = "Name";
this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem1.TextSize = new System.Drawing.Size(27, 13);
//
// layoutControlItem2
//
this.layoutControlItem2.Control = this.CCondition1;
this.layoutControlItem2.CustomizationFormText = "layoutControlItem2";
this.layoutControlItem2.Location = new System.Drawing.Point(0, 31);
this.layoutControlItem2.Name = "layoutControlItem2";
this.layoutControlItem2.Size = new System.Drawing.Size(205, 31);
this.layoutControlItem2.Text = "layoutControlItem2";
this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem2.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem2.TextToControlDistance = 0;
this.layoutControlItem2.TextVisible = false;
//
// layoutControlItem3
//
this.layoutControlItem3.Control = this.CCondition2;
this.layoutControlItem3.CustomizationFormText = "layoutControlItem3";
this.layoutControlItem3.Location = new System.Drawing.Point(205, 31);
this.layoutControlItem3.Name = "layoutControlItem3";
this.layoutControlItem3.Size = new System.Drawing.Size(205, 31);
this.layoutControlItem3.Text = "layoutControlItem3";
this.layoutControlItem3.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem3.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem3.TextToControlDistance = 0;
this.layoutControlItem3.TextVisible = false;
//
// DeviceManagerForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(412, 466);
this.Controls.Add(this.CManager);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(420, 500);
this.Name = "DeviceManagerForm";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Devices";
this.CManager.LayoutPanel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
this.layoutControl1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.CCondition2.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CCondition1.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CName.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CManagerValidator)).EndInit();
this.ResumeLayout(false);
}
#endregion
private KabMan.Controls.C_ControlManagerForm CManager;
private DevExpress.XtraLayout.LayoutControl layoutControl1;
private DevExpress.XtraEditors.CheckEdit CCondition2;
private DevExpress.XtraEditors.CheckEdit CCondition1;
private DevExpress.XtraEditors.TextEdit CName;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3;
private DevExpress.XtraEditors.DXErrorProvider.DXValidationProvider CManagerValidator;
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Net.Sockets
{
public enum IOControlCode : long
{
AbsorbRouterAlert = (long)2550136837,
AddMulticastGroupOnInterface = (long)2550136842,
AddressListChange = (long)671088663,
AddressListQuery = (long)1207959574,
AddressListSort = (long)3355443225,
AssociateHandle = (long)2281701377,
AsyncIO = (long)2147772029,
BindToInterface = (long)2550136840,
DataToRead = (long)1074030207,
DeleteMulticastGroupFromInterface = (long)2550136843,
EnableCircularQueuing = (long)671088642,
Flush = (long)671088644,
GetBroadcastAddress = (long)1207959557,
GetExtensionFunctionPointer = (long)3355443206,
GetGroupQos = (long)3355443208,
GetQos = (long)3355443207,
KeepAliveValues = (long)2550136836,
LimitBroadcasts = (long)2550136839,
MulticastInterface = (long)2550136841,
MulticastScope = (long)2281701386,
MultipointLoopback = (long)2281701385,
NamespaceChange = (long)2281701401,
NonBlockingIO = (long)2147772030,
OobDataRead = (long)1074033415,
QueryTargetPnpHandle = (long)1207959576,
ReceiveAll = (long)2550136833,
ReceiveAllIgmpMulticast = (long)2550136835,
ReceiveAllMulticast = (long)2550136834,
RoutingInterfaceChange = (long)2281701397,
RoutingInterfaceQuery = (long)3355443220,
SetGroupQos = (long)2281701388,
SetQos = (long)2281701387,
TranslateHandle = (long)3355443213,
UnicastInterface = (long)2550136838,
}
public partial struct IPPacketInformation
{
private object _dummy;
public System.Net.IPAddress Address { get { throw null; } }
public int Interface { get { throw null; } }
public override bool Equals(object comparand) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Net.Sockets.IPPacketInformation packetInformation1, System.Net.Sockets.IPPacketInformation packetInformation2) { throw null; }
public static bool operator !=(System.Net.Sockets.IPPacketInformation packetInformation1, System.Net.Sockets.IPPacketInformation packetInformation2) { throw null; }
}
public enum IPProtectionLevel
{
EdgeRestricted = 20,
Restricted = 30,
Unrestricted = 10,
Unspecified = -1,
}
public partial class IPv6MulticastOption
{
public IPv6MulticastOption(System.Net.IPAddress group) { }
public IPv6MulticastOption(System.Net.IPAddress group, long ifindex) { }
public System.Net.IPAddress Group { get { throw null; } set { } }
public long InterfaceIndex { get { throw null; } set { } }
}
public partial class LingerOption
{
public LingerOption(bool enable, int seconds) { }
public bool Enabled { get { throw null; } set { } }
public int LingerTime { get { throw null; } set { } }
}
public partial class MulticastOption
{
public MulticastOption(System.Net.IPAddress group) { }
public MulticastOption(System.Net.IPAddress group, int interfaceIndex) { }
public MulticastOption(System.Net.IPAddress group, System.Net.IPAddress mcint) { }
public System.Net.IPAddress Group { get { throw null; } set { } }
public int InterfaceIndex { get { throw null; } set { } }
public System.Net.IPAddress LocalAddress { get { throw null; } set { } }
}
public partial class NetworkStream : System.IO.Stream
{
public NetworkStream(System.Net.Sockets.Socket socket) { }
public NetworkStream(System.Net.Sockets.Socket socket, bool ownsSocket) { }
public NetworkStream(System.Net.Sockets.Socket socket, System.IO.FileAccess access) { }
public NetworkStream(System.Net.Sockets.Socket socket, System.IO.FileAccess access, bool ownsSocket) { }
public override bool CanRead { get { throw null; } }
public override bool CanSeek { get { throw null; } }
public override bool CanTimeout { get { throw null; } }
public override bool CanWrite { get { throw null; } }
public virtual bool DataAvailable { get { throw null; } }
public override long Length { get { throw null; } }
public override long Position { get { throw null; } set { } }
protected bool Readable { get { throw null; } set { } }
public override int ReadTimeout { get { throw null; } set { } }
protected Socket Socket { get { throw null; } }
protected bool Writeable { get { throw null; } set { } }
public override int WriteTimeout { get { throw null; } set { } }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { throw null; }
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { throw null; }
public void Close(int timeout) { }
protected override void Dispose(bool disposing) { }
~NetworkStream() { }
public override int EndRead(IAsyncResult asyncResult) { throw null; }
public override void EndWrite(IAsyncResult asyncResult) { }
public override void Flush() { }
public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
public override int Read(byte[] buffer, int offset, int size) { throw null; }
public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int size, System.Threading.CancellationToken cancellationToken) { throw null; }
public override long Seek(long offset, System.IO.SeekOrigin origin) { throw null; }
public override void SetLength(long value) { }
public override void Write(byte[] buffer, int offset, int size) { }
public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int size, System.Threading.CancellationToken cancellationToken) { throw null; }
}
public enum ProtocolFamily
{
AppleTalk = 16,
Atm = 22,
Banyan = 21,
Ccitt = 10,
Chaos = 5,
Cluster = 24,
DataKit = 9,
DataLink = 13,
DecNet = 12,
Ecma = 8,
FireFox = 19,
HyperChannel = 15,
Ieee12844 = 25,
ImpLink = 3,
InterNetwork = 2,
InterNetworkV6 = 23,
Ipx = 6,
Irda = 26,
Iso = 7,
Lat = 14,
Max = 29,
NetBios = 17,
NetworkDesigners = 28,
NS = 6,
Osi = 7,
Pup = 4,
Sna = 11,
Unix = 1,
Unknown = -1,
Unspecified = 0,
VoiceView = 18,
}
public enum ProtocolType
{
Ggp = 3,
Icmp = 1,
IcmpV6 = 58,
Idp = 22,
Igmp = 2,
IP = 0,
IPSecAuthenticationHeader = 51,
IPSecEncapsulatingSecurityPayload = 50,
IPv4 = 4,
IPv6 = 41,
IPv6DestinationOptions = 60,
IPv6FragmentHeader = 44,
IPv6HopByHopOptions = 0,
IPv6NoNextHeader = 59,
IPv6RoutingHeader = 43,
Ipx = 1000,
ND = 77,
Pup = 12,
Raw = 255,
Spx = 1256,
SpxII = 1257,
Tcp = 6,
Udp = 17,
Unknown = -1,
Unspecified = 0,
}
public enum SelectMode
{
SelectError = 2,
SelectRead = 0,
SelectWrite = 1,
}
public partial class SendPacketsElement
{
public SendPacketsElement(byte[] buffer) { }
public SendPacketsElement(byte[] buffer, int offset, int count) { }
public SendPacketsElement(byte[] buffer, int offset, int count, bool endOfPacket) { }
public SendPacketsElement(string filepath) { }
public SendPacketsElement(string filepath, int offset, int count) { }
public SendPacketsElement(string filepath, int offset, int count, bool endOfPacket) { }
public byte[] Buffer { get { throw null; } }
public int Count { get { throw null; } }
public bool EndOfPacket { get { throw null; } }
public string FilePath { get { throw null; } }
public int Offset { get { throw null; } }
}
public partial class Socket : System.IDisposable
{
public Socket(System.Net.Sockets.AddressFamily addressFamily, System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType) { }
public Socket(System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType) { }
public Socket(SocketInformation socketInformation) { }
public System.Net.Sockets.AddressFamily AddressFamily { get { throw null; } }
public int Available { get { throw null; } }
public bool Blocking { get { throw null; } set { } }
public bool Connected { get { throw null; } }
public bool DontFragment { get { throw null; } set { } }
public bool DualMode { get { throw null; } set { } }
public bool EnableBroadcast { get { throw null; } set { } }
public bool ExclusiveAddressUse { get { throw null; } set { } }
public IntPtr Handle { get { throw null; } }
public bool IsBound { get { throw null; } }
public System.Net.Sockets.LingerOption LingerState { get { throw null; } set { } }
public System.Net.EndPoint LocalEndPoint { get { throw null; } }
public bool MulticastLoopback { get { throw null; } set { } }
public bool NoDelay { get { throw null; } set { } }
public static bool OSSupportsIPv4 { get { throw null; } }
public static bool OSSupportsIPv6 { get { throw null; } }
public System.Net.Sockets.ProtocolType ProtocolType { get { throw null; } }
public int ReceiveBufferSize { get { throw null; } set { } }
public int ReceiveTimeout { get { throw null; } set { } }
public System.Net.EndPoint RemoteEndPoint { get { throw null; } }
public int SendBufferSize { get { throw null; } set { } }
public int SendTimeout { get { throw null; } set { } }
public System.Net.Sockets.SocketType SocketType { get { throw null; } }
[Obsolete("SupportsIPv4 is obsoleted for this type, please use OSSupportsIPv4 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static bool SupportsIPv4 { get { throw null; } }
[Obsolete("SupportsIPv6 is obsoleted for this type, please use OSSupportsIPv6 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static bool SupportsIPv6 { get { throw null; } }
public short Ttl { get { throw null; } set { } }
public bool UseOnlyOverlappedIO { get { throw null; } set { } }
public System.Net.Sockets.Socket Accept() { throw null; }
public bool AcceptAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; }
public IAsyncResult BeginAccept(AsyncCallback callback, object state) { throw null; }
public IAsyncResult BeginAccept(int receiveSize, AsyncCallback callback, object state) { throw null; }
public IAsyncResult BeginAccept(Socket acceptSocket, int receiveSize, AsyncCallback callback, object state) { throw null; }
public IAsyncResult BeginConnect(string host, int port, AsyncCallback requestCallback, object state) { throw null; }
public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state) { throw null; }
public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback requestCallback, object state) { throw null; }
public IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state) { throw null; }
public IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback callback, object state) { throw null; }
public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state) { throw null; }
public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state) { throw null; }
public IAsyncResult BeginReceive(Collections.Generic.IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback callback, object state) { throw null; }
public IAsyncResult BeginReceive(Collections.Generic.IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state) { throw null; }
public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state) { throw null; }
public IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state) { throw null; }
public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state) { throw null; }
public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state) { throw null; }
public IAsyncResult BeginSend(Collections.Generic.IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback callback, object state) { throw null; }
public IAsyncResult BeginSend(Collections.Generic.IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state) { throw null; }
public IAsyncResult BeginSendFile(string fileName, AsyncCallback callback, object state) { throw null; }
public IAsyncResult BeginSendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state) { throw null; }
public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, AsyncCallback callback, object state) { throw null; }
public void Bind(System.Net.EndPoint localEP) { }
public static void CancelConnectAsync(System.Net.Sockets.SocketAsyncEventArgs e) { }
public void Close() { }
public void Close(int timeout) { }
public void Connect(System.Net.EndPoint remoteEP) { }
public void Connect(System.Net.IPAddress address, int port) { }
public void Connect(System.Net.IPAddress[] addresses, int port) { }
public void Connect(string host, int port) { }
public bool ConnectAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; }
public static bool ConnectAsync(System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType, System.Net.Sockets.SocketAsyncEventArgs e) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
~Socket() { }
public void Disconnect(bool reuseSocket) { }
public bool DisconnectAsync(SocketAsyncEventArgs e) { throw null; }
public SocketInformation DuplicateAndClose(int targetProcessId) { throw null; }
public Socket EndAccept(IAsyncResult asyncResult) { throw null; }
public Socket EndAccept(out byte[] buffer, IAsyncResult asyncResult) { throw null; }
public Socket EndAccept(out byte[] buffer, out int bytesTransferred, IAsyncResult asyncResult) { throw null; }
public void EndConnect(IAsyncResult asyncResult) { }
public void EndDisconnect(IAsyncResult asyncResult) { }
public int EndReceive(IAsyncResult asyncResult) { throw null; }
public int EndReceive(IAsyncResult asyncResult, out SocketError errorCode) { throw null; }
public int EndReceiveFrom(IAsyncResult asyncResult, ref EndPoint endPoint) { throw null; }
public int EndReceiveMessageFrom(IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation) { throw null; }
public int EndSend(IAsyncResult asyncResult) { throw null; }
public int EndSend(IAsyncResult asyncResult, out SocketError errorCode) { throw null; }
public void EndSendFile(IAsyncResult asyncResult) { }
public int EndSendTo(IAsyncResult asyncResult) { throw null; }
public object GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName) { throw null; }
public void GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, byte[] optionValue) { }
public byte[] GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, int optionLength) { throw null; }
public int IOControl(int ioControlCode, byte[] optionInValue, byte[] optionOutValue) { throw null; }
public int IOControl(System.Net.Sockets.IOControlCode ioControlCode, byte[] optionInValue, byte[] optionOutValue) { throw null; }
public void Listen(int backlog) { }
public bool Poll(int microSeconds, System.Net.Sockets.SelectMode mode) { throw null; }
public int Receive(byte[] buffer) { throw null; }
public int Receive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags) { throw null; }
public int Receive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; }
public int Receive(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags) { throw null; }
public int Receive(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; }
public int Receive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers) { throw null; }
public int Receive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; }
public int Receive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; }
public bool ReceiveAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; }
public int ReceiveFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { throw null; }
public int ReceiveFrom(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { throw null; }
public int ReceiveFrom(byte[] buffer, ref System.Net.EndPoint remoteEP) { throw null; }
public int ReceiveFrom(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { throw null; }
public bool ReceiveFromAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; }
public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, out System.Net.Sockets.IPPacketInformation ipPacketInformation) { throw null; }
public bool ReceiveMessageFromAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; }
public static void Select(System.Collections.IList checkRead, System.Collections.IList checkWrite, System.Collections.IList checkError, int microSeconds) { }
public int Send(byte[] buffer) { throw null; }
public int Send(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags) { throw null; }
public int Send(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; }
public int Send(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags) { throw null; }
public int Send(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; }
public int Send(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers) { throw null; }
public int Send(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; }
public int Send(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; }
public bool SendAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; }
public bool SendPacketsAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; }
public void SendFile(string fileName) { }
public void SendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags) { }
public int SendTo(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; }
public int SendTo(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; }
public int SendTo(byte[] buffer, System.Net.EndPoint remoteEP) { throw null; }
public int SendTo(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; }
public bool SendToAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; }
public void SetIPProtectionLevel(System.Net.Sockets.IPProtectionLevel level) { throw null; }
public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, bool optionValue) { }
public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, byte[] optionValue) { }
public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, int optionValue) { }
public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, object optionValue) { }
public void Shutdown(System.Net.Sockets.SocketShutdown how) { }
}
public partial class SocketAsyncEventArgs : System.EventArgs, System.IDisposable
{
public SocketAsyncEventArgs() { }
public System.Net.Sockets.Socket AcceptSocket { get { throw null; } set { } }
public byte[] Buffer { get { throw null; } }
public System.Collections.Generic.IList<System.ArraySegment<byte>> BufferList { get { throw null; } set { } }
public int BytesTransferred { get { throw null; } }
public System.Exception ConnectByNameError { get { throw null; } }
public System.Net.Sockets.Socket ConnectSocket { get { throw null; } }
public int Count { get { throw null; } }
public bool DisconnectReuseSocket { get { throw null; } set { } }
public System.Net.Sockets.SocketAsyncOperation LastOperation { get { throw null; } }
public int Offset { get { throw null; } }
public System.Net.Sockets.IPPacketInformation ReceiveMessageFromPacketInfo { get { throw null; } }
public System.Net.EndPoint RemoteEndPoint { get { throw null; } set { } }
public System.Net.Sockets.SendPacketsElement[] SendPacketsElements { get { throw null; } set { } }
public System.Net.Sockets.TransmitFileOptions SendPacketsFlags { get { throw null; } set { } }
public int SendPacketsSendSize { get { throw null; } set { } }
public System.Net.Sockets.SocketError SocketError { get { throw null; } set { } }
public System.Net.Sockets.SocketFlags SocketFlags { get { throw null; } set { } }
public object UserToken { get { throw null; } set { } }
public event System.EventHandler<System.Net.Sockets.SocketAsyncEventArgs> Completed { add { } remove { } }
public void Dispose() { }
~SocketAsyncEventArgs() { }
protected virtual void OnCompleted(System.Net.Sockets.SocketAsyncEventArgs e) { }
public void SetBuffer(byte[] buffer, int offset, int count) { }
public void SetBuffer(int offset, int count) { }
}
public enum SocketAsyncOperation
{
Accept = 1,
Connect = 2,
Disconnect = 3,
None = 0,
Receive = 4,
ReceiveFrom = 5,
ReceiveMessageFrom = 6,
Send = 7,
SendPackets = 8,
SendTo = 9,
}
[System.FlagsAttribute]
public enum SocketFlags
{
Broadcast = 1024,
ControlDataTruncated = 512,
DontRoute = 4,
Multicast = 2048,
None = 0,
OutOfBand = 1,
Partial = 32768,
Peek = 2,
Truncated = 256,
}
public partial struct SocketInformation
{
private object _dummy;
public System.Net.Sockets.SocketInformationOptions Options { get { throw null; } set { } }
public byte[] ProtocolInformation { get { throw null; } set { } }
}
[Flags]
public enum SocketInformationOptions
{
NonBlocking = 1,
Connected = 2,
Listening = 4,
UseOnlyOverlappedIO = 8,
}
public enum SocketOptionLevel
{
IP = 0,
IPv6 = 41,
Socket = 65535,
Tcp = 6,
Udp = 17,
}
public enum SocketOptionName
{
AcceptConnection = 2,
AddMembership = 12,
AddSourceMembership = 15,
BlockSource = 17,
Broadcast = 32,
BsdUrgent = 2,
ChecksumCoverage = 20,
Debug = 1,
DontFragment = 14,
DontLinger = -129,
DontRoute = 16,
DropMembership = 13,
DropSourceMembership = 16,
Error = 4103,
ExclusiveAddressUse = -5,
Expedited = 2,
HeaderIncluded = 2,
HopLimit = 21,
IPOptions = 1,
IPProtectionLevel = 23,
IpTimeToLive = 4,
IPv6Only = 27,
KeepAlive = 8,
Linger = 128,
MaxConnections = 2147483647,
MulticastInterface = 9,
MulticastLoopback = 11,
MulticastTimeToLive = 10,
NoChecksum = 1,
NoDelay = 1,
OutOfBandInline = 256,
PacketInformation = 19,
ReceiveBuffer = 4098,
ReceiveLowWater = 4100,
ReceiveTimeout = 4102,
ReuseAddress = 4,
ReuseUnicastPort = 12295,
SendBuffer = 4097,
SendLowWater = 4099,
SendTimeout = 4101,
Type = 4104,
TypeOfService = 3,
UnblockSource = 18,
UpdateAcceptContext = 28683,
UpdateConnectContext = 28688,
UseLoopback = 64,
}
// Review note: RemoteEndPoint definition includes the Address and Port.
// PacketInformation includes Address and Interface (physical interface number).
// The redundancy could be removed by replacing RemoteEndPoint with Port.
// Alternative:
// public struct SocketReceiveFromResult
// {
// public int ReceivedBytes;
// public IPAddress Address;
// public int Port;
// }
public struct SocketReceiveFromResult
{
public int ReceivedBytes;
public EndPoint RemoteEndPoint;
}
// Alternative:
// public struct SocketReceiveMessageFromResult
// {
// public int ReceivedBytes;
// public SocketFlags SocketFlags;
// public IPAddress Address;
// public int Port;
// public int Interface;
// }
public struct SocketReceiveMessageFromResult
{
public int ReceivedBytes;
public SocketFlags SocketFlags;
public EndPoint RemoteEndPoint;
public IPPacketInformation PacketInformation;
}
public enum SocketShutdown
{
Both = 2,
Receive = 0,
Send = 1,
}
public static partial class SocketTaskExtensions
{
public static System.Threading.Tasks.Task<Socket> AcceptAsync(this System.Net.Sockets.Socket socket) { throw null; }
public static System.Threading.Tasks.Task<Socket> AcceptAsync(this System.Net.Sockets.Socket socket, System.Net.Sockets.Socket acceptSocket) { throw null; }
public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.EndPoint remoteEP) { throw null; }
public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress address, int port) { throw null; }
public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress[] addresses, int port) { throw null; }
public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, string host, int port) { throw null; }
public static System.Threading.Tasks.Task<int> ReceiveAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; }
public static System.Threading.Tasks.Task<int> ReceiveAsync(this System.Net.Sockets.Socket socket, System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; }
public static System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveFromResult> ReceiveFromAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint) { throw null; }
public static System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveMessageFromResult> ReceiveMessageFromAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint) { throw null; }
public static System.Threading.Tasks.Task<int> SendAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; }
public static System.Threading.Tasks.Task<int> SendAsync(this System.Net.Sockets.Socket socket, System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; }
public static System.Threading.Tasks.Task<int> SendToAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; }
}
public enum SocketType
{
Dgram = 2,
Raw = 3,
Rdm = 4,
Seqpacket = 5,
Stream = 1,
Unknown = -1,
}
public partial class TcpClient : System.IDisposable
{
public TcpClient() { }
public TcpClient(System.Net.Sockets.AddressFamily family) { }
public TcpClient(System.Net.IPEndPoint localEP) { }
public TcpClient(string hostname, int port) { }
protected bool Active { get { throw null; } set { } }
public int Available { get { throw null; } }
public System.Net.Sockets.Socket Client { get { throw null; } set { } }
public bool Connected { get { throw null; } }
public bool ExclusiveAddressUse { get { throw null; } set { } }
public System.Net.Sockets.LingerOption LingerState { get { throw null; } set { } }
public bool NoDelay { get { throw null; } set { } }
public int ReceiveBufferSize { get { throw null; } set { } }
public int ReceiveTimeout { get { throw null; } set { } }
public int SendBufferSize { get { throw null; } set { } }
public int SendTimeout { get { throw null; } set { } }
public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state) { throw null; }
public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback requestCallback, object state) { throw null; }
public IAsyncResult BeginConnect(string host, int port, AsyncCallback requestCallback, object state) { throw null; }
public void Close() { }
public void Connect(System.Net.IPAddress address, int port) { }
public void Connect(System.Net.IPAddress[] ipAddresses, int port) { }
public void Connect(System.Net.IPEndPoint remoteEP) { }
public void Connect(string hostname, int port) { }
public System.Threading.Tasks.Task ConnectAsync(System.Net.IPAddress address, int port) { throw null; }
public System.Threading.Tasks.Task ConnectAsync(System.Net.IPAddress[] addresses, int port) { throw null; }
public System.Threading.Tasks.Task ConnectAsync(string host, int port) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
~TcpClient() { }
public void EndConnect(IAsyncResult asyncResult) { }
public System.Net.Sockets.NetworkStream GetStream() { throw null; }
}
public partial class TcpListener
{
[System.ObsoleteAttribute("This method has been deprecated. Please use TcpListener(IPAddress localaddr, int port) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public TcpListener(int port) { }
public TcpListener(System.Net.IPAddress localaddr, int port) { }
public TcpListener(System.Net.IPEndPoint localEP) { }
protected bool Active { get { throw null; } }
public bool ExclusiveAddressUse { get { throw null; } set { } }
public System.Net.EndPoint LocalEndpoint { get { throw null; } }
public System.Net.Sockets.Socket Server { get { throw null; } }
public System.Net.Sockets.Socket AcceptSocket() { throw null; }
public System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptSocketAsync() { throw null; }
public System.Net.Sockets.TcpClient AcceptTcpClient() { throw null; }
public System.Threading.Tasks.Task<System.Net.Sockets.TcpClient> AcceptTcpClientAsync() { throw null; }
public System.IAsyncResult BeginAcceptSocket(System.AsyncCallback callback, object state) { throw null; }
public System.IAsyncResult BeginAcceptTcpClient(System.AsyncCallback callback, object state) { throw null; }
public System.Net.Sockets.Socket EndAcceptSocket(System.IAsyncResult asyncResult) { throw null; }
public System.Net.Sockets.TcpClient EndAcceptTcpClient(System.IAsyncResult asyncResult) { throw null; }
public bool Pending() { throw null; }
public void Start() { }
public void Start(int backlog) { }
public void Stop() { }
public void AllowNatTraversal(bool allowed) { throw null; }
public static TcpListener Create(int port) { throw null; }
}
[System.FlagsAttribute]
public enum TransmitFileOptions
{
Disconnect = 1,
ReuseSocket = 2,
UseDefaultWorkerThread = 0,
UseKernelApc = 32,
UseSystemThread = 16,
WriteBehind = 4,
}
public partial class UdpClient : System.IDisposable
{
public UdpClient() { }
public UdpClient(int port) { }
public UdpClient(int port, System.Net.Sockets.AddressFamily family) { }
public UdpClient(System.Net.IPEndPoint localEP) { }
public UdpClient(System.Net.Sockets.AddressFamily family) { }
public UdpClient(string hostname, int port) { }
protected bool Active { get { throw null; } set { } }
public int Available { get { throw null; } }
public System.Net.Sockets.Socket Client { get { throw null; } set { } }
public bool DontFragment { get { throw null; } set { } }
public bool EnableBroadcast { get { throw null; } set { } }
public bool ExclusiveAddressUse { get { throw null; } set { } }
public bool MulticastLoopback { get { throw null; } set { } }
public short Ttl { get { throw null; } set { } }
public IAsyncResult BeginReceive(AsyncCallback requestCallback, object state) { throw null; }
public IAsyncResult BeginSend(byte[] datagram, int bytes, AsyncCallback requestCallback, object state) { throw null; }
public IAsyncResult BeginSend(byte[] datagram, int bytes, IPEndPoint endPoint, AsyncCallback requestCallback, object state) { throw null; }
public IAsyncResult BeginSend(byte[] datagram, int bytes, string hostname, int port, AsyncCallback requestCallback, object state) { throw null; }
public void Close() { }
public void Connect(IPAddress addr, int port) { }
public void Connect(IPEndPoint endPoint) { }
public void Connect(string hostname, int port) { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public void DropMulticastGroup(System.Net.IPAddress multicastAddr) { }
public void DropMulticastGroup(System.Net.IPAddress multicastAddr, int ifindex) { }
public byte[] EndReceive(IAsyncResult asyncResult, ref IPEndPoint remoteEP) { throw null; }
public int EndSend(IAsyncResult asyncResult) { throw null; }
public void JoinMulticastGroup(int ifindex, System.Net.IPAddress multicastAddr) { }
public void JoinMulticastGroup(System.Net.IPAddress multicastAddr) { }
public void JoinMulticastGroup(System.Net.IPAddress multicastAddr, int timeToLive) { }
public void JoinMulticastGroup(System.Net.IPAddress multicastAddr, System.Net.IPAddress localAddress) { }
public byte[] Receive(ref IPEndPoint remoteEP) { throw null; }
public System.Threading.Tasks.Task<System.Net.Sockets.UdpReceiveResult> ReceiveAsync() { throw null; }
public int Send(byte[] dgram, int bytes) { throw null; }
public int Send(byte[] dgram, int bytes, System.Net.IPEndPoint endPoint) { throw null; }
public int Send(byte[] dgram, int bytes, string hostname, int port) { throw null; }
public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes) { throw null; }
public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, System.Net.IPEndPoint endPoint) { throw null; }
public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, string hostname, int port) { throw null; }
public void AllowNatTraversal(bool allowed) { throw null; }
}
public partial struct UdpReceiveResult : System.IEquatable<System.Net.Sockets.UdpReceiveResult>
{
private object _dummy;
public UdpReceiveResult(byte[] buffer, System.Net.IPEndPoint remoteEndPoint) { throw null; }
public byte[] Buffer { get { throw null; } }
public System.Net.IPEndPoint RemoteEndPoint { get { throw null; } }
public bool Equals(System.Net.Sockets.UdpReceiveResult other) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Net.Sockets.UdpReceiveResult left, System.Net.Sockets.UdpReceiveResult right) { throw null; }
public static bool operator !=(System.Net.Sockets.UdpReceiveResult left, System.Net.Sockets.UdpReceiveResult right) { throw null; }
}
}
| |
namespace Nancy.Tests.Unit
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using FakeItEasy;
using Nancy.Bootstrapper;
using Nancy.Diagnostics;
using Nancy.ErrorHandling;
using Nancy.Extensions;
using Nancy.Helpers;
using Nancy.Routing;
using Nancy.Tests.Fakes;
using Xunit;
using Nancy.Responses.Negotiation;
using Nancy.Tests.xUnitExtensions;
public class NancyEngineFixture
{
private readonly INancyEngine engine;
private readonly IRouteResolver resolver;
private readonly FakeRoute route;
private readonly NancyContext context;
private readonly INancyContextFactory contextFactory;
private readonly Response response;
private readonly IStatusCodeHandler statusCodeHandler;
private readonly IRouteInvoker routeInvoker;
private readonly IRequestDispatcher requestDispatcher;
private readonly IResponseNegotiator negotiator;
public NancyEngineFixture()
{
this.resolver = A.Fake<IRouteResolver>();
this.response = new Response();
this.route = new FakeRoute(response);
this.context = new NancyContext();
this.statusCodeHandler = A.Fake<IStatusCodeHandler>();
this.requestDispatcher = A.Fake<IRequestDispatcher>();
this.negotiator = A.Fake<IResponseNegotiator>();
A.CallTo(() => this.requestDispatcher.Dispatch(A<NancyContext>._, A<CancellationToken>._))
.Returns(Task.FromResult(new Response()));
A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(false);
contextFactory = A.Fake<INancyContextFactory>();
A.CallTo(() => contextFactory.Create(A<Request>._)).Returns(context);
var resolveResult = new ResolveResult { Route = route, Parameters = DynamicDictionary.Empty, Before = null, After = null, OnError = null };
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolveResult);
var applicationPipelines = new Pipelines();
this.routeInvoker = A.Fake<IRouteInvoker>();
A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, A<DynamicDictionary>._, A<NancyContext>._)).ReturnsLazily(arg =>
{
return ((Route)arg.Arguments[0]).Action.Invoke((DynamicDictionary)arg.Arguments[1], A<CancellationToken>._).Result;
});
this.engine =
new NancyEngine(this.requestDispatcher, this.contextFactory, new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator)
{
RequestPipelinesFactory = ctx => applicationPipelines
};
}
[Fact]
public void Should_throw_argumentnullexception_when_created_with_null_dispatcher()
{
// Given, When
var exception =
Record.Exception(() => new NancyEngine(null, A.Fake<INancyContextFactory>(), new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator));
// Then
exception.ShouldBeOfType<ArgumentNullException>();
}
[Fact]
public void Should_throw_argumentnullexception_when_created_with_null_context_factory()
{
// Given, When
var exception =
Record.Exception(() => new NancyEngine(this.requestDispatcher, null, new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator));
// Then
exception.ShouldBeOfType<ArgumentNullException>();
}
[Fact]
public void Should_throw_argumentnullexception_when_created_with_null_status_handler()
{
// Given, When
var exception =
Record.Exception(() => new NancyEngine(this.requestDispatcher, A.Fake<INancyContextFactory>(), null, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator));
// Then
exception.ShouldBeOfType<ArgumentNullException>();
}
[Fact]
public async Task HandleRequest_Should_Throw_ArgumentNullException_When_Given_A_Null_Request()
{
// Given,
Request request = null;
// When
var exception = await RecordAsync.Exception(async () => await engine.HandleRequest(request));
// Then
exception.ShouldBeOfType<ArgumentNullException>();
}
[Fact]
public void HandleRequest_should_get_context_from_context_factory()
{
// Given
var request = new Request("GET", "/", "http");
// When
this.engine.HandleRequest(request);
// Then
A.CallTo(() => this.contextFactory.Create(request)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public async Task HandleRequest_should_set_correct_response_on_returned_context()
{
// Given
var request = new Request("GET", "/", "http");
A.CallTo(() => this.requestDispatcher.Dispatch(this.context, A<CancellationToken>._))
.Returns(Task.FromResult(this.response));
// When
var result = await this.engine.HandleRequest(request);
// Then
result.Response.ShouldBeSameAs(this.response);
}
[Fact]
public async Task Should_not_add_nancy_version_number_header_on_returned_response()
{
// NOTE: Regression for removal of nancy-version from response headers
// Given
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
// Then
result.Response.Headers.ContainsKey("Nancy-Version").ShouldBeFalse();
}
[Fact]
public async Task Should_not_throw_exception_when_handlerequest_is_invoked_and_pre_request_hook_is_null()
{
// Given
var pipelines = new Pipelines { BeforeRequest = null };
engine.RequestPipelinesFactory = (ctx) => pipelines;
// When
var request = new Request("GET", "/", "http");
// Then
await this.engine.HandleRequest(request);
}
[Fact]
public async Task Should_not_throw_exception_when_handlerequest_is_invoked_and_post_request_hook_is_null()
{
// Given
var pipelines = new Pipelines { AfterRequest = null };
engine.RequestPipelinesFactory = (ctx) => pipelines;
// When
var request = new Request("GET", "/", "http");
// Then
await this.engine.HandleRequest(request);
}
[Fact]
public async Task Should_call_pre_request_hook_should_be_invoked_with_request_from_context()
{
// Given
Request passedRequest = null;
var pipelines = new Pipelines();
pipelines.BeforeRequest.AddItemToStartOfPipeline((ctx) =>
{
passedRequest = ctx.Request;
return null;
});
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
this.context.Request = request;
// When
await this.engine.HandleRequest(request);
// Then
passedRequest.ShouldBeSameAs(request);
}
[Fact]
public async Task Should_return_response_from_pre_request_hook_when_not_null()
{
// Given
var returnedResponse = A.Fake<Response>();
var pipelines = new Pipelines();
pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => returnedResponse);
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
// Then
result.Response.ShouldBeSameAs(returnedResponse);
}
[Fact]
public async Task Should_allow_post_request_hook_to_modify_context_items()
{
// Given
var pipelines = new Pipelines();
pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx =>
{
ctx.Items.Add("PostReqTest", new object());
return null;
});
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
// Then
result.Items.ContainsKey("PostReqTest").ShouldBeTrue();
}
[Fact]
public async Task Should_allow_post_request_hook_to_replace_response()
{
// Given
var newResponse = new Response();
var pipelines = new Pipelines();
pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => ctx.Response = newResponse);
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
// Then
result.Response.ShouldBeSameAs(newResponse);
}
[Fact]
public async Task HandleRequest_prereq_returns_response_should_still_run_postreq()
{
// Given
var returnedResponse = A.Fake<Response>();
var postReqCalled = false;
var pipelines = new Pipelines();
pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => returnedResponse);
pipelines.AfterRequest.AddItemToEndOfPipeline(ctx => postReqCalled = true);
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
await this.engine.HandleRequest(request);
// Then
postReqCalled.ShouldBeTrue();
}
[Fact]
public async Task Should_ask_status_handler_if_it_can_handle_status_code()
{
// Given
var request = new Request("GET", "/", "http");
// When
await this.engine.HandleRequest(request);
// Then
A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public async Task Should_not_invoke_status_handler_if_not_supported_status_code()
{
// Given
var request = new Request("GET", "/", "http");
// When
await this.engine.HandleRequest(request);
// Then
A.CallTo(() => this.statusCodeHandler.Handle(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).MustNotHaveHappened();
}
[Fact]
public async Task Should_invoke_status_handler_if_supported_status_code()
{
// Given
var request = new Request("GET", "/", "http");
A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(true);
// When
await this.engine.HandleRequest(request);
// Then
A.CallTo(() => this.statusCodeHandler.Handle(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public async Task Should_set_status_code_to_500_if_route_throws()
{
// Given
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))
.Returns(TaskHelpers.GetFaultedTask<Response>(new NotImplementedException()));
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
// Then
result.Response.StatusCode.ShouldEqual(HttpStatusCode.InternalServerError);
}
[Fact]
public async Task Should_store_exception_details_if_dispatcher_throws()
{
// Given
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))
.Returns(TaskHelpers.GetFaultedTask<Response>(new NotImplementedException()));
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
// Then
result.GetExceptionDetails().ShouldContain("NotImplementedException");
}
[Fact]
public async Task Should_invoke_the_error_request_hook_if_one_exists_when_dispatcher_throws()
{
// Given
var testEx = new Exception();
var errorRoute =
new Route("GET", "/", null, (x,c) => { throw testEx; });
var resolvedRoute = new ResolveResult(
errorRoute,
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))
.Returns(TaskHelpers.GetFaultedTask<Response>(testEx));
Exception handledException = null;
NancyContext handledContext = null;
var errorResponse = new Response();
A.CallTo(() => this.negotiator.NegotiateResponse(A<object>.Ignored, A<NancyContext>.Ignored))
.Returns(errorResponse);
Func<NancyContext, Exception, dynamic> routeErrorHook = (ctx, ex) =>
{
handledContext = ctx;
handledException = ex;
return errorResponse;
};
var pipelines = new Pipelines();
pipelines.OnError.AddItemToStartOfPipeline(routeErrorHook);
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
// Then
Assert.Equal(testEx, handledException);
Assert.Equal(result, handledContext);
Assert.Equal(result.Response, errorResponse);
}
[Fact]
public async Task Should_add_unhandled_exception_to_context_as_requestexecutionexception()
{
// Given
var routeUnderTest =
new Route("GET", "/", null, (x,c) => { throw new Exception(); });
var resolved =
new ResolveResult(routeUnderTest, DynamicDictionary.Empty, null, null, null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolved);
A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, A<DynamicDictionary>._, A<NancyContext>._))
.Invokes((x) => routeUnderTest.Action.Invoke(DynamicDictionary.Empty, new CancellationToken()));
A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))
.Returns(TaskHelpers.GetFaultedTask<Response>(new Exception()));
var pipelines = new Pipelines();
pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null);
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
// Then
result.Items.Keys.Contains("ERROR_EXCEPTION").ShouldBeTrue();
result.Items["ERROR_EXCEPTION"].ShouldBeOfType<RequestExecutionException>();
}
[Fact]
public async Task Should_persist_original_exception_in_requestexecutionexception()
{
// Given
var expectedException = new Exception();
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))
.Returns(TaskHelpers.GetFaultedTask<Response>(expectedException));
var pipelines = new Pipelines();
pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null);
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
var returnedException = result.Items["ERROR_EXCEPTION"] as RequestExecutionException;
// Then
returnedException.InnerException.ShouldBeSameAs(expectedException);
}
[Fact]
public async Task Should_persist_original_exception_in_requestexecutionexception_when_pipeline_is_null()
{
// Given
var expectedException = new Exception();
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))
.Returns(TaskHelpers.GetFaultedTask<Response>(expectedException));
var pipelines = new Pipelines { OnError = null };
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
var returnedException = result.Items["ERROR_EXCEPTION"] as RequestExecutionException;
// Then
returnedException.InnerException.ShouldBeSameAs(expectedException);
}
[Fact]
public async Task Should_return_static_content_response_if_one_returned()
{
var localResponse = new Response();
var staticContent = A.Fake<IStaticContentProvider>();
A.CallTo(() => staticContent.GetContent(A<NancyContext>._))
.Returns(localResponse);
var localEngine = new NancyEngine(
this.requestDispatcher,
this.contextFactory,
new[] { this.statusCodeHandler },
A.Fake<IRequestTracing>(),
staticContent,
this.negotiator);
var request = new Request("GET", "/", "http");
var result = await localEngine.HandleRequest(request);
result.Response.ShouldBeSameAs(localResponse);
}
[Fact]
public async Task Should_set_status_code_to_500_if_pre_execute_response_throws()
{
// Given
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))
.Returns(Task.FromResult<Response>(new PreExecuteFailureResponse()));
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
// Then
result.Response.StatusCode.ShouldEqual(HttpStatusCode.InternalServerError);
}
[Fact]
public async Task Should_throw_operationcancelledexception_when_disposed_handling_request()
{
// Given
var request = new Request("GET", "/", "http");
var engine = new NancyEngine(A.Fake<IRequestDispatcher>(), A.Fake<INancyContextFactory>(),
new[] {this.statusCodeHandler}, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(),
this.negotiator);
engine.Dispose();
// When
var exception = await RecordAsync.Exception(async () => await engine.HandleRequest(request));
// Then
exception.ShouldBeOfType<OperationCanceledException>();
}
}
public class PreExecuteFailureResponse : Response
{
public override Task PreExecute(NancyContext context)
{
return TaskHelpers.GetFaultedTask<object>(new InvalidOperationException());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Htc.Vita.Core.Log;
namespace Htc.Vita.Core.Runtime
{
public static partial class UserManager
{
internal static class Windows
{
internal static string GetFirstActiveUserInPlatform(string serverName)
{
var windowsUsers = GetPlatformUsers(serverName);
return (from windowsUser
in windowsUsers
where windowsUser.State == Interop.Windows.WindowsTerminalServiceConnectState.Active
select string.Format($"{windowsUser.Domain}\\{windowsUser.Username}")
).FirstOrDefault();
}
internal static string GetPlatformUsernameBySid(string userSid)
{
return GetPlatformUsernameBySid(userSid, null);
}
internal static string GetPlatformUsernameBySid(string userSid, string serverName)
{
if (string.IsNullOrWhiteSpace(userSid))
{
return null;
}
string result = null;
var userSidPtr = IntPtr.Zero;
var username = new StringBuilder();
uint usernameLength = 0;
var domain = new StringBuilder();
uint domainLength = 0;
try
{
var success = Interop.Windows.ConvertStringSidToSidW(
userSid,
userSidPtr
);
if (success)
{
var sidType = Interop.Windows.SidType.Unknown;
success = Interop.Windows.LookupAccountSidW(
serverName,
userSidPtr,
username,
ref usernameLength,
domain,
ref domainLength,
ref sidType
);
if (success)
{
if (sidType == Interop.Windows.SidType.User)
{
result = string.Format($"{domain}\\{username}");
}
else
{
Logger.GetInstance(typeof(Windows)).Warn($"Can not translate sid type \"{sidType}\" to username.");
}
}
}
}
catch (Exception e)
{
Logger.GetInstance(typeof(Windows)).Error($"Can not get Windows username: {e.Message}");
}
return result;
}
internal static List<WindowsUserInfo> GetPlatformUsers(string serverName)
{
var machineName = serverName;
if (string.IsNullOrWhiteSpace(machineName))
{
machineName = Environment.MachineName;
}
var results = new List<WindowsUserInfo>();
using (var serverHandle = Interop.Windows.WTSOpenServerW(machineName))
{
if (serverHandle == null || serverHandle.IsInvalid)
{
return results;
}
try
{
var sessionInfoPtr = IntPtr.Zero;
var sessionCount = 0U;
var success = Interop.Windows.WTSEnumerateSessionsW(
serverHandle,
0,
1,
ref sessionInfoPtr,
ref sessionCount
);
var dataSize = Marshal.SizeOf(typeof(Interop.Windows.WindowsTerminalServiceSessionInfo));
var currentSessionInfoPtr = sessionInfoPtr;
if (success)
{
if (sessionCount <= 0U)
{
Logger.GetInstance(typeof(Windows)).Error("Can not find available WTS session");
}
for (var sessionIndex = 0U; sessionIndex < sessionCount; sessionIndex++)
{
var sessionInfo = (Interop.Windows.WindowsTerminalServiceSessionInfo)Marshal.PtrToStructure(
currentSessionInfoPtr,
typeof(Interop.Windows.WindowsTerminalServiceSessionInfo)
);
currentSessionInfoPtr += dataSize;
uint bytes = 0;
var usernamePtr = IntPtr.Zero;
success = Interop.Windows.WTSQuerySessionInformationW(
serverHandle,
sessionInfo.sessionId,
Interop.Windows.WindowsTerminalServiceInfo.UserName,
ref usernamePtr,
ref bytes
);
if (!success)
{
continue;
}
var username = Marshal.PtrToStringUni(usernamePtr);
Interop.Windows.WTSFreeMemory(usernamePtr);
var domainPtr = IntPtr.Zero;
success = Interop.Windows.WTSQuerySessionInformationW(
serverHandle,
sessionInfo.sessionId,
Interop.Windows.WindowsTerminalServiceInfo.DomainName,
ref domainPtr,
ref bytes
);
if (!success)
{
continue;
}
var domain = Marshal.PtrToStringUni(domainPtr);
Interop.Windows.WTSFreeMemory(domainPtr);
var userInfo = new WindowsUserInfo
{
State = sessionInfo.state,
Domain = domain,
Username = username
};
results.Add(userInfo);
}
Interop.Windows.WTSFreeMemory(sessionInfoPtr);
}
else
{
Logger.GetInstance(typeof(Windows)).Error($"Can not enumerate WTS session, error code: {Marshal.GetLastWin32Error()}");
}
}
catch (Exception e)
{
Logger.GetInstance(typeof(Windows)).Error($"Can not get Windows user list: {e.Message}");
}
return results;
}
}
internal static bool IsShellUserElevatedInPlatform()
{
var shellWindowHandle = Interop.Windows.GetShellWindow();
if (shellWindowHandle == IntPtr.Zero)
{
Logger.GetInstance(typeof(Windows)).Error($"Can not get shell window handle, error code: {Marshal.GetLastWin32Error()}");
return false;
}
try
{
var shellWindowProcessId = 0U;
Interop.Windows.GetWindowThreadProcessId(
shellWindowHandle,
ref shellWindowProcessId
);
if (shellWindowProcessId == 0)
{
Logger.GetInstance(typeof(Windows)).Error($"Can not get shell window process id, error code: {Marshal.GetLastWin32Error()}");
return false;
}
using (var shellWindowProcess = Process.GetProcessById((int) shellWindowProcessId))
{
Logger.GetInstance(typeof(Windows)).Debug($"Current shell process: {shellWindowProcess.ProcessName} ({shellWindowProcessId})");
return ProcessManager.IsElevatedProcess(shellWindowProcess);
}
}
catch (Exception e)
{
Logger.GetInstance(typeof(Windows)).Error($"Can not check if shell user is elevated. {e.Message}");
}
finally
{
if (shellWindowHandle != IntPtr.Zero)
{
Interop.Windows.CloseHandle(shellWindowHandle);
}
}
return false;
}
internal static bool SendMessageToFirstActiveUserInPlatform(
string title,
string message,
uint timeout,
string serverName)
{
if (string.IsNullOrWhiteSpace(title) || string.IsNullOrWhiteSpace(message))
{
return false;
}
var machineName = serverName;
if (string.IsNullOrWhiteSpace(machineName))
{
machineName = Environment.MachineName;
}
using (var serverHandle = Interop.Windows.WTSOpenServerW(machineName))
{
if (serverHandle == null || serverHandle.IsInvalid)
{
return false;
}
try
{
var sessionInfoPtr = IntPtr.Zero;
var sessionCount = 0U;
var success = Interop.Windows.WTSEnumerateSessionsW(
serverHandle,
0,
1,
ref sessionInfoPtr,
ref sessionCount
);
var dataSize = Marshal.SizeOf(typeof(Interop.Windows.WindowsTerminalServiceSessionInfo));
var currentSessionInfoPtr = sessionInfoPtr;
if (success)
{
if (sessionCount <= 0U)
{
Logger.GetInstance(typeof(Windows)).Error("Can not find available WTS session");
return false;
}
for (var sessionIndex = 0U; sessionIndex < sessionCount; sessionIndex++)
{
var sessionInfo = (Interop.Windows.WindowsTerminalServiceSessionInfo)Marshal.PtrToStructure(
currentSessionInfoPtr,
typeof(Interop.Windows.WindowsTerminalServiceSessionInfo)
);
currentSessionInfoPtr += dataSize;
if (sessionInfo.state != Interop.Windows.WindowsTerminalServiceConnectState.Active)
{
continue;
}
var dialogBoxResult = Interop.Windows.DialogBoxResult.None;
success = Interop.Windows.WTSSendMessageW(
serverHandle,
sessionInfo.sessionId,
title,
(uint) title.Length * 2,
message,
(uint) message.Length * 2,
Interop.Windows.MessageBoxStyle.Ok,
timeout,
ref dialogBoxResult,
true
);
if (!success)
{
return false;
}
if (dialogBoxResult == Interop.Windows.DialogBoxResult.Ok)
{
return true;
}
}
Interop.Windows.WTSFreeMemory(sessionInfoPtr);
}
else
{
Logger.GetInstance(typeof(Windows)).Error($"Can not enumerate WTS session, error code: {Marshal.GetLastWin32Error()}");
}
}
catch (Exception e)
{
Logger.GetInstance(typeof(Windows)).Error($"Can not send message to active user: {e.Message}");
}
return false;
}
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using u32 = System.UInt32;
using Pgno = System.UInt32;
namespace Community.CsharpSqlite
{
using sqlite3_value = Sqlite3.Mem;
using sqlite3_pcache = Sqlite3.PCache1;
public partial class Sqlite3
{
/*
** 2008 August 05
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file implements that page cache.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-03-09 19:31:43 4ae453ea7be69018d8c16eb8dabe05617397dc4d
**
** $Header$
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** A complete page cache is an instance of this structure.
*/
public class PCache
{
public PgHdr pDirty, pDirtyTail; /* List of dirty pages in LRU order */
public PgHdr pSynced; /* Last synced page in dirty page list */
public int nRef; /* Number of referenced pages */
public int nMax; /* Configured cache size */
public int szPage; /* Size of every page in this cache */
public int szExtra; /* Size of extra space for each page */
public bool bPurgeable; /* True if pages are on backing store */
public dxStress xStress; //int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
public object pStress; /* Argument to xStress */
public sqlite3_pcache pCache; /* Pluggable cache module */
public PgHdr pPage1; /* Reference to page 1 */
public void Clear()
{
pDirty = null;
pDirtyTail = null;
pSynced = null;
nRef = 0;
}
};
/*
** Some of the Debug.Assert() macros in this code are too expensive to run
** even during normal debugging. Use them only rarely on long-running
** tests. Enable the expensive asserts using the
** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
*/
#if SQLITE_ENABLE_EXPENSIVE_ASSERT
//# define expensive_assert(X) Debug.Assert(X)
static void expensive_assert( bool x ) { Debug.Assert( x ); }
#else
//# define expensive_assert(X)
#endif
/********************************** Linked List Management ********************/
#if !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT
/*
** Check that the pCache.pSynced variable is set correctly. If it
** is not, either fail an Debug.Assert or return zero. Otherwise, return
** non-zero. This is only used in debugging builds, as follows:
**
** expensive_assert( pcacheCheckSynced(pCache) );
*/
static int pcacheCheckSynced(PCache pCache){
PgHdr p ;
for(p=pCache.pDirtyTail; p!=pCache.pSynced; p=p.pDirtyPrev){
Debug.Assert( p.nRef !=0|| (p.flags&PGHDR_NEED_SYNC) !=0);
}
return (p==null || p.nRef!=0 || (p.flags&PGHDR_NEED_SYNC)==0)?1:0;
}
#endif //* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
/*
** Remove page pPage from the list of dirty pages.
*/
static void pcacheRemoveFromDirtyList( PgHdr pPage )
{
PCache p = pPage.pCache;
Debug.Assert( pPage.pDirtyNext != null || pPage == p.pDirtyTail );
Debug.Assert( pPage.pDirtyPrev != null || pPage == p.pDirty );
/* Update the PCache1.pSynced variable if necessary. */
if ( p.pSynced == pPage )
{
PgHdr pSynced = pPage.pDirtyPrev;
while ( pSynced != null && ( pSynced.flags & PGHDR_NEED_SYNC ) != 0 )
{
pSynced = pSynced.pDirtyPrev;
}
p.pSynced = pSynced;
}
if ( pPage.pDirtyNext != null )
{
pPage.pDirtyNext.pDirtyPrev = pPage.pDirtyPrev;
}
else
{
Debug.Assert( pPage == p.pDirtyTail );
p.pDirtyTail = pPage.pDirtyPrev;
}
if ( pPage.pDirtyPrev != null )
{
pPage.pDirtyPrev.pDirtyNext = pPage.pDirtyNext;
}
else
{
Debug.Assert( pPage == p.pDirty );
p.pDirty = pPage.pDirtyNext;
}
pPage.pDirtyNext = null;
pPage.pDirtyPrev = null;
#if SQLITE_ENABLE_EXPENSIVE_ASSERT
expensive_assert( pcacheCheckSynced(p) );
#endif
}
/*
** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
** pPage).
*/
static void pcacheAddToDirtyList( PgHdr pPage )
{
PCache p = pPage.pCache;
Debug.Assert( pPage.pDirtyNext == null && pPage.pDirtyPrev == null && p.pDirty != pPage );
pPage.pDirtyNext = p.pDirty;
if ( pPage.pDirtyNext != null )
{
Debug.Assert( pPage.pDirtyNext.pDirtyPrev == null );
pPage.pDirtyNext.pDirtyPrev = pPage;
}
p.pDirty = pPage;
if ( null == p.pDirtyTail )
{
p.pDirtyTail = pPage;
}
if ( null == p.pSynced && 0 == ( pPage.flags & PGHDR_NEED_SYNC ) )
{
p.pSynced = pPage;
}
#if SQLITE_ENABLE_EXPENSIVE_ASSERT
expensive_assert( pcacheCheckSynced(p) );
#endif
}
/*
** Wrapper around the pluggable caches xUnpin method. If the cache is
** being used for an in-memory database, this function is a no-op.
*/
static void pcacheUnpin( PgHdr p )
{
PCache pCache = p.pCache;
if ( pCache.bPurgeable )
{
if ( p.pgno == 1 )
{
pCache.pPage1 = null;
}
sqlite3GlobalConfig.pcache.xUnpin( pCache.pCache, p, 0 );
}
}
/*************************************************** General Interfaces ******
**
** Initialize and shutdown the page cache subsystem. Neither of these
** functions are threadsafe.
*/
static int sqlite3PcacheInitialize()
{
if ( sqlite3GlobalConfig.pcache.xInit == null )
{
sqlite3PCacheSetDefault();
}
return sqlite3GlobalConfig.pcache.xInit( sqlite3GlobalConfig.pcache.pArg );
}
static void sqlite3PcacheShutdown()
{
if ( sqlite3GlobalConfig.pcache.xShutdown != null )
{
sqlite3GlobalConfig.pcache.xShutdown( sqlite3GlobalConfig.pcache.pArg );
}
}
/*
** Return the size in bytes of a PCache object.
*/
static int sqlite3PcacheSize() { return 4; }// sizeof( PCache ); }
/*
** Create a new PCache object. Storage space to hold the object
** has already been allocated and is passed in as the p pointer.
** The caller discovers how much space needs to be allocated by
** calling sqlite3PcacheSize().
*/
static void sqlite3PcacheOpen(
int szPage, /* Size of every page */
int szExtra, /* Extra space associated with each page */
bool bPurgeable, /* True if pages are on backing store */
dxStress xStress,//int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
object pStress, /* Argument to xStress */
PCache p /* Preallocated space for the PCache */
)
{
p.Clear();//memset(p, 0, sizeof(PCache));
p.szPage = szPage;
p.szExtra = szExtra;
p.bPurgeable = bPurgeable;
p.xStress = xStress;
p.pStress = pStress;
p.nMax = 100;
}
/*
** Change the page size for PCache object. The caller must ensure that there
** are no outstanding page references when this function is called.
*/
static void sqlite3PcacheSetPageSize( PCache pCache, int szPage )
{
Debug.Assert( pCache.nRef == 0 && pCache.pDirty == null );
if ( pCache.pCache != null )
{
sqlite3GlobalConfig.pcache.xDestroy( ref pCache.pCache );
pCache.pCache = null;
}
pCache.szPage = szPage;
}
/*
** Try to obtain a page from the cache.
*/
static int sqlite3PcacheFetch(
PCache pCache, /* Obtain the page from this cache */
u32 pgno, /* Page number to obtain */
int createFlag, /* If true, create page if it does not exist already */
ref PgHdr ppPage /* Write the page here */
)
{
PgHdr pPage = null;
int eCreate;
Debug.Assert( pCache != null );
Debug.Assert( createFlag == 1 || createFlag == 0 );
Debug.Assert( pgno > 0 );
/* If the pluggable cache (sqlite3_pcache*) has not been allocated,
** allocate it now.
*/
if ( null == pCache.pCache && createFlag != 0 )
{
sqlite3_pcache p;
int nByte;
nByte = pCache.szPage + pCache.szExtra + 0;// sizeof( PgHdr );
p = sqlite3GlobalConfig.pcache.xCreate( nByte, pCache.bPurgeable ? 1 : 0 );
if ( null == p )
{
return SQLITE_NOMEM;
}
sqlite3GlobalConfig.pcache.xCachesize( p, pCache.nMax );
pCache.pCache = p;
}
eCreate = createFlag * ( 1 + ( ( !pCache.bPurgeable || null == pCache.pDirty ) ? 1 : 0 ) );
if ( pCache.pCache != null )
{
pPage = sqlite3GlobalConfig.pcache.xFetch( pCache.pCache, pgno, eCreate );
}
if ( null == pPage && eCreate == 1 )
{
PgHdr pPg;
/* Find a dirty page to write-out and recycle. First try to find a
** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
** cleared), but if that is not possible settle for any other
** unreferenced dirty page.
*/
#if SQLITE_ENABLE_EXPENSIVE_ASSERT
expensive_assert( pcacheCheckSynced(pCache) );
#endif
for ( pPg = pCache.pSynced;
pPg != null && ( pPg.nRef != 0 || ( pPg.flags & PGHDR_NEED_SYNC ) != 0 );
pPg = pPg.pDirtyPrev
) ;
pCache.pSynced = pPg;
if ( null == pPg )
{
for ( pPg = pCache.pDirtyTail; pPg != null && pPg.nRef != 0; pPg = pPg.pDirtyPrev ) ;
}
if ( pPg != null )
{
int rc;
rc = pCache.xStress( pCache.pStress, pPg );
if ( rc != SQLITE_OK && rc != SQLITE_BUSY )
{
return rc;
}
}
pPage = sqlite3GlobalConfig.pcache.xFetch( pCache.pCache, pgno, 2 );
}
if ( pPage != null )
{
if ( null == pPage.pData )
{
//memset( pPage, 0, sizeof( PgHdr ) + pCache.szExtra );
pPage.pData = sqlite3Malloc(pCache.szPage);
//pPage.pExtra = (void*)&pPage[1];
//pPage.pData = (void*)&( (char*)pPage )[sizeof( PgHdr ) + pCache.szExtra];
pPage.pCache = pCache;
pPage.pgno = pgno;
}
Debug.Assert( pPage.pCache == pCache );
Debug.Assert( pPage.pgno == pgno );
//Debug.Assert( pPage.pExtra == (void*)&pPage[1] );
if ( 0 == pPage.nRef )
{
pCache.nRef++;
}
pPage.nRef++;
if ( pgno == 1 )
{
pCache.pPage1 = pPage;
}
}
ppPage = pPage;
return ( pPage == null && eCreate != 0 ) ? SQLITE_NOMEM : SQLITE_OK;
}
/*
** Decrement the reference count on a page. If the page is clean and the
** reference count drops to 0, then it is made elible for recycling.
*/
static void sqlite3PcacheRelease( PgHdr p )
{
Debug.Assert( p.nRef > 0 );
p.nRef--;
if ( p.nRef == 0 )
{
PCache pCache = p.pCache;
pCache.nRef--;
if ( ( p.flags & PGHDR_DIRTY ) == 0 )
{
pcacheUnpin( p );
}
else
{
/* Move the page to the head of the dirty list. */
pcacheRemoveFromDirtyList( p );
pcacheAddToDirtyList( p );
}
}
}
/*
** Increase the reference count of a supplied page by 1.
*/
static void sqlite3PcacheRef( PgHdr p )
{
Debug.Assert( p.nRef > 0 );
p.nRef++;
}
/*
** Drop a page from the cache. There must be exactly one reference to the
** page. This function deletes that reference, so after it returns the
** page pointed to by p is invalid.
*/
static void sqlite3PcacheDrop( PgHdr p )
{
PCache pCache;
Debug.Assert( p.nRef == 1 );
if ( ( p.flags & PGHDR_DIRTY ) != 0 )
{
pcacheRemoveFromDirtyList( p );
}
pCache = p.pCache;
pCache.nRef--;
if ( p.pgno == 1 )
{
pCache.pPage1 = null;
}
sqlite3GlobalConfig.pcache.xUnpin( pCache.pCache, p, 1 );
}
/*
** Make sure the page is marked as dirty. If it isn't dirty already,
** make it so.
*/
static void sqlite3PcacheMakeDirty( PgHdr p )
{
p.flags &= ~PGHDR_DONT_WRITE;
Debug.Assert( p.nRef > 0 );
if ( 0 == ( p.flags & PGHDR_DIRTY ) )
{
p.flags |= PGHDR_DIRTY;
pcacheAddToDirtyList( p );
}
}
/*
** Make sure the page is marked as clean. If it isn't clean already,
** make it so.
*/
static void sqlite3PcacheMakeClean( PgHdr p )
{
if ( ( p.flags & PGHDR_DIRTY ) != 0 )
{
pcacheRemoveFromDirtyList( p );
p.flags &= ~( PGHDR_DIRTY | PGHDR_NEED_SYNC );
if ( p.nRef == 0 )
{
pcacheUnpin( p );
}
}
}
/*
** Make every page in the cache clean.
*/
static void sqlite3PcacheCleanAll( PCache pCache )
{
PgHdr p;
while ( ( p = pCache.pDirty ) != null )
{
sqlite3PcacheMakeClean( p );
}
}
/*
** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
*/
static void sqlite3PcacheClearSyncFlags( PCache pCache )
{
PgHdr p;
for ( p = pCache.pDirty; p != null; p = p.pDirtyNext )
{
p.flags &= ~PGHDR_NEED_SYNC;
}
pCache.pSynced = pCache.pDirtyTail;
}
/*
** Change the page number of page p to newPgno.
*/
static void sqlite3PcacheMove( PgHdr p, Pgno newPgno )
{
PCache pCache = p.pCache;
Debug.Assert( p.nRef > 0 );
Debug.Assert( newPgno > 0 );
sqlite3GlobalConfig.pcache.xRekey( pCache.pCache, p, p.pgno, newPgno );
p.pgno = newPgno;
if ( ( p.flags & PGHDR_DIRTY ) != 0 && ( p.flags & PGHDR_NEED_SYNC ) != 0 )
{
pcacheRemoveFromDirtyList( p );
pcacheAddToDirtyList( p );
}
}
/*
** Drop every cache entry whose page number is greater than "pgno". The
** caller must ensure that there are no outstanding references to any pages
** other than page 1 with a page number greater than pgno.
**
** If there is a reference to page 1 and the pgno parameter passed to this
** function is 0, then the data area associated with page 1 is zeroed, but
** the page object is not dropped.
*/
static void sqlite3PcacheTruncate( PCache pCache, u32 pgno )
{
if ( pCache.pCache != null )
{
PgHdr p;
PgHdr pNext;
for ( p = pCache.pDirty; p != null; p = pNext )
{
pNext = p.pDirtyNext;
if ( p.pgno > pgno )
{
Debug.Assert( ( p.flags & PGHDR_DIRTY ) != 0 );
sqlite3PcacheMakeClean( p );
}
}
if ( pgno == 0 && pCache.pPage1 != null )
{
// memset( pCache.pPage1.pData, 0, pCache.szPage );
pCache.pPage1.pData = sqlite3Malloc(pCache.szPage);
pgno = 1;
}
sqlite3GlobalConfig.pcache.xTruncate( pCache.pCache, pgno + 1 );
}
}
/*
** Close a cache.
*/
static void sqlite3PcacheClose( PCache pCache )
{
if ( pCache.pCache != null )
{
sqlite3GlobalConfig.pcache.xDestroy( ref pCache.pCache );
}
}
/*
** Discard the contents of the cache.
*/
static void sqlite3PcacheClear( PCache pCache )
{
sqlite3PcacheTruncate( pCache, 0 );
}
/*
** Merge two lists of pages connected by pDirty and in pgno order.
** Do not both fixing the pDirtyPrev pointers.
*/
static PgHdr pcacheMergeDirtyList( PgHdr pA, PgHdr pB )
{
PgHdr result = new PgHdr();
PgHdr pTail = result;
while ( pA != null && pB != null )
{
if ( pA.pgno < pB.pgno )
{
pTail.pDirty = pA;
pTail = pA;
pA = pA.pDirty;
}
else
{
pTail.pDirty = pB;
pTail = pB;
pB = pB.pDirty;
}
}
if ( pA != null )
{
pTail.pDirty = pA;
}
else if ( pB != null )
{
pTail.pDirty = pB;
}
else
{
pTail.pDirty = null;
}
return result.pDirty;
}
/*
** Sort the list of pages in accending order by pgno. Pages are
** connected by pDirty pointers. The pDirtyPrev pointers are
** corrupted by this sort.
**
** Since there cannot be more than 2^31 distinct pages in a database,
** there cannot be more than 31 buckets required by the merge sorter.
** One extra bucket is added to catch overflow in case something
** ever changes to make the previous sentence incorrect.
*/
//#define N_SORT_BUCKET 32
const int N_SORT_BUCKET = 32;
static PgHdr pcacheSortDirtyList( PgHdr pIn )
{
PgHdr[] a; PgHdr p;//a[N_SORT_BUCKET], p;
int i;
a = new PgHdr[N_SORT_BUCKET];//memset(a, 0, sizeof(a));
while ( pIn != null )
{
p = pIn;
pIn = p.pDirty;
p.pDirty = null;
for ( i = 0; ALWAYS( i < N_SORT_BUCKET - 1 ); i++ )
{
if ( a[i] == null )
{
a[i] = p;
break;
}
else
{
p = pcacheMergeDirtyList( a[i], p );
a[i] = null;
}
}
if ( NEVER( i == N_SORT_BUCKET - 1 ) )
{
/* To get here, there need to be 2^(N_SORT_BUCKET) elements in
** the input list. But that is impossible.
*/
a[i] = pcacheMergeDirtyList( a[i], p );
}
}
p = a[0];
for ( i = 1; i < N_SORT_BUCKET; i++ )
{
p = pcacheMergeDirtyList( p, a[i] );
}
return p;
}
/*
** Return a list of all dirty pages in the cache, sorted by page number.
*/
static PgHdr sqlite3PcacheDirtyList( PCache pCache )
{
PgHdr p;
for ( p = pCache.pDirty; p != null; p = p.pDirtyNext )
{
p.pDirty = p.pDirtyNext;
}
return pcacheSortDirtyList( pCache.pDirty );
}
/*
** Return the total number of referenced pages held by the cache.
*/
static int sqlite3PcacheRefCount( PCache pCache )
{
return pCache.nRef;
}
/*
** Return the number of references to the page supplied as an argument.
*/
static int sqlite3PcachePageRefcount( PgHdr p )
{
return p.nRef;
}
/*
** Return the total number of pages in the cache.
*/
static int sqlite3PcachePagecount( PCache pCache )
{
int nPage = 0;
if ( pCache.pCache != null )
{
nPage = sqlite3GlobalConfig.pcache.xPagecount( pCache.pCache );
}
return nPage;
}
#if SQLITE_TEST
/*
** Get the suggested cache-size value.
*/
static int sqlite3PcacheGetCachesize( PCache pCache )
{
return pCache.nMax;
}
#endif
/*
** Set the suggested cache-size value.
*/
static void sqlite3PcacheSetCachesize( PCache pCache, int mxPage )
{
pCache.nMax = mxPage;
if ( pCache.pCache != null )
{
sqlite3GlobalConfig.pcache.xCachesize( pCache.pCache, mxPage );
}
}
#if SQLITE_CHECK_PAGES || (SQLITE_DEBUG)
/*
** For all dirty pages currently in the cache, invoke the specified
** callback. This is only used if the SQLITE_CHECK_PAGES macro is
** defined.
*/
static void sqlite3PcacheIterateDirty( PCache pCache, dxIter xIter )
{
PgHdr pDirty;
for ( pDirty = pCache.pDirty; pDirty != null; pDirty = pDirty.pDirtyNext )
{
xIter( pDirty );
}
}
#endif
}
}
| |
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Platform;
using Avalonia.UnitTests;
using Moq;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class GridSplitterTests
{
public GridSplitterTests()
{
var cursorFactoryImpl = new Mock<IStandardCursorFactory>();
AvaloniaLocator.CurrentMutable.Bind<IStandardCursorFactory>().ToConstant(cursorFactoryImpl.Object);
}
[Fact]
public void Detects_Horizontal_Orientation()
{
GridSplitter splitter;
var grid = new Grid
{
RowDefinitions = new RowDefinitions("*,Auto,*"),
ColumnDefinitions = new ColumnDefinitions("*,*"),
Children =
{
new Border { [Grid.RowProperty] = 0 },
(splitter = new GridSplitter { [Grid.RowProperty] = 1 }),
new Border { [Grid.RowProperty] = 2 }
}
};
var root = new TestRoot { Child = grid };
root.Measure(new Size(100, 300));
root.Arrange(new Rect(0, 0, 100, 300));
Assert.Equal(GridResizeDirection.Rows, splitter.GetEffectiveResizeDirection());
}
[Fact]
public void Detects_Vertical_Orientation()
{
GridSplitter splitter;
var grid = new Grid
{
ColumnDefinitions = new ColumnDefinitions("*,Auto,*"),
RowDefinitions = new RowDefinitions("*,*"),
Children =
{
new Border { [Grid.ColumnProperty] = 0 },
(splitter = new GridSplitter { [Grid.ColumnProperty] = 1 }),
new Border { [Grid.ColumnProperty] = 2 },
}
};
var root = new TestRoot { Child = grid };
root.Measure(new Size(100, 300));
root.Arrange(new Rect(0, 0, 100, 300));
Assert.Equal(GridResizeDirection.Columns, splitter.GetEffectiveResizeDirection());
}
[Fact]
public void Detects_With_Both_Auto()
{
GridSplitter splitter;
var grid = new Grid
{
ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto"),
RowDefinitions = new RowDefinitions("Auto,Auto"),
Children =
{
new Border { [Grid.ColumnProperty] = 0 },
(splitter = new GridSplitter { [Grid.ColumnProperty] = 1 }),
new Border { [Grid.ColumnProperty] = 2 },
}
};
var root = new TestRoot { Child = grid };
root.Measure(new Size(100, 300));
root.Arrange(new Rect(0, 0, 100, 300));
Assert.Equal(GridResizeDirection.Columns, splitter.GetEffectiveResizeDirection());
}
[Fact]
public void In_First_Position_Doesnt_Throw_Exception()
{
GridSplitter splitter;
var grid = new Grid
{
ColumnDefinitions = new ColumnDefinitions("Auto,*,*"),
RowDefinitions = new RowDefinitions("*,*"),
Children =
{
(splitter = new GridSplitter { [Grid.ColumnProperty] = 0 }),
new Border { [Grid.ColumnProperty] = 1 },
new Border { [Grid.ColumnProperty] = 2 },
}
};
var root = new TestRoot { Child = grid };
root.Measure(new Size(100, 300));
root.Arrange(new Rect(0, 0, 100, 300));
splitter.RaiseEvent(
new VectorEventArgs { RoutedEvent = Thumb.DragStartedEvent });
splitter.RaiseEvent(new VectorEventArgs
{
RoutedEvent = Thumb.DragDeltaEvent, Vector = new Vector(100, 1000)
});
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Horizontal_Stays_Within_Constraints(bool showsPreview)
{
var control1 = new Border { [Grid.RowProperty] = 0 };
var splitter = new GridSplitter { [Grid.RowProperty] = 1, ShowsPreview = showsPreview};
var control2 = new Border { [Grid.RowProperty] = 2 };
var rowDefinitions = new RowDefinitions
{
new RowDefinition(1, GridUnitType.Star) { MinHeight = 70, MaxHeight = 110 },
new RowDefinition(GridLength.Auto),
new RowDefinition(1, GridUnitType.Star) { MinHeight = 10, MaxHeight = 140 },
};
var grid = new Grid { RowDefinitions = rowDefinitions, Children = { control1, splitter, control2 } };
var root = new TestRoot
{
Child = new VisualLayerManager
{
Child = grid
}
};
root.Measure(new Size(100, 200));
root.Arrange(new Rect(0, 0, 100, 200));
splitter.RaiseEvent(
new VectorEventArgs { RoutedEvent = Thumb.DragStartedEvent });
splitter.RaiseEvent(new VectorEventArgs
{
RoutedEvent = Thumb.DragDeltaEvent,
Vector = new Vector(0, -100)
});
if (showsPreview)
{
Assert.Equal(rowDefinitions[0].Height, new GridLength(1, GridUnitType.Star));
Assert.Equal(rowDefinitions[2].Height, new GridLength(1, GridUnitType.Star));
}
else
{
Assert.Equal(rowDefinitions[0].Height, new GridLength(70, GridUnitType.Star));
Assert.Equal(rowDefinitions[2].Height, new GridLength(130, GridUnitType.Star));
}
splitter.RaiseEvent(new VectorEventArgs
{
RoutedEvent = Thumb.DragDeltaEvent,
Vector = new Vector(0, 100)
});
if (showsPreview)
{
Assert.Equal(rowDefinitions[0].Height, new GridLength(1, GridUnitType.Star));
Assert.Equal(rowDefinitions[2].Height, new GridLength(1, GridUnitType.Star));
}
else
{
Assert.Equal(rowDefinitions[0].Height, new GridLength(110, GridUnitType.Star));
Assert.Equal(rowDefinitions[2].Height, new GridLength(90, GridUnitType.Star));
}
splitter.RaiseEvent(new VectorEventArgs
{
RoutedEvent = Thumb.DragCompletedEvent
});
Assert.Equal(rowDefinitions[0].Height, new GridLength(110, GridUnitType.Star));
Assert.Equal(rowDefinitions[2].Height, new GridLength(90, GridUnitType.Star));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Vertical_Stays_Within_Constraints(bool showsPreview)
{
var control1 = new Border { [Grid.ColumnProperty] = 0 };
var splitter = new GridSplitter { [Grid.ColumnProperty] = 1, ShowsPreview = showsPreview};
var control2 = new Border { [Grid.ColumnProperty] = 2 };
var columnDefinitions = new ColumnDefinitions
{
new ColumnDefinition(1, GridUnitType.Star) { MinWidth = 10, MaxWidth = 190 },
new ColumnDefinition(GridLength.Auto),
new ColumnDefinition(1, GridUnitType.Star) { MinWidth = 80, MaxWidth = 120 },
};
var grid = new Grid { ColumnDefinitions = columnDefinitions, Children = { control1, splitter, control2 } };
var root = new TestRoot
{
Child = new VisualLayerManager
{
Child = grid
}
};
root.Measure(new Size(200, 100));
root.Arrange(new Rect(0, 0, 200, 100));
splitter.RaiseEvent(
new VectorEventArgs { RoutedEvent = Thumb.DragStartedEvent });
splitter.RaiseEvent(new VectorEventArgs
{
RoutedEvent = Thumb.DragDeltaEvent,
Vector = new Vector(-100, 0)
});
if (showsPreview)
{
Assert.Equal(columnDefinitions[0].Width, new GridLength(1, GridUnitType.Star));
Assert.Equal(columnDefinitions[2].Width, new GridLength(1, GridUnitType.Star));
}
else
{
Assert.Equal(columnDefinitions[0].Width, new GridLength(80, GridUnitType.Star));
Assert.Equal(columnDefinitions[2].Width, new GridLength(120, GridUnitType.Star));
}
splitter.RaiseEvent(new VectorEventArgs
{
RoutedEvent = Thumb.DragDeltaEvent,
Vector = new Vector(100, 0)
});
if (showsPreview)
{
Assert.Equal(columnDefinitions[0].Width, new GridLength(1, GridUnitType.Star));
Assert.Equal(columnDefinitions[2].Width, new GridLength(1, GridUnitType.Star));
}
else
{
Assert.Equal(columnDefinitions[0].Width, new GridLength(120, GridUnitType.Star));
Assert.Equal(columnDefinitions[2].Width, new GridLength(80, GridUnitType.Star));
}
splitter.RaiseEvent(new VectorEventArgs
{
RoutedEvent = Thumb.DragCompletedEvent
});
Assert.Equal(columnDefinitions[0].Width, new GridLength(120, GridUnitType.Star));
Assert.Equal(columnDefinitions[2].Width, new GridLength(80, GridUnitType.Star));
}
[Theory]
[InlineData(Key.Up, 90, 110)]
[InlineData(Key.Down, 110, 90)]
public void Vertical_Keyboard_Input_Can_Move_Splitter(Key key, double expectedHeightFirst, double expectedHeightSecond)
{
var control1 = new Border { [Grid.RowProperty] = 0 };
var splitter = new GridSplitter { [Grid.RowProperty] = 1, KeyboardIncrement = 10d };
var control2 = new Border { [Grid.RowProperty] = 2 };
var rowDefinitions = new RowDefinitions
{
new RowDefinition(1, GridUnitType.Star),
new RowDefinition(GridLength.Auto),
new RowDefinition(1, GridUnitType.Star)
};
var grid = new Grid { RowDefinitions = rowDefinitions, Children = { control1, splitter, control2 } };
var root = new TestRoot
{
Child = grid
};
root.Measure(new Size(200, 200));
root.Arrange(new Rect(0, 0, 200, 200));
splitter.RaiseEvent(new KeyEventArgs
{
RoutedEvent = InputElement.KeyDownEvent,
Key = key
});
Assert.Equal(rowDefinitions[0].Height, new GridLength(expectedHeightFirst, GridUnitType.Star));
Assert.Equal(rowDefinitions[2].Height, new GridLength(expectedHeightSecond, GridUnitType.Star));
}
[Theory]
[InlineData(Key.Left, 90, 110)]
[InlineData(Key.Right, 110, 90)]
public void Horizontal_Keyboard_Input_Can_Move_Splitter(Key key, double expectedWidthFirst, double expectedWidthSecond)
{
var control1 = new Border { [Grid.ColumnProperty] = 0 };
var splitter = new GridSplitter { [Grid.ColumnProperty] = 1, KeyboardIncrement = 10d };
var control2 = new Border { [Grid.ColumnProperty] = 2 };
var columnDefinitions = new ColumnDefinitions
{
new ColumnDefinition(1, GridUnitType.Star),
new ColumnDefinition(GridLength.Auto),
new ColumnDefinition(1, GridUnitType.Star)
};
var grid = new Grid { ColumnDefinitions = columnDefinitions, Children = { control1, splitter, control2 } };
var root = new TestRoot
{
Child = grid
};
root.Measure(new Size(200, 200));
root.Arrange(new Rect(0, 0, 200, 200));
splitter.RaiseEvent(new KeyEventArgs
{
RoutedEvent = InputElement.KeyDownEvent,
Key = key
});
Assert.Equal(columnDefinitions[0].Width, new GridLength(expectedWidthFirst, GridUnitType.Star));
Assert.Equal(columnDefinitions[2].Width, new GridLength(expectedWidthSecond, GridUnitType.Star));
}
[Fact]
public void Pressing_Escape_Key_Cancels_Resizing()
{
var control1 = new Border { [Grid.ColumnProperty] = 0 };
var splitter = new GridSplitter { [Grid.ColumnProperty] = 1, KeyboardIncrement = 10d };
var control2 = new Border { [Grid.ColumnProperty] = 2 };
var columnDefinitions = new ColumnDefinitions
{
new ColumnDefinition(1, GridUnitType.Star),
new ColumnDefinition(GridLength.Auto),
new ColumnDefinition(1, GridUnitType.Star)
};
var grid = new Grid { ColumnDefinitions = columnDefinitions, Children = { control1, splitter, control2 } };
var root = new TestRoot
{
Child = grid
};
root.Measure(new Size(200, 200));
root.Arrange(new Rect(0, 0, 200, 200));
splitter.RaiseEvent(
new VectorEventArgs { RoutedEvent = Thumb.DragStartedEvent });
splitter.RaiseEvent(new VectorEventArgs
{
RoutedEvent = Thumb.DragDeltaEvent,
Vector = new Vector(-100, 0)
});
Assert.Equal(columnDefinitions[0].Width, new GridLength(0, GridUnitType.Star));
Assert.Equal(columnDefinitions[2].Width, new GridLength(200, GridUnitType.Star));
splitter.RaiseEvent(new KeyEventArgs
{
RoutedEvent = InputElement.KeyDownEvent,
Key = Key.Escape
});
Assert.Equal(columnDefinitions[0].Width, new GridLength(1, GridUnitType.Star));
Assert.Equal(columnDefinitions[2].Width, new GridLength(1, GridUnitType.Star));
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Cache.cs" company="Sirenix IVS">
// Copyright (c) 2018 Sirenix IVS
//
// 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.
// </copyright>
//-----------------------------------------------------------------------
namespace Stratus.OdinSerializer.Utilities
{
using System;
using System.Threading;
public interface ICache<out T> : IDisposable
{
T Value { get; }
}
/// <summary>
/// Provides an easy way of claiming and freeing cached values of any non-abstract reference type with a public parameterless constructor.
/// <para />
/// Cached types which implement the <see cref="ICacheNotificationReceiver"/> interface will receive notifications when they are claimed and freed.
/// <para />
/// Only one thread should be holding a given cache instance at a time if <see cref="ICacheNotificationReceiver"/> is implemented, since the invocation of
/// <see cref="ICacheNotificationReceiver.OnFreed()"/> is not thread safe, IE, weird stuff might happen if multiple different threads are trying to free
/// the same cache instance at the same time. This will practically never happen unless you're doing really strange stuff, but the case is documented here.
/// </summary>
/// <typeparam name="T">The type which is cached.</typeparam>
/// <seealso cref="System.IDisposable" />
public sealed class Cache<T> : ICache<T> where T : class, new()
{
private static readonly bool IsNotificationReceiver = typeof(ICacheNotificationReceiver).IsAssignableFrom(typeof(T));
private static object[] FreeValues = new object[4];
private bool isFree;
private static volatile int THREAD_LOCK_TOKEN = 0;
private static int maxCacheSize = 5;
/// <summary>
/// Gets or sets the maximum size of the cache. This value can never go beneath 1.
/// </summary>
/// <value>
/// The maximum size of the cache.
/// </value>
public static int MaxCacheSize
{
get
{
return Cache<T>.maxCacheSize;
}
set
{
Cache<T>.maxCacheSize = Math.Max(1, value);
}
}
private Cache()
{
this.Value = new T();
this.isFree = false;
}
/// <summary>
/// The cached value.
/// </summary>
public T Value;
/// <summary>
/// Gets a value indicating whether this cached value is free.
/// </summary>
/// <value>
/// <c>true</c> if this cached value is free; otherwise, <c>false</c>.
/// </value>
public bool IsFree { get { return this.isFree; } }
T ICache<T>.Value { get { return this.Value; } }
/// <summary>
/// Claims a cached value of type <see cref="T"/>.
/// </summary>
/// <returns>A cached value of type <see cref="T"/>.</returns>
public static Cache<T> Claim()
{
Cache<T> result = null;
// Very, very simple spinlock implementation
// this lock will almost never be contested
// and it will never be held for more than
// an instant; therefore, we want to avoid paying
// the lock(object) statement's semaphore
// overhead.
while (true)
{
if (Interlocked.CompareExchange(ref THREAD_LOCK_TOKEN, 1, 0) == 0)
{
break;
}
}
// We now hold the lock
var freeValues = FreeValues;
var length = freeValues.Length;
for (int i = 0; i < length; i++)
{
result = (Cache<T>)freeValues[i];
if (!object.ReferenceEquals(result, null))
{
freeValues[i] = null;
result.isFree = false;
break;
}
}
// Release the lock
THREAD_LOCK_TOKEN = 0;
if (result == null)
{
result = new Cache<T>();
}
if (IsNotificationReceiver)
{
(result.Value as ICacheNotificationReceiver).OnClaimed();
}
return result;
}
/// <summary>
/// Releases a cached value.
/// </summary>
/// <param name="cache">The cached value to release.</param>
/// <exception cref="System.ArgumentNullException">The cached value to release is null.</exception>
public static void Release(Cache<T> cache)
{
if (cache == null)
{
throw new ArgumentNullException("cache");
}
if (cache.isFree) return;
// No need to call this method inside the lock, which might do heavy work
// there is a thread safety hole here, actually - if several different threads
// are trying to free the same cache instance, OnFreed might be called several
// times concurrently for the same cached value.
if (IsNotificationReceiver)
{
(cache.Value as ICacheNotificationReceiver).OnFreed();
}
while (true)
{
if (Interlocked.CompareExchange(ref THREAD_LOCK_TOKEN, 1, 0) == 0)
{
break;
}
}
// We now hold the lock
if (cache.isFree)
{
// Release the lock and leave - job's done already
THREAD_LOCK_TOKEN = 0;
return;
}
cache.isFree = true;
var freeValues = FreeValues;
var length = freeValues.Length;
bool added = false;
for (int i = 0; i < length; i++)
{
if (object.ReferenceEquals(freeValues[i], null))
{
freeValues[i] = cache;
added = true;
break;
}
}
if (!added && length < MaxCacheSize)
{
var newArr = new object[length * 2];
for (int i = 0; i < length; i++)
{
newArr[i] = freeValues[i];
}
newArr[length] = cache;
FreeValues = newArr;
}
// Release the lock
THREAD_LOCK_TOKEN = 0;
}
/// <summary>
/// Performs an implicit conversion from <see cref="Cache{T}"/> to <see cref="T"/>.
/// </summary>
/// <param name="cache">The cache to convert.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator T(Cache<T> cache)
{
if (cache == null)
{
return default(T);
}
return cache.Value;
}
/// <summary>
/// Releases this cached value.
/// </summary>
public void Release()
{
Release(this);
}
/// <summary>
/// Releases this cached value.
/// </summary>
void IDisposable.Dispose()
{
Cache<T>.Release(this);
}
}
}
| |
namespace EIDSS.Reports.Document.Uni.Outbreak
{
partial class OutbreakReport
{
#region 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(OutbreakReport));
this.OutbreakDataSet = new EIDSS.Reports.Document.Uni.Outbreak.OutBreakDataSet();
this.OutbreakReportAdapter = new EIDSS.Reports.Document.Uni.Outbreak.OutBreakDataSetTableAdapters.spRepUniOutbreakReportTableAdapter();
this.OutbreakNotesAdapter = new EIDSS.Reports.Document.Uni.Outbreak.OutBreakDataSetTableAdapters.spRepUniOutbreakNotesReportTableAdapter();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable2 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable4 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable5 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable6 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.LocationCell = new DevExpress.XtraReports.UI.XRTableCell();
this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand();
this.Detail1 = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable3 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.OutbreakDateCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable7 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable8 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell();
this.RelatedReportsCell = new DevExpress.XtraReports.UI.XRTableCell();
this.DetailReport1 = new DevExpress.XtraReports.UI.DetailReportBand();
this.Detail2 = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable10 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell();
this.ReportHeader1 = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.xrTable9 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow14 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow16 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell();
((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.OutbreakDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable6)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable7)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable8)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable10)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable9)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// cellLanguage
//
this.cellLanguage.StylePriority.UseTextAlignment = false;
//
// lblReportName
//
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// Detail
//
this.Detail.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.Detail, "Detail");
this.Detail.StylePriority.UseBorders = false;
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
this.Detail.StylePriority.UseTextAlignment = false;
//
// PageHeader
//
this.PageHeader.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.PageHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable4});
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.StylePriority.UseBorders = false;
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
this.PageHeader.StylePriority.UseTextAlignment = false;
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.StylePriority.UseBorders = false;
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable8,
this.xrTable7,
this.xrTable3,
this.xrTable2,
this.xrTable1});
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.Controls.SetChildIndex(this.tableBaseHeader, 0);
this.ReportHeader.Controls.SetChildIndex(this.xrTable1, 0);
this.ReportHeader.Controls.SetChildIndex(this.xrTable2, 0);
this.ReportHeader.Controls.SetChildIndex(this.xrTable3, 0);
this.ReportHeader.Controls.SetChildIndex(this.xrTable7, 0);
this.ReportHeader.Controls.SetChildIndex(this.xrTable8, 0);
//
// xrPageInfo1
//
resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1");
this.xrPageInfo1.StylePriority.UseBorders = false;
//
// cellReportHeader
//
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
this.cellReportHeader.Weight = 2.4334737611816486D;
//
// cellBaseSite
//
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
this.cellBaseSite.Weight = 2.9098718985042393D;
//
// cellBaseCountry
//
this.cellBaseCountry.Weight = 1.0787583450479124D;
//
// cellBaseLeftHeader
//
this.cellBaseLeftHeader.Weight = 0.90214643196245714D;
//
// tableBaseHeader
//
resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader");
this.tableBaseHeader.StylePriority.UseBorders = false;
this.tableBaseHeader.StylePriority.UseBorderWidth = false;
this.tableBaseHeader.StylePriority.UseFont = false;
this.tableBaseHeader.StylePriority.UsePadding = false;
this.tableBaseHeader.StylePriority.UseTextAlignment = false;
//
// OutbreakDataSet
//
this.OutbreakDataSet.DataSetName = "OutBreakDataSet";
this.OutbreakDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// OutbreakReportAdapter
//
this.OutbreakReportAdapter.ClearBeforeFill = true;
//
// OutbreakNotesAdapter
//
this.OutbreakNotesAdapter.ClearBeforeFill = true;
//
// xrTable1
//
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.Name = "xrTable1";
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1,
this.xrTableRow2});
this.xrTable1.StylePriority.UseTextAlignment = false;
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell1,
this.xrTableCell3});
this.xrTableRow1.Name = "xrTableRow1";
this.xrTableRow1.Weight = 0.80808080808080807D;
//
// xrTableCell1
//
this.xrTableCell1.Name = "xrTableCell1";
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Weight = 0.61224495538937551D;
//
// xrTableCell3
//
this.xrTableCell3.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.OutbreakDataSet, "spRepUniOutbreakReport.OutbreakID", "*{0}*")});
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Name = "xrTableCell3";
this.xrTableCell3.StylePriority.UseFont = false;
this.xrTableCell3.StylePriority.UseTextAlignment = false;
this.xrTableCell3.Weight = 1.224489967274712D;
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell2,
this.xrTableCell4});
this.xrTableRow2.Name = "xrTableRow2";
this.xrTableRow2.Weight = 0.505050505050505D;
//
// xrTableCell2
//
this.xrTableCell2.Name = "xrTableCell2";
this.xrTableCell2.Weight = 0.612244996370904D;
//
// xrTableCell4
//
this.xrTableCell4.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell4.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.OutbreakDataSet, "spRepUniOutbreakReport.OutbreakID")});
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.StylePriority.UseBorders = false;
this.xrTableCell4.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Weight = 1.2244899262931837D;
//
// xrTable2
//
resources.ApplyResources(this.xrTable2, "xrTable2");
this.xrTable2.Name = "xrTable2";
this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow3});
//
// xrTableRow3
//
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell5,
this.xrTableCell6});
this.xrTableRow3.Name = "xrTableRow3";
this.xrTableRow3.Weight = 0.59999981689458715D;
//
// xrTableCell5
//
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
this.xrTableCell5.Weight = 0.90221337434619753D;
//
// xrTableCell6
//
this.xrTableCell6.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.OutbreakDataSet, "spRepUniOutbreakReport.Diagnosis")});
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.StylePriority.UseBorders = false;
this.xrTableCell6.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
this.xrTableCell6.Weight = 3.4284107188894981D;
//
// xrTableRow4
//
this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell7,
this.xrTableCell8});
this.xrTableRow4.Name = "xrTableRow4";
this.xrTableRow4.Weight = 1D;
//
// xrTableCell7
//
this.xrTableCell7.Name = "xrTableCell7";
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
this.xrTableCell7.Weight = 1D;
//
// xrTableCell8
//
this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.OutbreakDataSet, "spRepUniOutbreakReport.OutbreakStatus")});
this.xrTableCell8.Name = "xrTableCell8";
this.xrTableCell8.Weight = 3.4208443271767806D;
//
// xrTable4
//
resources.ApplyResources(this.xrTable4, "xrTable4");
this.xrTable4.Name = "xrTable4";
this.xrTable4.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow5});
//
// xrTableRow5
//
this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell9,
this.xrTableCell12,
this.xrTableCell10,
this.xrTableCell13,
this.xrTableCell11});
this.xrTableRow5.Name = "xrTableRow5";
this.xrTableRow5.Weight = 1D;
//
// xrTableCell9
//
this.xrTableCell9.Name = "xrTableCell9";
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
this.xrTableCell9.Weight = 0.59086841115379507D;
//
// xrTableCell12
//
this.xrTableCell12.Name = "xrTableCell12";
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
this.xrTableCell12.Weight = 0.40286480281218523D;
//
// xrTableCell10
//
this.xrTableCell10.Name = "xrTableCell10";
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
this.xrTableCell10.Weight = 0.32229186000841054D;
//
// xrTableCell13
//
this.xrTableCell13.Name = "xrTableCell13";
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
this.xrTableCell13.Weight = 0.48343778659748843D;
//
// xrTableCell11
//
this.xrTableCell11.Name = "xrTableCell11";
resources.ApplyResources(this.xrTableCell11, "xrTableCell11");
this.xrTableCell11.Weight = 1.2005371394281208D;
//
// xrTable5
//
resources.ApplyResources(this.xrTable5, "xrTable5");
this.xrTable5.Name = "xrTable5";
this.xrTable5.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow10});
//
// xrTableRow10
//
this.xrTableRow10.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell14,
this.xrTableCell15,
this.xrTableCell16,
this.xrTableCell17,
this.LocationCell});
this.xrTableRow10.Name = "xrTableRow10";
this.xrTableRow10.Weight = 1.2D;
//
// xrTableCell14
//
this.xrTableCell14.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable6});
this.xrTableCell14.Name = "xrTableCell14";
this.xrTableCell14.Weight = 0.59086837017226668D;
//
// xrTable6
//
resources.ApplyResources(this.xrTable6, "xrTable6");
this.xrTable6.Name = "xrTable6";
this.xrTable6.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow11,
this.xrTableRow12});
//
// xrTableRow11
//
this.xrTableRow11.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell21});
this.xrTableRow11.Name = "xrTableRow11";
this.xrTableRow11.Weight = 1D;
//
// xrTableCell21
//
this.xrTableCell21.Borders = DevExpress.XtraPrinting.BorderSide.None;
this.xrTableCell21.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepUniOutbreakReport.CaseID", "*{0}*")});
resources.ApplyResources(this.xrTableCell21, "xrTableCell21");
this.xrTableCell21.Name = "xrTableCell21";
this.xrTableCell21.StylePriority.UseBorders = false;
this.xrTableCell21.StylePriority.UseFont = false;
this.xrTableCell21.Weight = 3D;
//
// xrTableRow12
//
this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell19});
this.xrTableRow12.Name = "xrTableRow12";
this.xrTableRow12.Weight = 0.51515151515151514D;
//
// xrTableCell19
//
this.xrTableCell19.Borders = DevExpress.XtraPrinting.BorderSide.None;
this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepUniOutbreakReport.CaseID")});
this.xrTableCell19.Name = "xrTableCell19";
this.xrTableCell19.StylePriority.UseBorders = false;
this.xrTableCell19.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
this.xrTableCell19.Weight = 3D;
//
// xrTableCell15
//
this.xrTableCell15.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepUniOutbreakReport.ActType")});
this.xrTableCell15.Name = "xrTableCell15";
this.xrTableCell15.Weight = 0.40286484379371357D;
//
// xrTableCell16
//
this.xrTableCell16.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepUniOutbreakReport.CaseDate", "{0:dd/MM/yyyy}")});
this.xrTableCell16.Name = "xrTableCell16";
this.xrTableCell16.Weight = 0.32229177804535381D;
//
// xrTableCell17
//
this.xrTableCell17.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepUniOutbreakReport.CaseStatus")});
this.xrTableCell17.Name = "xrTableCell17";
this.xrTableCell17.Weight = 0.48343786856054516D;
//
// LocationCell
//
this.LocationCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepUniOutbreakReport.Location")});
this.LocationCell.Name = "LocationCell";
this.LocationCell.Weight = 1.2005371394281208D;
this.LocationCell.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.LocationCell_BeforePrint);
//
// DetailReport
//
this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail1});
this.DetailReport.DataAdapter = this.OutbreakReportAdapter;
this.DetailReport.DataMember = "spRepUniOutbreakReport";
this.DetailReport.DataSource = this.OutbreakDataSet;
this.DetailReport.Level = 0;
this.DetailReport.Name = "DetailReport";
//
// Detail1
//
this.Detail1.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.Detail1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable5});
resources.ApplyResources(this.Detail1, "Detail1");
this.Detail1.Name = "Detail1";
this.Detail1.StylePriority.UseBorders = false;
this.Detail1.StylePriority.UseTextAlignment = false;
//
// xrTable3
//
resources.ApplyResources(this.xrTable3, "xrTable3");
this.xrTable3.Name = "xrTable3";
this.xrTable3.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow6,
this.xrTableRow8,
this.xrTableRow7});
this.xrTable3.StylePriority.UseTextAlignment = false;
//
// xrTableRow6
//
this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell18,
this.OutbreakDateCell});
this.xrTableRow6.Name = "xrTableRow6";
this.xrTableRow6.Weight = 0.606060606060606D;
//
// xrTableCell18
//
this.xrTableCell18.Name = "xrTableCell18";
this.xrTableCell18.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
this.xrTableCell18.Weight = 0.80711803994842279D;
//
// OutbreakDateCell
//
this.OutbreakDateCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.OutbreakDateCell.Name = "OutbreakDateCell";
this.OutbreakDateCell.StylePriority.UseBorders = false;
this.OutbreakDateCell.StylePriority.UseFont = false;
this.OutbreakDateCell.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.OutbreakDateCell, "OutbreakDateCell");
this.OutbreakDateCell.Weight = 2.2548874001164134D;
//
// xrTableRow8
//
this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell20,
this.xrTableCell24});
this.xrTableRow8.Name = "xrTableRow8";
this.xrTableRow8.Weight = 0.30303030303030309D;
//
// xrTableCell20
//
this.xrTableCell20.Name = "xrTableCell20";
this.xrTableCell20.Weight = 0.80711803994842279D;
//
// xrTableCell24
//
this.xrTableCell24.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "sprepGetBaseParameters.strDateFormat")});
resources.ApplyResources(this.xrTableCell24, "xrTableCell24");
this.xrTableCell24.Name = "xrTableCell24";
this.xrTableCell24.StylePriority.UseFont = false;
this.xrTableCell24.StylePriority.UseTextAlignment = false;
this.xrTableCell24.Weight = 2.2548874001164134D;
//
// xrTableRow7
//
this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell22,
this.xrTableCell23});
this.xrTableRow7.Name = "xrTableRow7";
this.xrTableRow7.Weight = 1.0101010101010102D;
//
// xrTableCell22
//
this.xrTableCell22.Name = "xrTableCell22";
this.xrTableCell22.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
this.xrTableCell22.Weight = 0.80711833622518658D;
//
// xrTableCell23
//
this.xrTableCell23.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell23.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.OutbreakDataSet, "spRepUniOutbreakReport.strOutbreakLocation")});
this.xrTableCell23.Name = "xrTableCell23";
this.xrTableCell23.StylePriority.UseBorders = false;
this.xrTableCell23.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell23, "xrTableCell23");
this.xrTableCell23.Weight = 2.2548871038396494D;
//
// xrTable7
//
resources.ApplyResources(this.xrTable7, "xrTable7");
this.xrTable7.Name = "xrTable7";
this.xrTable7.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow9});
//
// xrTableRow9
//
this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell25,
this.xrTableCell26});
this.xrTableRow9.Name = "xrTableRow9";
this.xrTableRow9.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableRow9, "xrTableRow9");
this.xrTableRow9.Weight = 0.59999981689458715D;
//
// xrTableCell25
//
this.xrTableCell25.Name = "xrTableCell25";
resources.ApplyResources(this.xrTableCell25, "xrTableCell25");
this.xrTableCell25.Weight = 0.90221337434619753D;
//
// xrTableCell26
//
this.xrTableCell26.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell26.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.OutbreakDataSet, "spRepUniOutbreakReport.strDescription")});
this.xrTableCell26.Name = "xrTableCell26";
this.xrTableCell26.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell26, "xrTableCell26");
this.xrTableCell26.Weight = 9.1755108772890281D;
//
// xrTable8
//
resources.ApplyResources(this.xrTable8, "xrTable8");
this.xrTable8.Name = "xrTable8";
this.xrTable8.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow13});
//
// xrTableRow13
//
this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell27,
this.RelatedReportsCell});
this.xrTableRow13.Name = "xrTableRow13";
this.xrTableRow13.Weight = 0.59999981689458715D;
//
// xrTableCell27
//
resources.ApplyResources(this.xrTableCell27, "xrTableCell27");
this.xrTableCell27.Name = "xrTableCell27";
this.xrTableCell27.StylePriority.UseFont = false;
this.xrTableCell27.StylePriority.UseTextAlignment = false;
this.xrTableCell27.Weight = 1.9393135306688358D;
//
// RelatedReportsCell
//
this.RelatedReportsCell.Name = "RelatedReportsCell";
this.RelatedReportsCell.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.RelatedReportsCell, "RelatedReportsCell");
this.RelatedReportsCell.Weight = 2.4815307965079447D;
//
// DetailReport1
//
this.DetailReport1.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail2,
this.ReportHeader1});
this.DetailReport1.DataAdapter = this.OutbreakNotesAdapter;
this.DetailReport1.DataMember = "spRepUniOutbreakNotesReport";
this.DetailReport1.DataSource = this.OutbreakDataSet;
this.DetailReport1.Level = 1;
this.DetailReport1.Name = "DetailReport1";
//
// Detail2
//
this.Detail2.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable10});
resources.ApplyResources(this.Detail2, "Detail2");
this.Detail2.Name = "Detail2";
//
// xrTable10
//
this.xrTable10.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTable10, "xrTable10");
this.xrTable10.Name = "xrTable10";
this.xrTable10.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow15});
this.xrTable10.StylePriority.UseBorders = false;
this.xrTable10.StylePriority.UseTextAlignment = false;
//
// xrTableRow15
//
this.xrTableRow15.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell33,
this.xrTableCell34,
this.xrTableCell29});
this.xrTableRow15.Name = "xrTableRow15";
this.xrTableRow15.Weight = 0.59999981689458715D;
//
// xrTableCell33
//
this.xrTableCell33.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepUniOutbreakNotesReport.strNote")});
this.xrTableCell33.Name = "xrTableCell33";
this.xrTableCell33.Weight = 2.651714749787641D;
//
// xrTableCell34
//
this.xrTableCell34.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepUniOutbreakNotesReport.datNoteDate", "{0:dd/MM/yyyy}")});
this.xrTableCell34.Name = "xrTableCell34";
this.xrTableCell34.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell34, "xrTableCell34");
this.xrTableCell34.Weight = 0.39577807929991043D;
//
// xrTableCell29
//
this.xrTableCell29.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepUniOutbreakNotesReport.strCreatorName")});
this.xrTableCell29.Name = "xrTableCell29";
this.xrTableCell29.StylePriority.UseFont = false;
this.xrTableCell29.StylePriority.UseTextAlignment = false;
this.xrTableCell29.Weight = 1.3733514980892294D;
//
// ReportHeader1
//
this.ReportHeader1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable9});
resources.ApplyResources(this.ReportHeader1, "ReportHeader1");
this.ReportHeader1.Name = "ReportHeader1";
//
// xrTable9
//
resources.ApplyResources(this.xrTable9, "xrTable9");
this.xrTable9.Name = "xrTable9";
this.xrTable9.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow14,
this.xrTableRow16});
this.xrTable9.StylePriority.UseFont = false;
//
// xrTableRow14
//
this.xrTableRow14.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell28});
this.xrTableRow14.Name = "xrTableRow14";
this.xrTableRow14.Weight = 0.59999981689458715D;
//
// xrTableCell28
//
this.xrTableCell28.Name = "xrTableCell28";
this.xrTableCell28.StylePriority.UseFont = false;
this.xrTableCell28.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell28, "xrTableCell28");
this.xrTableCell28.Weight = 4.4208443271767806D;
//
// xrTableRow16
//
this.xrTableRow16.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableRow16.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell32,
this.xrTableCell31,
this.xrTableCell30});
this.xrTableRow16.Name = "xrTableRow16";
this.xrTableRow16.StylePriority.UseBorders = false;
this.xrTableRow16.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableRow16, "xrTableRow16");
this.xrTableRow16.Weight = 0.59999981689458715D;
//
// xrTableCell32
//
this.xrTableCell32.Name = "xrTableCell32";
resources.ApplyResources(this.xrTableCell32, "xrTableCell32");
this.xrTableCell32.Weight = 2.6517145082237246D;
//
// xrTableCell31
//
this.xrTableCell31.Name = "xrTableCell31";
resources.ApplyResources(this.xrTableCell31, "xrTableCell31");
this.xrTableCell31.Weight = 0.39577832086382692D;
//
// xrTableCell30
//
this.xrTableCell30.Name = "xrTableCell30";
resources.ApplyResources(this.xrTableCell30, "xrTableCell30");
this.xrTableCell30.Weight = 1.373351498089229D;
//
// OutbreakReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.DetailReport,
this.DetailReport1});
this.Landscape = true;
this.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.PageHeight = 827;
this.PageWidth = 1169;
this.Version = "11.1";
this.Controls.SetChildIndex(this.DetailReport1, 0);
this.Controls.SetChildIndex(this.DetailReport, 0);
this.Controls.SetChildIndex(this.ReportHeader, 0);
this.Controls.SetChildIndex(this.PageFooter, 0);
this.Controls.SetChildIndex(this.PageHeader, 0);
this.Controls.SetChildIndex(this.Detail, 0);
((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.OutbreakDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable6)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable7)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable8)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable10)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable9)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private OutBreakDataSet OutbreakDataSet;
private OutBreakDataSetTableAdapters.spRepUniOutbreakReportTableAdapter OutbreakReportAdapter;
private OutBreakDataSetTableAdapters.spRepUniOutbreakNotesReportTableAdapter OutbreakNotesAdapter;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTable xrTable4;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTable xrTable2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTable xrTable5;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell LocationCell;
private DevExpress.XtraReports.UI.XRTable xrTable6;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.DetailReportBand DetailReport;
private DevExpress.XtraReports.UI.DetailBand Detail1;
private DevExpress.XtraReports.UI.XRTable xrTable3;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableCell OutbreakDateCell;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell22;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell23;
private DevExpress.XtraReports.UI.XRTable xrTable7;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell25;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell26;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell24;
private DevExpress.XtraReports.UI.XRTable xrTable8;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow13;
private DevExpress.XtraReports.UI.XRTableCell RelatedReportsCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell27;
private DevExpress.XtraReports.UI.DetailReportBand DetailReport1;
private DevExpress.XtraReports.UI.DetailBand Detail2;
private DevExpress.XtraReports.UI.XRTable xrTable10;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell33;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell34;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell29;
private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader1;
private DevExpress.XtraReports.UI.XRTable xrTable9;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell28;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell32;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell31;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell30;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace ODataValidator.RuleEngine.Common
{
#region Namespaces
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
#endregion
/// <summary>
/// Helper class to get server response for given uri string and request Accept header value
/// </summary>
public static class WebHelper
{
/// <summary>
/// Gets response content from uri string and accept header value
/// </summary>
/// <param name="uri">uri pointing to the destination resource</param>
/// <param name="acceptHeader">value of Accept header in request</param>
/// <param name="maximumPayloadSize">maximum size of payload in byte</param>
/// <param name="reqHeaders">collection of Http header to be sent out</param>
/// <returns>Reponse object which contains payload, response headers and status code</returns>
/// <exception cref="ArgumentException">Throws exception when parameter is out of scope</exception>
/// <exception cref="OversizedPayloadException">Throws exception when payload content exceeds the set maximum size</exception>
public static Response Get(Uri uri, string acceptHeader, int maximumPayloadSize, IEnumerable<KeyValuePair<string, string>> reqHeaders)
{
var req = WebRequest.Create(uri);
if (!string.IsNullOrEmpty(uri.UserInfo))
{
req.Credentials = new NetworkCredential(Uri.UnescapeDataString(uri.UserInfo.Split(':')[0]), Uri.UnescapeDataString(uri.UserInfo.Split(':')[1]));
}
var reqHttp = req as HttpWebRequest;
if (!string.IsNullOrEmpty(acceptHeader) && reqHttp != null)
{
reqHttp.Accept = acceptHeader;
}
if (reqHeaders != null && reqHeaders.Any())
{
foreach (var p in reqHeaders)
{
if (!string.IsNullOrEmpty(p.Key))
{
reqHttp.Headers[p.Key] = p.Value;
}
}
}
return WebHelper.Get(reqHttp, maximumPayloadSize);
}
/// <summary>
/// Returns Reponse object from a WebRequest object
/// </summary>
/// <param name="request">WebRequest object for which the response is returned</param>
/// <param name="maximumPayloadSize">maximum size of payload in byte</param>
/// <returns>Reponse object which contains payload, response headers and status code</returns>
/// <exception cref="ArgumentException">Throws exception when parameter is out of scope</exception>
/// <exception cref="OversizedPayloadException">Throws exception when payload content exceeds the set maximum size</exception>
[SuppressMessage("DataWeb.Usage", "AC0013: call WebUtil.GetResponseStream instead of calling the method directly on the HTTP object.", Justification = "interop prefers to interact directly with network")]
public static Response Get(WebRequest request, int maximumPayloadSize)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
try
{
request.Timeout = int.Parse(Constants.WebRequestTimeOut);
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; });
if (DataService.serviceInstance != null)
{
string responseHeaders = string.Empty;
string responsePayload = string.Empty;
HttpStatusCode? statusCode = null;
DataService service = new DataService();
service.HandleRequest(request, out statusCode, out responseHeaders, out responsePayload);
return new Response(statusCode, responseHeaders, responsePayload);
}
else
{
using (WebResponse resp = request.GetResponse())
{
string responseHeaders, responsePayload;
HttpStatusCode? statusCode = WebHelper.ParseResponse(maximumPayloadSize, resp, out responseHeaders, out responsePayload);
return new Response(statusCode, responseHeaders, responsePayload);
}
}
}
catch (WebException wex)
{
try
{
if (wex.Response != null)
{
string responseHeaders, responsePayload;
HttpStatusCode? statusCode = WebHelper.ParseResponse(maximumPayloadSize, wex.Response, out responseHeaders, out responsePayload);
return new Response(statusCode, responseHeaders, responsePayload);
}
}
catch (OversizedPayloadException)
{
return new Response(null, null, null);
}
}
return new Response(null, null, null);
}
/// <summary>
/// Extracts status code, response headers and payload (as string) from a WebResponse object
/// </summary>
/// <param name="maximumPayloadSize">maximum size of payload in bytes</param>
/// <param name="response">WebResponse object containing all the information about the response</param>
/// <param name="responseHeaders">respone header block in WebResponse object</param>
/// <param name="responsePayload">response payload in WebResponse object</param>
/// <returns>http status code if http/https protocol is invloved; otherwise, null</returns>
/// <exception cref="ArgumentException">Throws exception when parameter is out of scope</exception>
/// <exception cref="OversizedPayloadException">Throws exception when payload content exceeds the set maximum size</exception>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "response header and payload are returned values too")]
[SuppressMessage("DataWeb.Usage", "AC0013: call WebUtil.GetResponseStream instead of calling the method directly on the HTTP object.", Justification = "interop prefers to interact directly woth network")]
public static HttpStatusCode? ParseResponse(int maximumPayloadSize, WebResponse response, out string responseHeaders, out string responsePayload)
{
HttpStatusCode? statusCode = null;
responseHeaders = null;
responsePayload = null;
if (response != null)
{
if (maximumPayloadSize <= 0)
{
throw new ArgumentException(Resource.ArgumentNegativeOrZero, "maximumPayloadSize");
}
if (response.ContentLength > maximumPayloadSize)
{
throw new OversizedPayloadException(string.Format(CultureInfo.CurrentCulture, Resource.formatPayloadSizeIsTooBig, response.ContentLength));
}
var headers = response.Headers;
responseHeaders = headers != null ? headers.ToString() : null;
string charset = null;
var httpWebResponse = response as HttpWebResponse;
if (httpWebResponse != null)
{
charset = httpWebResponse.CharacterSet;
statusCode = httpWebResponse.StatusCode;
}
else
{
charset = responseHeaders.GetCharset();
}
string contentType = responseHeaders.GetContentTypeValue();
using (var stream = response.GetResponseStream())
{
responsePayload = WebHelper.GetPayloadString(stream, maximumPayloadSize, charset, contentType);
}
}
return statusCode;
}
/// <summary>
/// Canonicalizes a uri
/// </summary>
/// <param name="uri">uri to be canonicalized</param>
/// <returns>the canonicalized uri</returns>
public static Uri Canonicalize(this Uri uri)
{
Uri canonical = null;
if (uri != null)
{
try
{
string safeUnescaped = uri.GetComponents(UriComponents.AbsoluteUri, UriFormat.SafeUnescaped);
string normalized = Regex.Replace(safeUnescaped, "(?<!:)/+", "/");
canonical = new Uri(normalized);
}
catch (UriFormatException)
{
// does nothing
}
}
return canonical;
}
/// <summary>
/// Get response content using the http POST method.
/// </summary>
/// <param name="request">The odata service request.</param>
/// <returns>Response object which contains payload, response headers and status code.</returns>
public static Response Post(Request request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
var req = WebRequest.Create(new Uri(request.Url));
var httpReq = req as HttpWebRequest;
httpReq.Method = request.HttpMethod;
httpReq.ContentType = request.ContentType;
byte[] reqData = Encoding.UTF8.GetBytes(request.RequestPayload);
httpReq.ContentLength = reqData.Length;
if (request.RequestHeaders != null)
{
foreach (var header in request.RequestHeaders)
{
httpReq.Headers.Add(header.Key, header.Value);
}
}
if (request.RequestPayload != string.Empty)
{
Stream dataStream = httpReq.GetRequestStream();
dataStream.Write(reqData, 0, reqData.Length);
dataStream.Close();
}
return Get(httpReq, request.MaxPayloadSize);
}
#region Based Read/Write Operations (Create, Delete, Search, Update and Batch Ops).
/// <summary>
/// Create an entity and inserts it in an entity-set.
/// </summary>
/// <param name="url">The URL of an entity-set.</param>
/// <param name="entity">An entity data.</param>
/// <param name="requestHeaders">The request headers.</param>
/// <returns>Return the response of creating operation.</returns>
public static Response CreateEntity(string url, string entity, IEnumerable<KeyValuePair<string, string>> requestHeaders = null)
{
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute) || !entity.IsJsonPayload())
{
return null;
}
Request req = new Request();
req.Url = url;
req.HttpMethod = HttpMethod.Post;
req.ContentType = Constants.ContentTypeJson;
req.MaxPayloadSize = RuleEngineSetting.Instance().DefaultMaximumPayloadSize;
req.RequestHeaders = requestHeaders;
req.RequestPayload = entity;
Response resp = Post(req);
return resp;
}
/// <summary>
/// Delete an entity from an entity-set.
/// </summary>
/// <param name="url">The URL of an deleted entity.</param>
/// <param name="requestHeaders">The request headers.</param>
/// <returns>Returns the response of deleting operation.</returns>
public static Response DeleteEntity(string url, IEnumerable<KeyValuePair<string, string>> requestHeaders = null)
{
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
return null;
}
Request req = new Request();
req.Url = url;
req.HttpMethod = HttpMethod.Delete;
req.ContentType = Constants.ContentTypeJson;
req.MaxPayloadSize = RuleEngineSetting.Instance().DefaultMaximumPayloadSize;
req.RequestHeaders = requestHeaders;
req.RequestPayload = string.Empty;
Response resp = Post(req);
return resp;
}
/// <summary>
/// Get an entity from an entity-set.
/// </summary>
/// <param name="url">The URL of an entity in an entity-set.</param>
/// <param name="entityPayload">An entity which was got from entity-set.</param>
/// <param name="requestHeaders">The request headers.</param>
/// <returns>Return the response of getting operation.</returns>
public static Response GetEntity(string url, IEnumerable<KeyValuePair<string, string>> requestHeaders = null)
{
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
return null;
}
var resp = Get(new Uri(url), Constants.V4AcceptHeaderJsonFullMetadata, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, requestHeaders);
return resp;
}
/// <summary>
/// Get the value of the property.
/// </summary>
/// <param name="url">The URL of an property value in an entity.</param>
/// <param name="requestHeaders">The request headers.</param>
/// <returns>Return the response of getting operation.</returns>
public static Response GetPropertyValue(string url, IEnumerable<KeyValuePair<string, string>> requestHeaders = null)
{
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
return null;
}
var resp = Get(new Uri(url), null, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, requestHeaders);
return resp;
}
/// <summary>
/// Send the delta get request with the odata.track-changes prefer header.
/// </summary>
/// <param name="url">The URL to the resources whose change is asked to track.</param>
/// <param name="requestHeaders">The request headers.</param>
/// <returns>Return the response of getting operation.</returns>
public static Response GetDeltaLink(string url, IEnumerable<KeyValuePair<string, string>> requestHeaders = null)
{
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
return null;
}
Uri uri = new Uri(url);
var headers = new WebHeaderCollection();
foreach (var header in requestHeaders)
{
headers.Add(header.Key, header.Value);
}
headers.Add("Prefer", "odata.track-changes");
var req = WebRequest.Create(uri);
if (!string.IsNullOrEmpty(uri.UserInfo))
{
req.Credentials = new NetworkCredential(Uri.UnescapeDataString(uri.UserInfo.Split(':')[0]), Uri.UnescapeDataString(uri.UserInfo.Split(':')[1]));
}
var reqHttp = req as HttpWebRequest;
reqHttp.Headers = headers;
reqHttp.Accept = Constants.V4AcceptHeaderJsonFullMetadata;
return WebHelper.Get(reqHttp, RuleEngineSetting.Instance().DefaultMaximumPayloadSize);
}
/// <summary>
/// Update an entity to an entity-set.
/// </summary>
/// <param name="url">The URL of an entity-set.</param>
/// <param name="entity">An entity data.</param>
/// <param name="httpMethod">The http method.</param>
/// <param name="requestHeaders">The request headers.</param>
/// <returns>Return the response of updating operation.</returns>
public static Response UpdateEntity(string url, string entity, string httpMethod, IEnumerable<KeyValuePair<string, string>> requestHeaders = null)
{
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute) ||
!entity.IsJsonPayload() ||
!(httpMethod == HttpMethod.Put || httpMethod == HttpMethod.Patch))
{
return null;
}
Request req = new Request();
req.Url = url;
req.HttpMethod = httpMethod;
req.ContentType = Constants.ContentTypeJson;
req.MaxPayloadSize = RuleEngineSetting.Instance().DefaultMaximumPayloadSize;
req.RequestHeaders = requestHeaders;
req.RequestPayload = entity;
Response resp = Post(req);
return resp;
}
/// <summary>
/// Upsert an entity to an entity-set.
/// </summary>
/// <param name="url">The URL of an entity-set.</param>
/// <param name="entity">An entity data.</param>
/// <param name="httpMethod">The http method.</param>
/// <param name="requestHeaders">The request headers.</param>
/// <returns>Return the response of upserting operation.</returns>
public static Response UpsertEntity(string url, string entity, string httpMethod, IEnumerable<KeyValuePair<string, string>> requestHeaders = null)
{
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute) ||
!entity.IsJsonPayload() ||
!(httpMethod == HttpMethod.Put || httpMethod == HttpMethod.Patch))
{
return null;
}
Request req = new Request();
req.Url = url;
req.HttpMethod = httpMethod;
req.ContentType = Constants.ContentTypeJson;
req.MaxPayloadSize = RuleEngineSetting.Instance().DefaultMaximumPayloadSize;
req.RequestHeaders = requestHeaders;
req.RequestPayload = entity;
Response resp = Post(req);
return resp;
}
/// <summary>
/// Send a batch request to server.
/// </summary>
/// <param name="serviceUrl">A service document url.</param>
/// <param name="boundary">A boundary flag of batch operations.</param>
/// <param name="requestData">A request data stores all the batch operations.</param>
/// <param name="requestHeaders">The request headers of this batch request.</param>
/// <param name="host">The host of this batch request.</param>
/// <returns>Returns the response of batch operation.</returns>
public static Response BatchOperation(string serviceUrl, string requestData, string boundary, IEnumerable<KeyValuePair<string, string>> requestHeaders = null)
{
if (!Uri.IsWellFormedUriString(serviceUrl, UriKind.Absolute) ||
string.IsNullOrEmpty(requestData) ||
string.IsNullOrEmpty(boundary))
{
return null;
}
Request req = new Request();
req.HttpMethod = HttpMethod.Post;
req.MaxPayloadSize = RuleEngineSetting.Instance().DefaultMaximumPayloadSize;
req.RequestPayload = requestData;
req.Url = serviceUrl.TrimEnd('/') + "/$batch";
req.ContentType = string.Format("multipart/mixed;boundary={0}", boundary);
req.RequestHeaders = requestHeaders;
return WebHelper.Post(req);
}
/// <summary>
/// Gets the content using specified URL for more times utill the following has been happen.
/// 1. The response status code is 200 (OK);
/// 2. Timeout.
/// </summary>
/// <param name="url">The specified URL.</param>
/// <param name="requestHeaders">The request headers.</param>
/// <param name="interval">The time interval between the 2 request. (The default value is 0.1s.)</param>
/// <param name="times">The times of the request will be executed. (The default value is 5.)</param>
/// <param name="response">Output the response.</param>
/// <returns>true: Get the specified content; false: otherwise.</returns>
public static bool GetContent(string url, IEnumerable<KeyValuePair<string, string>> requestHeaders, int interval, int times, out Response response)
{
int loop = 0;
do
{
response = GetEntity(url, requestHeaders);
if (times <= loop++)
{
break;
}
Thread.Sleep(interval);
}
while (response.StatusCode != HttpStatusCode.OK);
return null != response;
}
#endregion
#region Facade methods.
/// <summary>
/// Gets the content using specified URL for more times utill the following has been happen.
/// 1. The response status code is 200 (OK);
/// 2. Timeout.
/// </summary>
/// <param name="url">The specified URL.</param>
/// <param name="requestHeaders">The request headers.</param>
/// <param name="response">Output the response.</param>
/// <returns>true: Get the specified content; false: otherwise.</returns>
public static bool GetContent(string url, IEnumerable<KeyValuePair<string, string>> requestHeaders, out Response response)
{
return WebHelper.GetContent(url, requestHeaders, WebHelper.RequestInterval, WebHelper.RequestTimes, out response);
}
/// <summary>
/// Create an entity with any type and insert it to an entity-set on the service.
/// </summary>
/// <param name="url">The URL of the entity-set on the service.</param>
/// <param name="requestHeaders">The request headers.</param>
/// <param name="entity">The non-media type entity template.</param>
/// <param name="isMediaType">Indicate whether the inserted entity is media type or not.</param>
/// <param name="additionInfos">The addition information.
/// (This output parameter must be qualified with an 'ref' key word.)</param>
/// <returns>Returns the response.</returns>
public static Response CreateEntity(string url, IEnumerable<KeyValuePair<string, string>> requestHeaders, JObject entity, bool isMediaType, ref List<AdditionalInfo> additionalInfos)
{
Response resp = null;
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute) || null == entity)
{
return resp;
}
if (isMediaType)
{
AdditionalInfo additionalInfo = null;
resp = CreateMediaTypeEntity(url, requestHeaders, out additionalInfo);
additionalInfos.RemoveAt(additionalInfos.Count - 1);
additionalInfos.Add(additionalInfo);
}
else
{
resp = CreateEntity(url, entity.ToString(), requestHeaders);
}
return resp;
}
/// <summary>
/// Delete an entity with an odata.etag annotation from an entity-set.
/// </summary>
/// <param name="url">The URL of an deleted entity.</param>
/// <param name="hasEtag">The flag indicates whether the entity has an odata.etag annotation or not.</param>
/// <returns>Returns the response of deleting operation.</returns>
public static Response DeleteEntity(string url, IEnumerable<KeyValuePair<string, string>> requestHeaders, bool hasEtag)
{
var headers = requestHeaders.ToList();
if (hasEtag)
{
headers.Add(new KeyValuePair<string, string>("If-Match", "*"));
}
return WebHelper.DeleteEntity(url, headers);
}
/// <summary>
/// Delete all the entities created by customer.
/// </summary>
/// <param name="additionalInfos">The additional information.</param>
/// <returns>Returns a response list.</returns>
public static List<Response> DeleteEntities(IEnumerable<KeyValuePair<string, string>> requestHeaders, List<AdditionalInfo> additionalInfos)
{
var resp = new List<Response>();
foreach (var info in additionalInfos)
{
resp.Add(WebHelper.DeleteEntity(info.EntityId, requestHeaders, info.HasEtag));
}
return resp;
}
/// <summary>
/// Update an entity with an odata.etag annotation from an entity-set.
/// </summary>
/// <param name="url">The URL of an entity-set.</param>
/// <param name="entity">An entity data.</param>
/// <param name="httpMethod">The http method.</param>
/// <param name="hasEtag">The flag indicates whether the entity has an odata.etag annotation or not.</param>
/// <returns>Return the response of updating operation.</returns>
public static Response UpdateEntity(string url, IEnumerable<KeyValuePair<string, string>> requestHeaders, string entity, string httpMethod, bool hasEtag)
{
var headers = requestHeaders.ToList();
if (hasEtag)
{
headers.Add(new KeyValuePair<string, string>("If-Match", "*"));
}
return WebHelper.UpdateEntity(url, entity, httpMethod, headers);
}
/// <summary>
/// Update an entity a string property.
/// </summary>
/// <param name="url">The URL the property.</param>
/// <param name="requestHeaders">The headers of the request.</param>
/// <param name="hasEtag">The flag indicates whether the entity has an odata.etag annotation or not.</param>
/// <returns>Return the response of updating operation.</returns>
public static Response UpdateAStringProperty(string url, IEnumerable<KeyValuePair<string, string>> requestHeaders, bool hasEtag)
{
var headers = requestHeaders.ToList();
if (hasEtag)
{
headers.Add(new KeyValuePair<string, string>("If-Match", "*"));
}
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
return null;
}
Request req = new Request();
req.Url = url;
req.HttpMethod = HttpMethod.Put;
req.ContentType = Constants.ContentTypeTextPlain;
req.MaxPayloadSize = RuleEngineSetting.Instance().DefaultMaximumPayloadSize;
req.RequestHeaders = headers;
req.RequestPayload = Constants.UpdateData;
Response resp = Post(req);
return resp;
}
/// <summary>
/// Update an entity complex property.
/// </summary>
/// <param name="url">The URL the property.</param>
/// <param name="requestHeaders">The headers of the request.</param>
/// <param name="hasEtag">The flag indicates whether the entity has an odata.etag annotation or not.</param>
/// <param name="propsToUpdate">The properties names of the complex type of the complex property.</param>
/// <returns>Return the response of updating operation.</returns>
public static Response UpdateComplexProperty(string url, IEnumerable<KeyValuePair<string, string>> requestHeaders, JProperty propContent, bool hasEtag, List<string> propsToUpdate)
{
var headers = requestHeaders.ToList();
if (hasEtag)
{
headers.Add(new KeyValuePair<string, string>("If-Match", "*"));
}
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
return null;
}
Request req = new Request();
req.Url = url;
req.HttpMethod = HttpMethod.Patch;
req.ContentType = Constants.ContentTypeJson;
req.MaxPayloadSize = RuleEngineSetting.Instance().DefaultMaximumPayloadSize;
req.RequestHeaders = headers;
JObject updateContent = new JObject();
foreach (var prop in propContent.Value.Children<JProperty>())
{
if (propsToUpdate.Contains(prop.Name))
{
updateContent.Add(prop.Name, Constants.UpdateData);
}
}
req.RequestPayload = updateContent.ToString();
Response resp = Post(req);
return resp;
}
/// <summary>
/// Update an entity collection property.
/// </summary>
/// <param name="url">The URL the property.</param>
/// <param name="requestHeaders">The headers of the request.</param>
/// <param name="propContent">The constructed property content of the request.</param>
/// <param name="hasEtag">The flag indicates whether the entity has an odata.etag annotation or not.</param>
/// <returns>Return the response of updating operation.</returns>
public static Response UpdateCollectionProperty(string url, IEnumerable<KeyValuePair<string, string>> requestHeaders, JProperty propContent, bool hasEtag)
{
var headers = requestHeaders.ToList();
if (hasEtag)
{
headers.Add(new KeyValuePair<string, string>("If-Match", "*"));
}
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
return null;
}
Request req = new Request();
req.Url = url;
req.HttpMethod = HttpMethod.Put;
req.ContentType = Constants.ContentTypeJson;
req.MaxPayloadSize = RuleEngineSetting.Instance().DefaultMaximumPayloadSize;
req.RequestHeaders = headers;
int count = propContent.Value.Count();
JObject updateContent = new JObject();
for (int i = 0; i < count; i++ )
{
propContent.Value[i] = Constants.UpdateData;
}
updateContent.Add("value", propContent.Value);
req.RequestPayload = updateContent.ToString();
Response resp = Post(req);
return resp;
}
/// <summary>
/// Update the media-type entity.
/// </summary>
/// <param name="url">The URL of an entity-set with media-type.</param>
/// <param name="requestHeaders">The request headers.</param>
/// <param name="hasEtag">true, if the entity has etag; false, otherwise.</param>
/// <returns>Returns the response.</returns>
public static Response UpdateMediaTypeEntity(string url, IEnumerable<KeyValuePair<string, string>> requestHeaders, bool hasEtag)
{
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
return null;
}
var headers = requestHeaders.ToList();
if (hasEtag)
{
headers.Add(new KeyValuePair<string, string>("If-Match", "*"));
}
string payload = string.Empty;
var imageResp = UpdateImage(url, headers, WebHelper.ImageUpdatePath);
return new Response(imageResp.StatusCode, imageResp.Headers.ToString(), payload);
}
#endregion
#region Private members.
/// <summary>
/// Indicates the request interval.
/// </summary>
private const int RequestInterval = 100;
/// <summary>
/// Indicates the request times.
/// </summary>
private const int RequestTimes = 5;
/// <summary>
/// Indicates the testing image path.
/// </summary>
private readonly static string ImagePath = AppDomain.CurrentDomain.BaseDirectory + "Images\\ODataValidatorToolLogo.jpg";
private readonly static string ImageUpdatePath = AppDomain.CurrentDomain.BaseDirectory + "Images\\EditImageStream.jpg";
#endregion
#region Private methods.
/// <summary>
/// Read the payload with the specified charset or embedded encoding in xml block if applicable
/// </summary>
/// <param name="stream">payload stream</param>
/// <param name="maximumPayloadSize">maximum payload size in bytes</param>
/// <param name="charset">charset value in content-type header</param>
/// <param name="contentType">content-type value</param>
/// <returns>payload text read using proper encoding</returns>
private static string GetPayloadString(Stream stream, int maximumPayloadSize, string charset, string contentType)
{
byte[] buffer = WebHelper.GetPayloadBytes(stream, maximumPayloadSize);
if (buffer == null || buffer.Length == 0)
{
return null;
}
Encoding encoding = Encoding.Default;
if (!string.IsNullOrEmpty(charset))
{
try
{
encoding = Encoding.GetEncoding(charset);
}
catch (ArgumentException)
{
charset = null;
}
}
if (buffer.Length > 3 && buffer[0] == 0xef && buffer[1] == 0xbb && buffer[2] == 0xbf)
{
buffer[0] = 0x20;
buffer[1] = 0x20;
buffer[2] = 0x20;
}
string responsePayload = encoding.GetString(buffer).TrimStart();
if (string.IsNullOrEmpty(charset))
{
string payloadInEmbbedEncoding;
if (TryReadWithEmbeddedEncoding(buffer, contentType, responsePayload, out payloadInEmbbedEncoding))
{
return payloadInEmbbedEncoding;
}
}
return responsePayload;
}
/// <summary>
/// Read stream into a byte array while limiting the size to the specified maximum
/// </summary>
/// <param name="stream">stream obhect to read from</param>
/// <param name="maximumPayloadSize">the maximum number of bytes to read</param>
/// <returns>byte array</returns>
[SuppressMessage("Microsoft.MSInternal", "CA908:generic method that does not require JIT compilation at runtime", Justification = "no other way to strip byte[] yet")]
private static byte[] GetPayloadBytes(Stream stream, int maximumPayloadSize)
{
if (stream == null)
{
return null;
}
byte[] buffer = new byte[maximumPayloadSize];
int roomLeft = maximumPayloadSize;
int offset = 0;
int count;
while ((count = stream.Read(buffer, offset, roomLeft)) > 0)
{
offset += count;
roomLeft -= count;
}
if (roomLeft == 0 && stream.ReadByte() != -1)
{
throw new OversizedPayloadException(Resource.PayloadSizeIsTooBig);
}
Array.Resize<byte>(ref buffer, offset);
return buffer;
}
/// <summary>
/// Try to read byte arrary into a string using the possibly-existent encoding seeting within
/// </summary>
/// <param name="buffer">byte arrary to read from</param>
/// <param name="contentType">content type of the byte array</param>
/// <param name="contentHint">string of byte array in the default encoding</param>
/// <param name="content">output string of byte array in the embedded encoding</param>
/// <returns>true if content is read using a found valid encoding; otherwise false</returns>
[SuppressMessage("Microsoft.Globalization", "CA1308: replace the call to 'string.ToLowerInvariant()' with String.ToUpperInvariant()'.", Justification = "the comparation targets are in lower case")]
private static bool TryReadWithEmbeddedEncoding(byte[] buffer, string contentType, string contentHint, out string content)
{
if (!string.IsNullOrEmpty(contentType))
{
contentType = contentType.ToLowerInvariant();
switch (contentType)
{
case Constants.ContentTypeXml:
case Constants.ContentTypeAtom:
case Constants.ContentTypeTextXml:
case Constants.ContentTypeJson:
return TryReadXmlUsingEmbeddedEncoding(buffer, contentHint, out content);
}
}
content = null;
return false;
}
/// <summary>
/// Try to read XML content using the embedded encoding
/// </summary>
/// <param name="buffer">byte array of the XML literal</param>
/// <param name="xmlHint">string of the xml literal in the default encoding</param>
/// <param name="xml">output string of the xml literal in the embedded encoding</param>
/// <returns>true if the output is read using a valid embedded encoding; otherwise false</returns>
private static bool TryReadXmlUsingEmbeddedEncoding(byte[] buffer, string xmlHint, out string xml)
{
string charsetEmbedded = null;
charsetEmbedded = xmlHint.GetEmbeddedEncoding();
if (!string.IsNullOrEmpty(charsetEmbedded))
{
try
{
Encoding encoding = Encoding.GetEncoding(charsetEmbedded);
xml = encoding.GetString(buffer);
return true;
}
catch (ArgumentException)
{
// does nothing
}
}
xml = null;
return false;
}
/// <summary>
/// Create an image on an entity-set with media-type.
/// </summary>
/// <param name="url">The URL of an entity-set with media-type.</param>
/// <param name="requestHeaders">The request headers.</param>
/// <param name="imagePath">The local path of an image which will be inserted to server.</param>
/// <returns>Returns the HTTP response.</returns>
private static HttpWebResponse CreateImage(string url, IEnumerable<KeyValuePair<string, string>> requestHeaders, string imagePath)
{
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute) ||
string.IsNullOrEmpty(imagePath))
{
return null;
}
var headers = new WebHeaderCollection();
foreach (var header in requestHeaders)
{
headers.Add(header.Key, header.Value);
}
try
{
byte[] image = File.ReadAllBytes(imagePath);
if (null != image && 0 != image.Length)
{
var req = WebRequest.Create(url) as HttpWebRequest;
req.Method = HttpMethod.Post;
req.Headers = headers;
req.ContentType = Constants.ContentTypeJPEGImage;
req.ContentLength = image.Length;
using (Stream dataStream = req.GetRequestStream())
{
dataStream.Write(image, 0, image.Length);
}
return req.GetResponse() as HttpWebResponse;
}
}
catch (DirectoryNotFoundException ex)
{
throw new DirectoryNotFoundException(ex.Message);
}
catch (FileNotFoundException ex)
{
throw new FileNotFoundException(ex.Message);
}
catch (WebException ex)
{
return ex.Response as HttpWebResponse;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return null;
}
/// <summary>
/// Change an image of the media entity to another image by HTTP put method.
/// </summary>
/// <param name="url">The URL of an entity-set with media-type.</param>
/// <param name="requestHeaders">The request headers.</param>
/// <param name="imagePath">The local path of an image which will be inserted to server.</param>
/// <returns>Returns the HTTP response.</returns>
private static HttpWebResponse UpdateImage(string url, List<KeyValuePair<string, string>> requestHeaders, string imagePath)
{
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute) ||
string.IsNullOrEmpty(imagePath))
{
return null;
}
var headers = new WebHeaderCollection();
foreach (var header in requestHeaders)
{
headers.Add(header.Key, header.Value);
}
try
{
byte[] image = File.ReadAllBytes(imagePath);
if (null != image && 0 != image.Length)
{
var req = WebRequest.Create(url) as HttpWebRequest;
req.Method = HttpMethod.Put;
req.Headers = headers;
req.ContentType = Constants.ContentTypeJPEGImage;
req.ContentLength = image.Length;
using (Stream dataStream = req.GetRequestStream())
{
dataStream.Write(image, 0, image.Length);
}
return req.GetResponse() as HttpWebResponse;
}
}
catch (DirectoryNotFoundException ex)
{
throw new DirectoryNotFoundException(ex.Message);
}
catch (FileNotFoundException ex)
{
throw new FileNotFoundException(ex.Message);
}
catch (WebException ex)
{
return ex.Response as HttpWebResponse;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return null;
}
/// <summary>
/// Create the entity with the media-type.
/// </summary>
/// <param name="url">The URL of an entity-set with media-type.</param>
/// <param name="requestHeaders">The request headers.</param>
/// <param name="additionalInfo">The additional information of the new inserted entity.</param>
/// <returns>Returns the response.</returns>
private static Response CreateMediaTypeEntity(string url, IEnumerable<KeyValuePair<string, string>> requestHeaders, out AdditionalInfo additionalInfo)
{
additionalInfo = null;
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
return null;
}
string payload = string.Empty;
var imageResp = CreateImage(url, requestHeaders, WebHelper.ImagePath);
if (null != imageResp && HttpStatusCode.Created == imageResp.StatusCode)
{
string entity = string.Empty;
using (var sr = new StreamReader(imageResp.GetResponseStream()))
{
string entityId = string.Empty;
string etag = string.Empty;
string mediaEtag = string.Empty;
string mediaReadLink = string.Empty;
string contextURL = string.Empty;
payload = sr.ReadToEnd();
var mediaEntity = JObject.Parse(payload);
var props = mediaEntity.Children<JProperty>();
foreach (var prop in props)
{
if (Constants.OdataV4JsonIdentity == prop.Name)
{
contextURL = prop.Value.ToString();
}
else if (Constants.V4OdataMediaReadLink == prop.Name)
{
mediaReadLink = prop.Value.ToString();
}
else if (Constants.V4OdataId == prop.Name)
{
entityId = prop.Value.ToString();
}
else if (Constants.V4OdataEtag == prop.Name)
{
etag = prop.Value.ToString();
}
else if (prop.Name.Contains(Constants.V4OdataMediaEtag))
{
mediaEtag = prop.Value.ToString();
}
}
if (string.IsNullOrEmpty(entityId))
{
if(!mediaReadLink.StartsWith("http"))
{
entityId = contextURL.Split('$')[0] + mediaReadLink;
}
else
{
entityId = mediaReadLink.Split('$')[0];
}
}
entityId = entityId.Split('$')[0];
additionalInfo = new AdditionalInfo(entityId, etag, mediaEtag);
}
}
return new Response(imageResp.StatusCode, imageResp.Headers.ToString(), payload);
}
#endregion
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using PCSComUtils.Common;
using PCSUtils.Utils;
using PCSComUtils.Common.BO;
using PCSComUtils.PCSExc;
using PCSUtils.Log;
namespace PCSProduction.DCP
{
/// <summary>
/// Summary description for NotConfiguredWC.
/// </summary>
public class NotConfiguredWC : System.Windows.Forms.Form
{
private System.Windows.Forms.Label lblMessage;
private System.Windows.Forms.Button btnClose;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private C1.Win.C1TrueDBGrid.C1TrueDBGrid tgridNotConfiguredWC;
private const string THIS = "PCSProduction.DCP.NotConfiguredWC";
private System.Windows.Forms.ContextMenu ctxmnuClipboard;
private System.Windows.Forms.MenuItem mnuSelectAll;
private System.Windows.Forms.MenuItem mnuCopy;
private DataTable m_dtbNotConfiguredWC;
public NotConfiguredWC(DataTable pdtbNotConfiguredWC) : this ()
{
m_dtbNotConfiguredWC = pdtbNotConfiguredWC;
}
public NotConfiguredWC()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <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.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(NotConfiguredWC));
this.lblMessage = new System.Windows.Forms.Label();
this.btnClose = new System.Windows.Forms.Button();
this.tgridNotConfiguredWC = new C1.Win.C1TrueDBGrid.C1TrueDBGrid();
this.ctxmnuClipboard = new System.Windows.Forms.ContextMenu();
this.mnuSelectAll = new System.Windows.Forms.MenuItem();
this.mnuCopy = new System.Windows.Forms.MenuItem();
((System.ComponentModel.ISupportInitialize)(this.tgridNotConfiguredWC)).BeginInit();
this.SuspendLayout();
//
// lblMessage
//
this.lblMessage.Location = new System.Drawing.Point(6, 6);
this.lblMessage.Name = "lblMessage";
this.lblMessage.Size = new System.Drawing.Size(524, 20);
this.lblMessage.TabIndex = 65;
this.lblMessage.Text = "The following Work Centers have not been configured. Please check before running " +
"DCP";
this.lblMessage.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// btnClose
//
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnClose.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnClose.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnClose.Location = new System.Drawing.Point(470, 324);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(60, 22);
this.btnClose.TabIndex = 64;
this.btnClose.Text = "&Close";
//
// tgridNotConfiguredWC
//
this.tgridNotConfiguredWC.AllowUpdate = false;
this.tgridNotConfiguredWC.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tgridNotConfiguredWC.CaptionHeight = 17;
this.tgridNotConfiguredWC.CollapseColor = System.Drawing.Color.Black;
this.tgridNotConfiguredWC.ContextMenu = this.ctxmnuClipboard;
this.tgridNotConfiguredWC.ExpandColor = System.Drawing.Color.Black;
this.tgridNotConfiguredWC.GroupByCaption = "Drag a column header here to group by that column";
this.tgridNotConfiguredWC.Images.Add(((System.Drawing.Image)(resources.GetObject("resource"))));
this.tgridNotConfiguredWC.Location = new System.Drawing.Point(6, 32);
this.tgridNotConfiguredWC.MarqueeStyle = C1.Win.C1TrueDBGrid.MarqueeEnum.DottedCellBorder;
this.tgridNotConfiguredWC.MultiSelect = C1.Win.C1TrueDBGrid.MultiSelectEnum.None;
this.tgridNotConfiguredWC.Name = "tgridNotConfiguredWC";
this.tgridNotConfiguredWC.PreviewInfo.Location = new System.Drawing.Point(0, 0);
this.tgridNotConfiguredWC.PreviewInfo.Size = new System.Drawing.Size(0, 0);
this.tgridNotConfiguredWC.PreviewInfo.ZoomFactor = 75;
this.tgridNotConfiguredWC.PrintInfo.ShowOptionsDialog = false;
this.tgridNotConfiguredWC.RecordSelectorWidth = 16;
this.tgridNotConfiguredWC.RowDivider.Color = System.Drawing.Color.DarkGray;
this.tgridNotConfiguredWC.RowDivider.Style = C1.Win.C1TrueDBGrid.LineStyleEnum.Single;
this.tgridNotConfiguredWC.RowHeight = 15;
this.tgridNotConfiguredWC.RowSubDividerColor = System.Drawing.Color.DarkGray;
this.tgridNotConfiguredWC.Size = new System.Drawing.Size(524, 284);
this.tgridNotConfiguredWC.TabIndex = 63;
this.tgridNotConfiguredWC.PropBag = "<?xml version=\"1.0\"?><Blob><DataCols><C1DataColumn Level=\"0\" Caption=\"WorkCenterI" +
"D\" DataField=\"WorkCenterID\"><ValueItems /><GroupInfo /></C1DataColumn><C1DataCol" +
"umn Level=\"0\" Caption=\"WorkCenter Code\" DataField=\"Code\"><ValueItems /><GroupInf" +
"o /></C1DataColumn><C1DataColumn Level=\"0\" Caption=\"WorkCenter Name\" DataField=\"" +
"Description\"><ValueItems /><GroupInfo /></C1DataColumn><C1DataColumn Level=\"0\" C" +
"aption=\"Description\" DataField=\"Description\"><ValueItems /><GroupInfo /></C1Data" +
"Column><C1DataColumn Level=\"0\" Caption=\"WorkCenterID\" DataField=\"WorkCenterID\"><" +
"ValueItems /><GroupInfo /></C1DataColumn></DataCols><Styles type=\"C1.Win.C1TrueD" +
"BGrid.Design.ContextWrapper\"><Data>HighlightRow{ForeColor:HighlightText;BackColo" +
"r:Highlight;}Caption{AlignHorz:Center;}Normal{Font:Tahoma, 11world;}Style25{}Sty" +
"le24{}Editor{}Style18{}Style19{}Style14{}Style15{}Style16{AlignHorz:Near;}Style1" +
"7{AlignHorz:Near;}Style10{AlignHorz:Near;}Style11{}OddRow{}Style13{}Style45{}Sty" +
"le12{}Style29{AlignHorz:Near;}Style28{AlignHorz:Near;}Style27{}Style26{}RecordSe" +
"lector{AlignImage:Center;}Footer{}Style23{AlignHorz:Near;}Style22{AlignHorz:Near" +
";}Style21{}Style20{}Group{BackColor:ControlDark;Border:None,,0, 0, 0, 0;AlignVer" +
"t:Center;}Inactive{ForeColor:InactiveCaptionText;BackColor:InactiveCaption;}Even" +
"Row{BackColor:Aqua;}Style6{}Heading{Wrap:True;AlignVert:Center;Border:Raised,,1," +
" 1, 1, 1;ForeColor:ControlText;BackColor:Control;}Style3{}Style4{}Style7{}Style8" +
"{}Style1{}Style5{}Style41{AlignHorz:Near;}Style40{AlignHorz:Near;}Style43{}Filte" +
"rBar{}Style42{}Selected{ForeColor:HighlightText;BackColor:Highlight;}Style44{}St" +
"yle9{}Style38{}Style39{}Style36{}Style37{}Style34{AlignHorz:Near;}Style35{AlignH" +
"orz:Near;}Style32{}Style33{}Style30{}Style31{}Style2{}</Data></Styles><Splits><C" +
"1.Win.C1TrueDBGrid.MergeView Name=\"\" CaptionHeight=\"17\" ColumnCaptionHeight=\"17\"" +
" ColumnFooterHeight=\"17\" MarqueeStyle=\"DottedCellBorder\" RecordSelectorWidth=\"16" +
"\" DefRecSelWidth=\"16\" VerticalScrollGroup=\"1\" HorizontalScrollGroup=\"1\"><ClientR" +
"ect>0, 0, 520, 280</ClientRect><BorderSide>0</BorderSide><CaptionStyle parent=\"S" +
"tyle2\" me=\"Style10\" /><EditorStyle parent=\"Editor\" me=\"Style5\" /><EvenRowStyle p" +
"arent=\"EvenRow\" me=\"Style8\" /><FilterBarStyle parent=\"FilterBar\" me=\"Style13\" />" +
"<FooterStyle parent=\"Footer\" me=\"Style3\" /><GroupStyle parent=\"Group\" me=\"Style1" +
"2\" /><HeadingStyle parent=\"Heading\" me=\"Style2\" /><HighLightRowStyle parent=\"Hig" +
"hlightRow\" me=\"Style7\" /><InactiveStyle parent=\"Inactive\" me=\"Style4\" /><OddRowS" +
"tyle parent=\"OddRow\" me=\"Style9\" /><RecordSelectorStyle parent=\"RecordSelector\" " +
"me=\"Style11\" /><SelectedStyle parent=\"Selected\" me=\"Style6\" /><Style parent=\"Nor" +
"mal\" me=\"Style1\" /><internalCols><C1DisplayColumn><HeadingStyle parent=\"Style2\" " +
"me=\"Style16\" /><Style parent=\"Style1\" me=\"Style17\" /><FooterStyle parent=\"Style3" +
"\" me=\"Style18\" /><EditorStyle parent=\"Style5\" me=\"Style19\" /><GroupHeaderStyle p" +
"arent=\"Style1\" me=\"Style21\" /><GroupFooterStyle parent=\"Style1\" me=\"Style20\" /><" +
"ColumnDivider>DarkGray,Single</ColumnDivider><Height>15</Height><DCIdx>0</DCIdx>" +
"</C1DisplayColumn><C1DisplayColumn><HeadingStyle parent=\"Style2\" me=\"Style40\" />" +
"<Style parent=\"Style1\" me=\"Style41\" /><FooterStyle parent=\"Style3\" me=\"Style42\" " +
"/><EditorStyle parent=\"Style5\" me=\"Style43\" /><GroupHeaderStyle parent=\"Style1\" " +
"me=\"Style45\" /><GroupFooterStyle parent=\"Style1\" me=\"Style44\" /><ColumnDivider>D" +
"arkGray,Single</ColumnDivider><Width>104</Width><Height>15</Height><DCIdx>4</DCI" +
"dx></C1DisplayColumn><C1DisplayColumn><HeadingStyle parent=\"Style2\" me=\"Style22\"" +
" /><Style parent=\"Style1\" me=\"Style23\" /><FooterStyle parent=\"Style3\" me=\"Style2" +
"4\" /><EditorStyle parent=\"Style5\" me=\"Style25\" /><GroupHeaderStyle parent=\"Style" +
"1\" me=\"Style27\" /><GroupFooterStyle parent=\"Style1\" me=\"Style26\" /><Visible>True" +
"</Visible><ColumnDivider>DarkGray,Single</ColumnDivider><Width>123</Width><Heigh" +
"t>15</Height><DCIdx>1</DCIdx></C1DisplayColumn><C1DisplayColumn><HeadingStyle pa" +
"rent=\"Style2\" me=\"Style28\" /><Style parent=\"Style1\" me=\"Style29\" /><FooterStyle " +
"parent=\"Style3\" me=\"Style30\" /><EditorStyle parent=\"Style5\" me=\"Style31\" /><Grou" +
"pHeaderStyle parent=\"Style1\" me=\"Style33\" /><GroupFooterStyle parent=\"Style1\" me" +
"=\"Style32\" /><Visible>True</Visible><ColumnDivider>DarkGray,Single</ColumnDivide" +
"r><Width>251</Width><Height>15</Height><DCIdx>2</DCIdx></C1DisplayColumn><C1Disp" +
"layColumn><HeadingStyle parent=\"Style2\" me=\"Style34\" /><Style parent=\"Style1\" me" +
"=\"Style35\" /><FooterStyle parent=\"Style3\" me=\"Style36\" /><EditorStyle parent=\"St" +
"yle5\" me=\"Style37\" /><GroupHeaderStyle parent=\"Style1\" me=\"Style39\" /><GroupFoot" +
"erStyle parent=\"Style1\" me=\"Style38\" /><Visible>True</Visible><ColumnDivider>Dar" +
"kGray,Single</ColumnDivider><Width>174</Width><Height>15</Height><DCIdx>3</DCIdx" +
"></C1DisplayColumn></internalCols></C1.Win.C1TrueDBGrid.MergeView></Splits><Name" +
"dStyles><Style parent=\"\" me=\"Normal\" /><Style parent=\"Normal\" me=\"Heading\" /><St" +
"yle parent=\"Heading\" me=\"Footer\" /><Style parent=\"Heading\" me=\"Caption\" /><Style" +
" parent=\"Heading\" me=\"Inactive\" /><Style parent=\"Normal\" me=\"Selected\" /><Style " +
"parent=\"Normal\" me=\"Editor\" /><Style parent=\"Normal\" me=\"HighlightRow\" /><Style " +
"parent=\"Normal\" me=\"EvenRow\" /><Style parent=\"Normal\" me=\"OddRow\" /><Style paren" +
"t=\"Heading\" me=\"RecordSelector\" /><Style parent=\"Normal\" me=\"FilterBar\" /><Style" +
" parent=\"Caption\" me=\"Group\" /></NamedStyles><vertSplits>1</vertSplits><horzSpli" +
"ts>1</horzSplits><Layout>Modified</Layout><DefaultRecSelWidth>16</DefaultRecSelW" +
"idth><ClientArea>0, 0, 520, 280</ClientArea><PrintPageHeaderStyle parent=\"\" me=\"" +
"Style14\" /><PrintPageFooterStyle parent=\"\" me=\"Style15\" /></Blob>";
//
// ctxmnuClipboard
//
this.ctxmnuClipboard.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuSelectAll,
this.mnuCopy});
//
// mnuSelectAll
//
this.mnuSelectAll.Index = 0;
this.mnuSelectAll.Text = "Select All";
this.mnuSelectAll.Click += new System.EventHandler(this.mnuSelectAll_Click);
//
// mnuCopy
//
this.mnuCopy.Index = 1;
this.mnuCopy.Text = "Copy";
this.mnuCopy.Click += new System.EventHandler(this.mnuCopy_Click);
//
// NotConfiguredWC
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.btnClose;
this.ClientSize = new System.Drawing.Size(536, 351);
this.Controls.Add(this.lblMessage);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.tgridNotConfiguredWC);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Name = "NotConfiguredWC";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Not Configured Work Centers";
this.Load += new System.EventHandler(this.NotConfiguredWC_Load);
((System.ComponentModel.ISupportInitialize)(this.tgridNotConfiguredWC)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void NotConfiguredWC_Load(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".NotConfiguredWC_Load()";
try
{
Security objSecurity = new Security();
this.Name = THIS;
if (objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0)
{
this.Close();
return;
}
if (m_dtbNotConfiguredWC != null)
{
DataTable dtbLayout = FormControlComponents.StoreGridLayout(tgridNotConfiguredWC);
tgridNotConfiguredWC.DataSource = m_dtbNotConfiguredWC;
FormControlComponents.RestoreGridLayout(tgridNotConfiguredWC,dtbLayout);
}
}
catch (PCSException ex)
{
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
private void mnuSelectAll_Click(object sender, System.EventArgs e)
{
for (int i=0; i < tgridNotConfiguredWC.RowCount; i++)
{
tgridNotConfiguredWC.SelectedRows.Add(i);
}
}
private void mnuCopy_Click(object sender, System.EventArgs e)
{
string strTemp = string.Empty; //string to be copied to the clipboard
if (tgridNotConfiguredWC.SelectedRows.Count > 0 )
{
foreach (int row in tgridNotConfiguredWC.SelectedRows)
{
foreach (C1.Win.C1TrueDBGrid.C1DataColumn col in tgridNotConfiguredWC.SelectedCols)
strTemp = strTemp + col.CellText(row) + "\t";
strTemp = strTemp + "\r\n";
}
} //
System.Windows.Forms.Clipboard.SetDataObject(strTemp, false);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using JetBrains.Metadata.Reader.API;
using JetBrains.Metadata.Reader.Impl;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.ReSharper.Psi.Util;
using JetBrains.ReSharper.UnitTestFramework;
using JetBrains.Util;
using XunitContrib.Runner.ReSharper.RemoteRunner.Tasks;
namespace XunitContrib.Runner.ReSharper.UnitTestProvider
{
public class XunitTestMethodElement : XunitBaseElement, ISerializableUnitTestElement, IEquatable<XunitTestMethodElement>
{
public XunitTestMethodElement(XunitServiceProvider services, UnitTestElementId id,
IClrTypeName typeName, string methodName, string skipReason,
bool isDynamic)
: base(services, id, typeName)
{
MethodName = methodName;
ExplicitReason = skipReason;
IsDynamic = isDynamic;
ShortName = MethodName;
}
public string MethodName { get; private set; }
public bool IsDynamic { get; private set; }
public override string GetPresentation(IUnitTestElement parentElement, bool full)
{
if (full)
return Id.Id;
// parentElement gives us the context this method is being presented in. Normally, it's
// null, which means we display the method name (or baseClass.methodName if the method
// is defined in a concrete base class, to distinguish between the method in the base
// class itself). But when displaying the gutter menu of fake container elements (e.g.
// that represent a test method in an abstract base class), ReSharper lists some of the
// sub-elements (the same method in the concrete derived class) and the name needs to
// be qualified with the parent class, or all of the methods would have the same name!
var inheritedTestMethodContainer = parentElement as XunitInheritedTestMethodContainerElement;
if (inheritedTestMethodContainer != null)
{
var parentTypeName = inheritedTestMethodContainer.TypeName.FullName;
if (!parentTypeName.Equals(TestClass.TypeName.FullName, StringComparison.InvariantCulture))
return string.Format("{0}.{1}", Parent.GetPresentation(), MethodName);
}
return IsTestInParentClass() ? MethodName : string.Format("{0}.{1}", TypeName.ShortName, MethodName);
}
public override UnitTestElementDisposition GetDisposition()
{
var element = GetDeclaredElement();
if (element == null || !element.IsValid())
return UnitTestElementDisposition.InvalidDisposition;
var locations = from declaration in element.GetDeclarations()
let file = declaration.GetContainingFile()
where file != null
select new UnitTestElementLocation(file.GetSourceFile().ToProjectFile(),
declaration.GetNameDocumentRange().TextRange,
declaration.GetDocumentRange().TextRange);
return new UnitTestElementDisposition(locations, this);
}
public override IDeclaredElement GetDeclaredElement()
{
var declaredType = GetDeclaredType();
if (declaredType == null)
return null;
// There is a small opportunity for this to choose the wrong method. If there is more than one
// method with the same name (e.g. by error, or as an overload), this will arbitrarily choose the
// first, whatever that means. Realistically, xunit throws an exception if there is more than
// one method with the same name. We wouldn't know which one to go for anyway, unless we stored
// the parameter types in this class. And that's overkill to fix such an edge case
// TODO: Does this get items from the base type?
var methodName = StripDynamicMethodSuffix(MethodName);
return (from member in declaredType.EnumerateMembers(methodName, declaredType.CaseSensistiveName)
where member is IMethod
select member).FirstOrDefault();
}
private ITypeElement GetDeclaredType()
{
return Services.CachingService.GetTypeElement(Id.Project, TypeName, true, true);
}
private static string StripDynamicMethodSuffix(string methodName)
{
// Slight hack for dynamic methods that don't set a unique name
var startIndex = methodName.IndexOf(" [", StringComparison.Ordinal);
if (startIndex == -1)
return methodName;
return methodName.Substring(0, startIndex);
}
public override IEnumerable<IProjectFile> GetProjectFiles()
{
var declaredType = GetDeclaredType();
if (declaredType != null)
{
var result = (from sourceFile in declaredType.GetSourceFiles()
select sourceFile.ToProjectFile()).ToList();
if (result.Count == 1)
return result;
}
var declaredElement = GetDeclaredElement();
if (declaredElement == null)
return EmptyArray<IProjectFile>.Instance;
return from sourceFile in declaredElement.GetSourceFiles()
select sourceFile.ToProjectFile();
}
public override IList<UnitTestTask> GetTaskSequence(ICollection<IUnitTestElement> explicitElements, IUnitTestRun run)
{
var sequence = TestClass.GetTaskSequence(explicitElements, run);
var classTask = sequence[sequence.Count - 1].RemoteTask as XunitTestClassTask;
sequence.Add(new UnitTestTask(this, new XunitTestMethodTask(classTask, ShortName, explicitElements.Contains(this), IsDynamic)));
return sequence;
}
private XunitTestClassElement TestClass
{
get { return Parent as XunitTestClassElement; }
}
public override string Kind
{
get { return "xUnit.net Test"; }
}
public override UnitTestElementState State
{
get { return base.State; }
set { base.State = (value == UnitTestElementState.Valid && IsDynamic) ? UnitTestElementState.Dynamic : value; }
}
public override bool Equals(IUnitTestElement other)
{
return Equals(other as XunitTestMethodElement);
}
public bool Equals(XunitTestMethodElement other)
{
if (other == null)
return false;
return Equals(Id, other.Id) &&
Equals(TypeName.FullName, other.TypeName.FullName) &&
Equals(MethodName, other.MethodName) &&
IsDynamic == other.IsDynamic;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (XunitTestMethodElement)) return false;
return Equals((XunitTestMethodElement) obj);
}
public override int GetHashCode()
{
unchecked
{
var result = (TypeName.FullName != null ? TypeName.FullName.GetHashCode() : 0);
result = (result*397) ^ (Id.GetHashCode());
result = (result*397) ^ (MethodName != null ? MethodName.GetHashCode() : 0);
return result;
}
}
public void WriteToXml(XmlElement element)
{
element.SetAttribute("typeName", TypeName.FullName);
element.SetAttribute("methodName", MethodName);
element.SetAttribute("skipReason", ExplicitReason);
element.SetAttribute("dynamic", IsDynamic.ToString());
}
internal static IUnitTestElement ReadFromXml(XmlElement parent, IUnitTestElement parentElement, IProject project, string id, UnitTestElementFactory unitTestElementFactory)
{
var testClass = parentElement as XunitTestClassElement;
if (testClass == null)
throw new InvalidOperationException("parentElement should be xUnit.net test class");
var typeName = parent.GetAttribute("typeName");
var methodName = parent.GetAttribute("methodName");
var skipReason = parent.GetAttribute("skipReason");
var isDynamic = parent.GetAttribute("dynamic", false);
// TODO: Save and load traits. Not sure it's really necessary, they get updated when the file is scanned
return unitTestElementFactory.GetOrCreateTestMethod(id, project, testClass, new ClrTypeName(typeName),
methodName, skipReason, new OneToSetMap<string, string>(), isDynamic);
}
public override string ToString()
{
return string.Format("{0} - {1}", GetType().Name, Id);
}
private bool IsTestInParentClass()
{
return TestClass.TypeName.Equals(TypeName);
}
}
}
| |
#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.Globalization;
namespace System
{
/// <summary>
/// HashCodeCombiner
/// </summary>
public class HashCodeCombiner
{
private long _combinedHash;
/// <summary>
/// Initializes a new instance of the <see cref="HashCodeCombiner"/> class.
/// </summary>
public HashCodeCombiner()
{
_combinedHash = 0x1505L;
}
/// <summary>
/// Initializes a new instance of the <see cref="HashCodeCombiner"/> class.
/// </summary>
/// <param name="initialCombinedHash">The initial combined hash.</param>
public HashCodeCombiner(long initialCombinedHash)
{
_combinedHash = initialCombinedHash;
}
/// <summary>
/// Adds the array.
/// </summary>
/// <param name="a">A.</param>
public void AddArray(string[] a)
{
if (a != null)
{
int length = a.Length;
for (int index = 0; index < length; index++)
AddObject(a[index]);
}
}
/// <summary>
/// Adds the case insensitive string.
/// </summary>
/// <param name="s">The s.</param>
public void AddCaseInsensitiveString(string s)
{
if (s != null)
AddInt(StringComparer.OrdinalIgnoreCase.GetHashCode(s));
}
/// <summary>
/// Adds the date time.
/// </summary>
/// <param name="dt">The dt.</param>
public void AddDateTime(System.DateTime dt)
{
AddInt(dt.GetHashCode());
}
///// <summary>
///// Adds the directory.
///// </summary>
///// <param name="directoryName">Name of the directory.</param>
//public void AddDirectory(string directoryName)
//{
// DirectoryInfo info = new DirectoryInfo(directoryName);
// if (info.Exists)
// {
// AddObject(directoryName);
// foreach (FileData data in (IEnumerable)FileEnumerator.Create(directoryName))
// if (data.IsDirectory)
// AddDirectory(data.FullName);
// else
// AddExistingFile(data.FullName);
// AddDateTime(info.CreationTimeUtc);
// AddDateTime(info.LastWriteTimeUtc);
// }
//}
///// <summary>
///// Adds the existing file.
///// </summary>
///// <param name="fileName">Name of the file.</param>
//public void AddExistingFile(string fileName)
//{
// AddInt(StringUtil.GetStringHashCode(fileName));
// FileInfo info = new FileInfo(fileName);
// AddDateTime(info.CreationTimeUtc);
// AddDateTime(info.LastWriteTimeUtc);
// AddFileSize(info.Length);
//}
///// <summary>
///// Adds the file.
///// </summary>
///// <param name="fileName">Name of the file.</param>
//public void AddFile(string fileName)
//{
// if (!FileUtil.FileExists(fileName))
// {
// if (FileUtil.DirectoryExists(fileName))
// AddDirectory(fileName);
// }
// else
// AddExistingFile(fileName);
//}
/// <summary>
/// Adds the size of the file.
/// </summary>
/// <param name="fileSize">Size of the file.</param>
public void AddFileSize(long fileSize)
{
AddInt(fileSize.GetHashCode());
}
/// <summary>
/// Adds the int.
/// </summary>
/// <param name="n">The n.</param>
public void AddInt(int n)
{
_combinedHash = ((_combinedHash << 5) + _combinedHash) ^ n;
}
/// <summary>
/// Adds the object.
/// </summary>
/// <param name="b">if set to <c>true</c> [b].</param>
public void AddObject(bool b)
{
AddInt(b.GetHashCode());
}
/// <summary>
/// Adds the object.
/// </summary>
/// <param name="b">The b.</param>
public void AddObject(byte b)
{
AddInt(b.GetHashCode());
}
/// <summary>
/// Adds the object.
/// </summary>
/// <param name="n">The n.</param>
public void AddObject(int n)
{
AddInt(n);
}
/// <summary>
/// Adds the object.
/// </summary>
/// <param name="l">The l.</param>
public void AddObject(long l)
{
AddInt(l.GetHashCode());
}
/// <summary>
/// Adds the object.
/// </summary>
/// <param name="o">The o.</param>
public void AddObject(object o)
{
if (o != null)
{
AddInt(o.GetHashCode());
}
}
///// <summary>
///// Adds the object.
///// </summary>
///// <param name="s">The s.</param>
//public void AddObject(string s)
//{
// if (s != null)
// AddInt(StringUtil.GetStringHashCode(s));
//}
///// <summary>
///// Adds the resources directory.
///// </summary>
///// <param name="directoryName">Name of the directory.</param>
//public void AddResourcesDirectory(string directoryName)
//{
// DirectoryInfo info = new DirectoryInfo(directoryName);
// if (info.Exists)
// {
// AddObject(directoryName);
// foreach (FileData data in (IEnumerable)FileEnumerator.Create(directoryName))
// {
// if (data.IsDirectory)
// AddResourcesDirectory(data.FullName);
// else
// {
// string fullName = data.FullName;
// if (Util.GetCultureName(fullName) == null)
// AddExistingFile(fullName);
// }
// }
// AddDateTime(info.CreationTimeUtc);
// }
//}
/// <summary>
/// Combines the hash codes.
/// </summary>
/// <param name="h1">The h1.</param>
/// <param name="h2">The h2.</param>
/// <returns></returns>
public static int CombineHashCodes(int h1, int h2)
{
return (((h1 << 5) + h1) ^ h2);
}
/// <summary>
/// Combines the hash codes.
/// </summary>
/// <param name="h1">The h1.</param>
/// <param name="h2">The h2.</param>
/// <param name="h3">The h3.</param>
/// <returns></returns>
public static int CombineHashCodes(int h1, int h2, int h3)
{
return CombineHashCodes(CombineHashCodes(h1, h2), h3);
}
/// <summary>
/// Combines the hash codes.
/// </summary>
/// <param name="h1">The h1.</param>
/// <param name="h2">The h2.</param>
/// <param name="h3">The h3.</param>
/// <param name="h4">The h4.</param>
/// <returns></returns>
public static int CombineHashCodes(int h1, int h2, int h3, int h4)
{
return CombineHashCodes(CombineHashCodes(h1, h2), CombineHashCodes(h3, h4));
}
/// <summary>
/// Combines the hash codes.
/// </summary>
/// <param name="h1">The h1.</param>
/// <param name="h2">The h2.</param>
/// <param name="h3">The h3.</param>
/// <param name="h4">The h4.</param>
/// <param name="h5">The h5.</param>
/// <returns></returns>
public static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5)
{
return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), h5);
}
///// <summary>
///// Gets the directory hash.
///// </summary>
///// <param name="virtualDir">The virtual dir.</param>
///// <returns></returns>
//public static string GetDirectoryHash(VirtualPath virtualDir)
//{
// HashCodeCombiner combiner = new HashCodeCombiner();
// combiner.AddDirectory(virtualDir.MapPathInternal());
// return combiner.CombinedHashString;
//}
/// <summary>
/// Gets the combined hash.
/// </summary>
/// <value>The combined hash.</value>
public long CombinedHash
{
get { return _combinedHash; }
}
/// <summary>
/// Gets the combined hash32.
/// </summary>
/// <value>The combined hash32.</value>
public int CombinedHash32
{
get { return _combinedHash.GetHashCode(); }
}
/// <summary>
/// Gets the combined hash string.
/// </summary>
/// <value>The combined hash string.</value>
public string CombinedHashString
{
get { return _combinedHash.ToString("x", CultureInfo.InvariantCulture); }
}
}
}
| |
//
// InternetRadioSource.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Hyena;
using Banshee.Base;
using Banshee.Sources;
using Banshee.Streaming;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Configuration;
using Banshee.PlaybackController;
using Banshee.Gui;
using Banshee.Sources.Gui;
namespace Banshee.InternetRadio
{
public class InternetRadioSource : PrimarySource, IDisposable, IBasicPlaybackController
{
private uint ui_id;
public InternetRadioSource () : base (Catalog.GetString ("Radio"), Catalog.GetString ("Radio"), "internet-radio", 52)
{
Properties.SetString ("Icon.Name", "radio");
TypeUniqueId = "internet-radio";
IsLocal = false;
AfterInitialized ();
InterfaceActionService uia_service = ServiceManager.Get<InterfaceActionService> ();
uia_service.GlobalActions.AddImportant (
new ActionEntry ("AddRadioStationAction", Stock.Add,
Catalog.GetString ("Add Station"), null,
Catalog.GetString ("Add a new Internet Radio station or playlist"),
OnAddStation)
);
ui_id = uia_service.UIManager.AddUiFromResource ("GlobalUI.xml");
Properties.SetString ("ActiveSourceUIResource", "ActiveSourceUI.xml");
Properties.Set<bool> ("ActiveSourceUIResourcePropagate", true);
Properties.Set<System.Reflection.Assembly> ("ActiveSourceUIResource.Assembly", typeof(InternetRadioSource).Assembly);
Properties.SetString ("GtkActionPath", "/InternetRadioContextMenu");
Properties.Set<bool> ("Nereid.SourceContentsPropagate", true);
Properties.Set<ISourceContents> ("Nereid.SourceContents", new LazyLoadSourceContents<InternetRadioSourceContents> ());
Properties.Set<string> ("SearchEntryDescription", Catalog.GetString ("Search your stations"));
Properties.SetString ("TrackEditorActionLabel", Catalog.GetString ("Edit Station"));
Properties.Set<InvokeHandler> ("TrackEditorActionHandler", delegate {
ITrackModelSource active_track_model_source =
(ITrackModelSource) ServiceManager.SourceManager.ActiveSource;
if (active_track_model_source.TrackModel.SelectedItems == null ||
active_track_model_source.TrackModel.SelectedItems.Count <= 0) {
return;
}
foreach (TrackInfo track in active_track_model_source.TrackModel.SelectedItems) {
DatabaseTrackInfo station_track = track as DatabaseTrackInfo;
if (station_track != null) {
EditStation (station_track);
return;
}
}
});
Properties.SetString ("TrackView.ColumnControllerXml", String.Format (@"
<column-controller>
<!--<column modify-default=""IndicatorColumn"">
<renderer type=""Banshee.Podcasting.Gui.ColumnCellPodcastStatusIndicator"" />
</column>-->
<add-default column=""IndicatorColumn"" />
<add-default column=""GenreColumn"" />
<column modify-default=""GenreColumn"">
<visible>false</visible>
</column>
<add-default column=""TitleColumn"" />
<column modify-default=""TitleColumn"">
<title>{0}</title>
<long-title>{0}</long-title>
</column>
<add-default column=""ArtistColumn"" />
<column modify-default=""ArtistColumn"">
<title>{1}</title>
<long-title>{1}</long-title>
</column>
<add-default column=""CommentColumn"" />
<column modify-default=""CommentColumn"">
<title>{2}</title>
<long-title>{2}</long-title>
</column>
<add-default column=""RatingColumn"" />
<add-default column=""PlayCountColumn"" />
<add-default column=""LastPlayedColumn"" />
<add-default column=""LastSkippedColumn"" />
<add-default column=""DateAddedColumn"" />
<add-default column=""UriColumn"" />
<sort-column direction=""asc"">genre</sort-column>
</column-controller>",
Catalog.GetString ("Station"),
Catalog.GetString ("Creator"),
Catalog.GetString ("Description")
));
ServiceManager.PlayerEngine.TrackIntercept += OnPlayerEngineTrackIntercept;
//ServiceManager.PlayerEngine.ConnectEvent (OnTrackInfoUpdated, Banshee.MediaEngine.PlayerEvent.TrackInfoUpdated);
TrackEqualHandler = delegate (DatabaseTrackInfo a, TrackInfo b) {
RadioTrackInfo radio_track = b as RadioTrackInfo;
return radio_track != null && DatabaseTrackInfo.TrackEqual (
radio_track.ParentTrack as DatabaseTrackInfo, a);
};
if (new XspfMigrator (this).Migrate ()) {
Reload ();
}
}
public override string GetPluralItemCountString (int count)
{
return Catalog.GetPluralString ("{0} station", "{0} stations", count);
}
protected override IEnumerable<IFilterListModel> CreateFiltersFor (DatabaseSource src)
{
DatabaseQueryFilterModel<string> genre_model = new DatabaseQueryFilterModel<string> (src, src.DatabaseTrackModel, ServiceManager.DbConnection,
Catalog.GetString ("All Genres ({0})"), src.UniqueId, Banshee.Query.BansheeQuery.GenreField, "Genre");
if (this == src) {
this.genre_model = genre_model;
}
yield return genre_model;
}
public override void Dispose ()
{
base.Dispose ();
//ServiceManager.PlayerEngine.DisconnectEvent (OnTrackInfoUpdated);
InterfaceActionService uia_service = ServiceManager.Get<InterfaceActionService> ();
if (uia_service == null) {
return;
}
if (ui_id > 0) {
uia_service.UIManager.RemoveUi (ui_id);
uia_service.GlobalActions.Remove ("AddRadioStationAction");
ui_id = 0;
}
ServiceManager.PlayerEngine.TrackIntercept -= OnPlayerEngineTrackIntercept;
}
// TODO the idea with this is to grab and display cover art when we get updated info
// for a radio station (eg it changes song and lets us know). The problem is I'm not sure
// if that info ever/usually includes the album name, and also we would probably want to mark
// such downloaded/cached cover art as temporary.
/*private void OnTrackInfoUpdated (Banshee.MediaEngine.PlayerEventArgs args)
{
RadioTrackInfo radio_track = ServiceManager.PlaybackController.CurrentTrack as RadioTrackInfo;
if (radio_track != null) {
Banshee.Metadata.MetadataService.Instance.Lookup (radio_track);
}
}*/
private bool OnPlayerEngineTrackIntercept (TrackInfo track)
{
DatabaseTrackInfo station = track as DatabaseTrackInfo;
if (station == null || station.PrimarySource != this) {
return false;
}
new RadioTrackInfo (station).Play ();
return true;
}
private void OnAddStation (object o, EventArgs args)
{
EditStation (null);
}
private void EditStation (DatabaseTrackInfo track)
{
StationEditor editor = new StationEditor (track);
editor.Response += OnStationEditorResponse;
editor.Show ();
}
private void OnStationEditorResponse (object o, ResponseArgs args)
{
StationEditor editor = (StationEditor)o;
bool destroy = true;
try {
if (args.ResponseId == ResponseType.Ok) {
DatabaseTrackInfo track = editor.Track ?? new DatabaseTrackInfo ();
track.PrimarySource = this;
track.IsLive = true;
try {
track.Uri = new SafeUri (editor.StreamUri);
} catch {
destroy = false;
editor.ErrorMessage = Catalog.GetString ("Please provide a valid station URI");
}
if (!String.IsNullOrEmpty (editor.StationCreator)) {
track.ArtistName = editor.StationCreator;
}
track.Comment = editor.Description;
if (!String.IsNullOrEmpty (editor.Genre)) {
track.Genre = editor.Genre;
} else {
destroy = false;
editor.ErrorMessage = Catalog.GetString ("Please provide a station genre");
}
if (!String.IsNullOrEmpty (editor.StationTitle)) {
track.TrackTitle = editor.StationTitle;
track.AlbumTitle = editor.StationTitle;
} else {
destroy = false;
editor.ErrorMessage = Catalog.GetString ("Please provide a station title");
}
track.Rating = editor.Rating;
if (destroy) {
track.Save ();
}
}
} finally {
if (destroy) {
editor.Response -= OnStationEditorResponse;
editor.Destroy ();
}
}
}
#region IBasicPlaybackController implementation
public bool First ()
{
return false;
}
public bool Next (bool restart, bool changeImmediately)
{
/*
* TODO: It should be technically possible to handle changeImmediately=False
* correctly here, but the current implementation is quite hostile.
* For the moment, just SetNextTrack (null), and go on to OpenPlay if
* the engine isn't currently playing.
*/
if (!changeImmediately) {
ServiceManager.PlayerEngine.SetNextTrack ((SafeUri)null);
if (ServiceManager.PlayerEngine.IsPlaying ()) {
return true;
}
}
RadioTrackInfo radio_track = ServiceManager.PlaybackController.CurrentTrack as RadioTrackInfo;
if (radio_track != null && radio_track.PlayNextStream ()) {
return true;
} else {
return false;
}
}
public bool Previous (bool restart)
{
RadioTrackInfo radio_track = ServiceManager.PlaybackController.CurrentTrack as RadioTrackInfo;
if (radio_track != null && radio_track.PlayPreviousStream ()) {
return true;
} else {
return false;
}
}
#endregion
public override bool AcceptsInputFromSource (Source source)
{
return false;
}
public override bool CanDeleteTracks {
get { return false; }
}
public override bool ShowBrowser {
get { return true; }
}
public override bool CanRename {
get { return false; }
}
protected override bool HasArtistAlbum {
get { return false; }
}
public override bool HasViewableTrackProperties {
get { return false; }
}
}
}
| |
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 MusicStore.WebAPI.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.Diagnostics;
using System.Runtime.InteropServices;
using FILE = System.IO.TextWriter;
using i64 = System.Int64;
using u8 = System.Byte;
using u16 = System.UInt16;
using u32 = System.UInt32;
using u64 = System.UInt64;
using unsigned = System.UIntPtr;
using Pgno = System.UInt32;
#if !SQLITE_MAX_VARIABLE_NUMBER
using ynVar = System.Int16;
#else
using ynVar = System.Int32;
#endif
namespace Community.CsharpSqlite
{
using Op = Sqlite3.VdbeOp;
public partial class Sqlite3
{
/*
** 2003 September 6
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This is the header file for information that is private to the
** VDBE. This information used to all be at the top of the single
** source code file "vdbe.c". When that file became too big (over
** 6000 lines long) it was split up into several smaller files and
** this header information was factored out.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2009-12-07 16:39:13 1ed88e9d01e9eda5cbc622e7614277f29bcc551c
**
** $Header$
*************************************************************************
*/
//#if !_VDBEINT_H_
//#define _VDBEINT_H_
/*
** SQL is translated into a sequence of instructions to be
** executed by a virtual machine. Each instruction is an instance
** of the following structure.
*/
//typedef struct VdbeOp Op;
/*
** Boolean values
*/
//typedef unsigned char Bool;
/*
** A cursor is a pointer into a single BTree within a database file.
** The cursor can seek to a BTree entry with a particular key, or
** loop over all entries of the Btree. You can also insert new BTree
** entries or retrieve the key or data from the entry that the cursor
** is currently pointing to.
**
** Every cursor that the virtual machine has open is represented by an
** instance of the following structure.
**
** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
** really a single row that represents the NEW or OLD pseudo-table of
** a row trigger. The data for the row is stored in VdbeCursor.pData and
** the rowid is in VdbeCursor.iKey.
*/
public class VdbeCursor
{
public BtCursor pCursor; /* The cursor structure of the backend */
public int iDb; /* Index of cursor database in db.aDb[] (or -1) */
public i64 lastRowid; /* Last rowid from a Next or NextIdx operation */
public bool zeroed; /* True if zeroed out and ready for reuse */
public bool rowidIsValid; /* True if lastRowid is valid */
public bool atFirst; /* True if pointing to first entry */
public bool useRandomRowid; /* Generate new record numbers semi-randomly */
public bool nullRow; /* True if pointing to a row with no data */
public bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
public bool isTable; /* True if a table requiring integer keys */
public bool isIndex; /* True if an index containing keys only - no data */
public i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
public Btree pBt; /* Separate file holding temporary table */
public int pseudoTableReg; /* Register holding pseudotable content. */
public KeyInfo pKeyInfo; /* Info about index keys needed by index cursors */
public int nField; /* Number of fields in the header */
public int seqCount; /* Sequence counter */
#if !SQLITE_OMIT_VIRTUALTABLE
public sqlite3_vtab_cursor pVtabCursor; /* The cursor for a virtual table */
public readonly sqlite3_module pModule; /* Module for cursor pVtabCursor */
#endif
/* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
** OP_IsUnique opcode on this cursor. */
public int seekResult;
/* Cached information about the header for the data record that the
** cursor is currently pointing to. Only valid if cacheStatus matches
** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
** the cache is out of date.
**
** aRow might point to (ephemeral) data for the current row, or it might
** be NULL.
*/
public u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
public Pgno payloadSize; /* Total number of bytes in the record */
public u32[] aType; /* Type values for all entries in the record */
public u32[] aOffset; /* Cached offsets to the start of each columns data */
public int aRow; /* Pointer to Data for the current row, if all on one page */
public VdbeCursor Copy()
{
return (VdbeCursor)MemberwiseClone();
}
};
//typedef struct VdbeCursor VdbeCursor;
/*
** When a sub-program is executed (OP_Program), a structure of this type
** is allocated to store the current value of the program counter, as
** well as the current memory cell array and various other frame specific
** values stored in the Vdbe struct. When the sub-program is finished,
** these values are copied back to the Vdbe from the VdbeFrame structure,
** restoring the state of the VM to as it was before the sub-program
** began executing.
**
** Frames are stored in a linked list headed at Vdbe.pParent. Vdbe.pParent
** is the parent of the current frame, or zero if the current frame
** is the main Vdbe program.
*/
//typedef struct VdbeFrame VdbeFrame;
public class VdbeFrame
{
public Vdbe v; /* VM this frame belongs to */
public int pc; /* Program Counter */
public Op[] aOp; /* Program instructions */
public int nOp; /* Size of aOp array */
public Mem[] aMem; /* Array of memory cells */
public int nMem; /* Number of entries in aMem */
public VdbeCursor[] apCsr; /* Element of Vdbe cursors */
public u16 nCursor; /* Number of entries in apCsr */
public int token; /* Copy of SubProgram.token */
public int nChildMem; /* Number of memory cells for child frame */
public int nChildCsr; /* Number of cursors for child frame */
public i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
public int nChange; /* Statement changes (Vdbe.nChanges) */
public VdbeFrame pParent; /* Parent of this frame */
//
// Needed for C# Implementation
//
public Mem[] aChildMem; /* Array of memory cells for child frame */
public VdbeCursor[] aChildCsr; /* Array of cursors for child frame */
};
//#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
/*
** A value for VdbeCursor.cacheValid that means the cache is always invalid.
*/
const int CACHE_STALE = 0;
/*
** Internally, the vdbe manipulates nearly all SQL values as Mem
** structures. Each Mem struct may cache multiple representations (string,
** integer etc.) of the same value. A value (and therefore Mem structure)
** has the following properties:
**
** Each value has a manifest type. The manifest type of the value stored
** in a Mem struct is returned by the MemType(Mem*) macro. The type is
** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
** SQLITE_BLOB.
*/
public class Mem
{
public struct union_ip
{
#if DEBUG_CLASS_MEM || DEBUG_CLASS_ALL
public i64 _i; /* First operand */
public i64 i
{
get { return _i; }
set { _i = value; }
}
#else
public i64 i; /* Integer value. */
#endif
public int nZero; /* Used when bit MEM_Zero is set in flags */
public FuncDef pDef; /* Used only when flags==MEM_Agg */
public RowSet pRowSet; /* Used only when flags==MEM_RowSet */
public VdbeFrame pFrame; /* Used when flags==MEM_Frame */
};
public union_ip u;
public double r; /* Real value */
public sqlite3 db; /* The associated database connection */
public string z; /* String value */
public byte[] zBLOB; /* BLOB value */
public int n; /* Number of characters in string value, excluding '\0' */
#if DEBUG_CLASS_MEM || DEBUG_CLASS_ALL
public u16 _flags; /* First operand */
public u16 flags
{
get { return _flags; }
set { _flags = value; }
}
#else
public u16 flags = MEM_Null; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
#endif
public u8 type = SQLITE_NULL; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
public u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
public dxDel xDel; /* If not null, call this function to delete Mem.z */
// Not used under c#
//public string zMalloc; /* Dynamic buffer allocated by sqlite3Malloc() */
public Mem _Mem; /* Used when C# overload Z as MEM space */
public SumCtx _SumCtx; /* Used when C# overload Z as Sum context */
public SubProgram[] _SubProgram;/* Used when C# overload Z as SubProgram*/
public StrAccum _StrAccum; /* Used when C# overload Z as STR context */
public object _MD5Context; /* Used when C# overload Z as MD5 context */
public void CopyTo( Mem ct )
{
ct.u = u;
ct.r = r;
ct.db = db;
ct.z = z;
if ( zBLOB == null ) ct.zBLOB = null;
else
{
ct.zBLOB = sqlite3Malloc( zBLOB.Length );
Buffer.BlockCopy( zBLOB, 0, ct.zBLOB, 0, zBLOB.Length );
}
ct.n = n;
ct.flags = flags;
ct.type = type;
ct.enc = enc;
ct.xDel = xDel;
}
};
/* One or more of the following flags are set to indicate the validOK
** representations of the value stored in the Mem struct.
**
** If the MEM_Null flag is set, then the value is an SQL NULL value.
** No other flags may be set in this case.
**
** If the MEM_Str flag is set then Mem.z points at a string representation.
** Usually this is encoded in the same unicode encoding as the main
** database (see below for exceptions). If the MEM_Term flag is also
** set, then the string is nul terminated. The MEM_Int and MEM_Real
** flags may coexist with the MEM_Str flag.
**
** Multiple of these values can appear in Mem.flags. But only one
** at a time can appear in Mem.type.
*/
//#define MEM_Null 0x0001 /* Value is NULL */
//#define MEM_Str 0x0002 /* Value is a string */
//#define MEM_Int 0x0004 /* Value is an integer */
//#define MEM_Real 0x0008 /* Value is a real number */
//#define MEM_Blob 0x0010 /* Value is a BLOB */
//#define MEM_RowSet 0x0020 /* Value is a RowSet object */
//#define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
//#define MEM_TypeMask 0x00ff /* Mask of type bits */
const int MEM_Null = 0x0001;
const int MEM_Str = 0x0002;
const int MEM_Int = 0x0004;
const int MEM_Real = 0x0008;
const int MEM_Blob = 0x0010;
const int MEM_RowSet = 0x0020;
const int MEM_Frame = 0x0040;
const int MEM_TypeMask = 0x00ff;
/* Whenever Mem contains a valid string or blob representation, one of
** the following flags must be set to determine the memory management
** policy for Mem.z. The MEM_Term flag tells us whether or not the
** string is \000 or \u0000 terminated
// */
//#define MEM_Term 0x0200 /* String rep is nul terminated */
//#define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
//#define MEM_Static 0x0800 /* Mem.z points to a static string */
//#define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
//#define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
//#define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
//#ifdef SQLITE_OMIT_INCRBLOB
// #undef MEM_Zero
// #define MEM_Zero 0x0000
//#endif
const int MEM_Term = 0x0200;
const int MEM_Dyn = 0x0400;
const int MEM_Static = 0x0800;
const int MEM_Ephem = 0x1000;
const int MEM_Agg = 0x2000;
#if !SQLITE_OMIT_INCRBLOB
const int MEM_Zero = 0x4000;
#else
const int MEM_Zero = 0x0000;
#endif
/*
** Clear any existing type flags from a Mem and replace them with f
*/
//#define MemSetTypeFlag(p, f) \
// ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
static void MemSetTypeFlag( Mem p, int f ) { p.flags = (u16)( p.flags & ~( MEM_TypeMask | MEM_Zero ) | f ); }// TODO -- Convert back to inline for speed
#if SQLITE_OMIT_INCRBLOB
//#undef MEM_Zero
#endif
/* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
** additional information about auxiliary information bound to arguments
** of the function. This is used to implement the sqlite3_get_auxdata()
** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data
** that can be associated with a constant argument to a function. This
** allows functions such as "regexp" to compile their constant regular
** expression argument once and reused the compiled code for multiple
** invocations.
*/
public class AuxData
{
public string pAux; /* Aux data for the i-th argument */
public dxDel xDelete; //(void *); /* Destructor for the aux data */
};
public class VdbeFunc : FuncDef
{
public FuncDef pFunc; /* The definition of the function */
public int nAux; /* Number of entries allocated for apAux[] */
public AuxData[] apAux = new AuxData[2]; /* One slot for each function argument */
};
/*
** The "context" argument for a installable function. A pointer to an
** instance of this structure is the first argument to the routines used
** implement the SQL functions.
**
** There is a typedef for this structure in sqlite.h. So all routines,
** even the public interface to SQLite, can use a pointer to this structure.
** But this file is the only place where the internal details of this
** structure are known.
**
** This structure is defined inside of vdbeInt.h because it uses substructures
** (Mem) which are only defined there.
*/
public class sqlite3_context
{
public FuncDef pFunc; /* Pointer to function information. MUST BE FIRST */
public VdbeFunc pVdbeFunc; /* Auxilary data, if created. */
public Mem s = new Mem(); /* The return value is stored here */
public Mem pMem; /* Memory cell used to store aggregate context */
public int isError; /* Error code returned by the function. */
public CollSeq pColl; /* Collating sequence */
};
/*
** A Set structure is used for quick testing to see if a value
** is part of a small set. Sets are used to implement code like
** this:
** x.y IN ('hi','hoo','hum')
*/
//typedef struct Set Set;
public class Set
{
Hash hash; /* A set is just a hash table */
HashElem prev; /* Previously accessed hash elemen */
};
/*
** An instance of the virtual machine. This structure contains the complete
** state of the virtual machine.
**
** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
** is really a pointer to an instance of this structure.
**
** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
** any virtual table method invocations made by the vdbe program. It is
** set to 2 for xDestroy method calls and 1 for all other methods. This
** variable is used for two purposes: to allow xDestroy methods to execute
** "DROP TABLE" statements and to prevent some nasty side effects of
** malloc failure when SQLite is invoked recursively by a virtual table
** method function.
*/
public class Vdbe
{
public sqlite3 db; /* The database connection that owns this statement */
public Vdbe pPrev; /* Linked list of VDBEs with the same Vdbe.db */
public Vdbe pNext; /* Linked list of VDBEs with the same Vdbe.db */
public int nOp; /* Number of instructions in the program */
public int nOpAlloc; /* Number of slots allocated for aOp[] */
public Op[] aOp; /* Space to hold the virtual machine's program */
public int nLabel; /* Number of labels used */
public int nLabelAlloc; /* Number of slots allocated in aLabel[] */
public int[] aLabel; /* Space to hold the labels */
public Mem[] apArg; /* Arguments to currently executing user function */
public Mem[] aColName; /* Column names to return */
public Mem[] pResultSet; /* Pointer to an array of results */
public u16 nResColumn; /* Number of columns in one row of the result set */
public u16 nCursor; /* Number of slots in apCsr[] */
public VdbeCursor[] apCsr; /* One element of this array for each open cursor */
public u8 errorAction; /* Recovery action to do in case of an error */
public u8 okVar; /* True if azVar[] has been initialized */
public ynVar nVar; /* Number of entries in aVar[] */
public Mem[] aVar; /* Values for the OP_Variable opcode. */
public string[] azVar; /* Name of variables */
public u32 magic; /* Magic number for sanity checking */
public int nMem; /* Number of memory locations currently allocated */
public Mem[] aMem; /* The memory locations */
public u32 cacheCtr; /* VdbeCursor row cache generation counter */
public int pc; /* The program counter */
public int rc; /* Value to return */
public string zErrMsg; /* Error message written here */
public int explain; /* True if EXPLAIN present on SQL command */
public bool changeCntOn; /* True to update the change-counter */
public bool expired; /* True if the VM needs to be recompiled */
public u8 runOnlyOnce; /* Automatically expire on reset */
public int minWriteFileFormat; /* Minimum file format for writable database files */
public int inVtabMethod; /* See comments above */
public bool usesStmtJournal; /* True if uses a statement journal */
public bool readOnly; /* True for read-only statements */
public int nChange; /* Number of db changes made since last reset */
public bool isPrepareV2; /* True if prepared with prepare_v2() */
public int btreeMask; /* Bitmask of db.aDb[] entries referenced */
public u64 startTime; /* Time when query started - used for profiling */
public BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
public int[] aCounter = new int[2]; /* Counters used by sqlite3_stmt_status() */
public string zSql = ""; /* Text of the SQL statement that generated this */
public object pFree; /* Free this when deleting the vdbe */
public i64 nFkConstraint; /* Number of imm. FK constraints this VM */
public i64 nStmtDefCons; /* Number of def. constraints when stmt started */
public int iStatement; /* Statement number (or 0 if has not opened stmt) */
#if SQLITE_DEBUG
public FILE trace; /* Write an execution trace here, if not NULL */
#endif
public VdbeFrame pFrame; /* Parent frame */
public int nFrame; /* Number of frames in pFrame list */
public u32 expmask; /* Binding to these vars invalidates VM */
public Vdbe Copy()
{
Vdbe cp = (Vdbe)MemberwiseClone();
return cp;
}
public void CopyTo( Vdbe ct )
{
ct.db = db;
ct.pPrev = pPrev;
ct.pNext = pNext;
ct.nOp = nOp;
ct.nOpAlloc = nOpAlloc;
ct.aOp = aOp;
ct.nLabel = nLabel;
ct.nLabelAlloc = nLabelAlloc;
ct.aLabel = aLabel;
ct.apArg = apArg;
ct.aColName = aColName;
ct.nCursor = nCursor;
ct.apCsr = apCsr;
ct.nVar = nVar;
ct.aVar = aVar;
ct.azVar = azVar;
ct.okVar = okVar;
ct.magic = magic;
ct.nMem = nMem;
ct.aMem = aMem;
ct.cacheCtr = cacheCtr;
ct.pc = pc;
ct.rc = rc;
ct.errorAction = errorAction;
ct.nResColumn = nResColumn;
ct.zErrMsg = zErrMsg;
ct.pResultSet = pResultSet;
ct.explain = explain;
ct.changeCntOn = changeCntOn;
ct.expired = expired;
ct.minWriteFileFormat = minWriteFileFormat;
ct.inVtabMethod = inVtabMethod;
ct.usesStmtJournal = usesStmtJournal;
ct.readOnly = readOnly;
ct.nChange = nChange;
ct.isPrepareV2 = isPrepareV2;
ct.startTime = startTime;
ct.btreeMask = btreeMask;
ct.aMutex = aMutex;
aCounter.CopyTo( ct.aCounter, 0 );
ct.zSql = zSql;
ct.pFree = pFree;
#if SQLITE_DEBUG
ct.trace = trace;
#endif
ct.nFkConstraint = nFkConstraint;
ct.nStmtDefCons = nStmtDefCons;
ct.iStatement = iStatement;
ct.pFrame = pFrame;
ct.nFrame = nFrame;
ct.expmask = expmask;
#if SQLITE_SSE
ct.fetchId=fetchId;
ct.lru=lru;
#endif
#if SQLITE_ENABLE_MEMORY_MANAGEMENT
ct.pLruPrev=pLruPrev;
ct.pLruNext=pLruNext;
#endif
}
};
/*
** The following are allowed values for Vdbe.magic
*/
//#define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
//#define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
//#define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
//#define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
const u32 VDBE_MAGIC_INIT = 0x26bceaa5; /* Building a VDBE program */
const u32 VDBE_MAGIC_RUN = 0xbdf20da3; /* VDBE is ready to execute */
const u32 VDBE_MAGIC_HALT = 0x519c2973; /* VDBE has completed execution */
const u32 VDBE_MAGIC_DEAD = 0xb606c3c8; /* The VDBE has been deallocated */
/*
** Function prototypes
*/
//void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
//void sqliteVdbePopStack(Vdbe*,int);
//int sqlite3VdbeCursorMoveto(VdbeCursor*);
//#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
//void sqlite3VdbePrintOp(FILE*, int, Op*);
//#endif
//u32 sqlite3VdbeSerialTypeLen(u32);
//u32 sqlite3VdbeSerialType(Mem*, int);
//u32sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
//u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
//void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
//int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
//int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
//int sqlite3VdbeIdxRowid(sqlite3 *, i64 *);
//int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
//int sqlite3VdbeExec(Vdbe*);
//int sqlite3VdbeList(Vdbe*);
//int sqlite3VdbeHalt(Vdbe*);
//int sqlite3VdbeChangeEncoding(Mem *, int);
//int sqlite3VdbeMemTooBig(Mem*);
//int sqlite3VdbeMemCopy(Mem*, const Mem*);
//void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
//void sqlite3VdbeMemMove(Mem*, Mem*);
//int sqlite3VdbeMemNulTerminate(Mem*);
//int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
//void sqlite3VdbeMemSetInt64(Mem*, i64);
#if SQLITE_OMIT_FLOATING_POINT
//# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
#else
//void sqlite3VdbeMemSetDouble(Mem*, double);
#endif
//void sqlite3VdbeMemSetNull(Mem*);
//void sqlite3VdbeMemSetZeroBlob(Mem*,int);
//void sqlite3VdbeMemSetRowSet(Mem*);
//int sqlite3VdbeMemMakeWriteable(Mem*);
//int sqlite3VdbeMemStringify(Mem*, int);
//i64 sqlite3VdbeIntValue(Mem*);
//int sqlite3VdbeMemIntegerify(Mem*);
//double sqlite3VdbeRealValue(Mem*);
//void sqlite3VdbeIntegerAffinity(Mem*);
//int sqlite3VdbeMemRealify(Mem*);
//int sqlite3VdbeMemNumerify(Mem*);
//int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
//void sqlite3VdbeMemRelease(Mem p);
//void sqlite3VdbeMemReleaseExternal(Mem p);
//int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
//const char *sqlite3OpcodeName(int);
//int sqlite3VdbeMemGrow(Mem pMem, int n, int preserve);
//int sqlite3VdbeCloseStatement(Vdbe *, int);
//void sqlite3VdbeFrameDelete(VdbeFrame*);
//int sqlite3VdbeFrameRestore(VdbeFrame *);
//void sqlite3VdbeMemStoreType(Mem *pMem);
#if !SQLITE_OMIT_FOREIGN_KEY
//int sqlite3VdbeCheckFk(Vdbe *, int);
#else
//# define sqlite3VdbeCheckFk(p,i) 0
static int sqlite3VdbeCheckFk( Vdbe p, int i ) { return 0; }
#endif
#if !SQLITE_OMIT_SHARED_CACHE
//void sqlite3VdbeMutexArrayEnter(Vdbe *p);
#else
//# define sqlite3VdbeMutexArrayEnter(p)
static void sqlite3VdbeMutexArrayEnter( Vdbe p ) { }
#endif
//int sqlite3VdbeMemTranslate(Mem*, u8);
//#if SQLITE_DEBUG
// void sqlite3VdbePrintSql(Vdbe*);
// void sqlite3VdbeMemPrettyPrint(Mem pMem, char *zBuf);
//#endif
//int sqlite3VdbeMemHandleBom(Mem pMem);
#if !SQLITE_OMIT_INCRBLOB
// int sqlite3VdbeMemExpandBlob(Mem *);
#else
// #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
static int sqlite3VdbeMemExpandBlob( Mem x ) { return SQLITE_OK; }
#endif
//#endif //* !_VDBEINT_H_) */
}
}
| |
using System.ComponentModel;
namespace Simple.Data
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
class PropertySetterBuilder
{
private static readonly MethodInfo DictionaryContainsKeyMethod = typeof(IDictionary<string, object>).GetMethod("ContainsKey", new[] { typeof(string) });
private static readonly PropertyInfo DictionaryIndexerProperty = typeof(IDictionary<string, object>).GetProperty("Item");
private static readonly MethodInfo ToArrayDictionaryMethod = typeof(Enumerable).GetMethod("ToArray",
BindingFlags.Public |
BindingFlags.Static).MakeGenericMethod(typeof(IDictionary<string, object>));
private static readonly MethodInfo ToArrayObjectMethod = typeof(Enumerable).GetMethod("ToArray",
BindingFlags.Public |
BindingFlags.Static).MakeGenericMethod(typeof(object));
private static readonly PropertyInfo ArrayDictionaryLengthProperty =
typeof(IDictionary<string, object>[]).GetProperty("Length");
private static readonly PropertyInfo ArrayObjectLengthProperty =
typeof(object[]).GetProperty("Length");
private readonly ParameterExpression _param;
private readonly ParameterExpression _obj;
private readonly PropertyInfo _property;
private MemberExpression _nameProperty;
private IndexExpression _itemProperty;
private MethodCallExpression _containsKey;
private static readonly MethodInfo CreatorCreateMethod = typeof(ConcreteTypeCreator).GetMethod("Create");
public PropertySetterBuilder(ParameterExpression param, ParameterExpression obj, PropertyInfo property)
{
_param = param;
_obj = obj;
_property = property;
}
public ConditionalExpression CreatePropertySetter()
{
CreatePropertyExpressions();
if (PropertyIsPrimitive())
{
return Expression.IfThen(_containsKey, CreateTrySimpleAssign());
}
if (_property.PropertyType.IsArray)
{
return Expression.IfThen(_containsKey, CreateTrySimpleArrayAssign());
}
if (_property.PropertyType.IsGenericCollection())
{
var collectionCreator = BuildCollectionCreator();
if (collectionCreator != null)
{
return Expression.IfThen(_containsKey, collectionCreator);
}
}
var isDictionary = Expression.TypeIs(_itemProperty, typeof(IDictionary<string, object>));
var tryComplexAssign = Expression.TryCatch(CreateComplexAssign(),
CreateCatchBlock());
var ifThen = Expression.IfThen(_containsKey, // if (dict.ContainsKey(propertyName)) {
Expression.IfThenElse(isDictionary, tryComplexAssign, CreateTrySimpleAssign()));
return ifThen;
}
private Expression BuildArrayCreator()
{
if (!_property.CanWrite) return null;
var genericType = _property.PropertyType.GetGenericArguments().Single();
var creatorInstance = ConcreteTypeCreator.Get(genericType);
var collection = Expression.Variable(_property.PropertyType);
var createCollection = MakeCreateNewCollection(collection, genericType);
if (createCollection == null) return null;
var addMethod = _property.PropertyType.GetMethod("Add");
if (addMethod == null) return null;
return BuildCollectionCreatorExpression(genericType, creatorInstance, collection, createCollection, addMethod);
}
private Expression BuildCollectionCreator()
{
var genericType = _property.PropertyType.GetGenericArguments().Single();
var creatorInstance = ConcreteTypeCreator.Get(genericType);
var collection = Expression.Variable(_property.PropertyType);
BinaryExpression createCollection = null;
if (_property.CanWrite)
{
createCollection = MakeCreateNewCollection(collection, genericType);
}
else
{
createCollection = Expression.Assign(collection, _nameProperty);
}
var addMethod = _property.PropertyType.GetInterfaceMethod("Add");
if (createCollection != null && addMethod != null)
{
return BuildCollectionCreatorExpression(genericType, creatorInstance, collection, createCollection, addMethod);
}
return null;
}
private Expression BuildCollectionCreatorExpression(Type genericType, ConcreteTypeCreator creatorInstance, ParameterExpression collection, BinaryExpression createCollection, MethodInfo addMethod)
{
BlockExpression dictionaryBlock;
var isDictionaryCollection = BuildComplexTypeCollectionPopulator(collection, genericType, addMethod, createCollection, creatorInstance, out dictionaryBlock);
BlockExpression objectBlock;
var isObjectcollection = BuildSimpleTypeCollectionPopulator(collection, genericType, addMethod, createCollection, creatorInstance, out objectBlock);
return Expression.IfThenElse(isDictionaryCollection, dictionaryBlock,
Expression.IfThen(isObjectcollection, objectBlock));
}
private TypeBinaryExpression BuildComplexTypeCollectionPopulator(ParameterExpression collection, Type genericType,
MethodInfo addMethod, BinaryExpression createCollection,
ConcreteTypeCreator creatorInstance, out BlockExpression block)
{
var creator = Expression.Constant(creatorInstance);
var array = Expression.Variable(typeof (IDictionary<string, object>[]));
var i = Expression.Variable(typeof (int));
var current = Expression.Variable(typeof (IDictionary<string, object>));
var isDictionaryCollection = Expression.TypeIs(_itemProperty,
typeof (IEnumerable<IDictionary<string, object>>));
var toArray = Expression.Assign(array,
Expression.Call(ToArrayDictionaryMethod,
Expression.Convert(_itemProperty,
typeof (IEnumerable<IDictionary<string, object>>))));
var start = Expression.Assign(i, Expression.Constant(0));
var label = Expression.Label();
var loop = Expression.Loop(
Expression.IfThenElse(
Expression.LessThan(i, Expression.Property(array, ArrayDictionaryLengthProperty)),
Expression.Block(
Expression.Assign(current, Expression.ArrayIndex(array, i)),
Expression.Call(collection, addMethod,
Expression.Convert(Expression.Call(creator, CreatorCreateMethod, current), genericType)),
Expression.PreIncrementAssign(i)
),
Expression.Break(label)
),
label
);
block = Expression.Block(
new[] {array, i, collection, current},
createCollection,
toArray,
start,
loop,
_property.CanWrite ? (Expression) Expression.Assign(_nameProperty, collection) : Expression.Empty());
return isDictionaryCollection;
}
private TypeBinaryExpression BuildSimpleTypeCollectionPopulator(ParameterExpression collection, Type genericType,
MethodInfo addMethod, BinaryExpression createCollection,
ConcreteTypeCreator creatorInstance, out BlockExpression block)
{
var creator = Expression.Constant(creatorInstance);
var array = Expression.Variable(typeof(object[]));
var i = Expression.Variable(typeof(int));
var current = Expression.Variable(typeof(object));
var isObjectCollection = Expression.TypeIs(_itemProperty,
typeof(IEnumerable<object>));
var toArray = Expression.Assign(array,
Expression.Call(ToArrayObjectMethod,
Expression.Convert(_itemProperty,
typeof(IEnumerable<object>))));
var start = Expression.Assign(i, Expression.Constant(0));
var label = Expression.Label();
var loop = Expression.Loop(
Expression.IfThenElse(
Expression.LessThan(i, Expression.Property(array, ArrayObjectLengthProperty)),
Expression.Block(
Expression.Assign(current, Expression.ArrayIndex(array, i)),
Expression.IfThenElse(
Expression.TypeIs(current, typeof(IDictionary<string,object>)),
Expression.Call(collection, addMethod,
Expression.Convert(Expression.Call(creator, CreatorCreateMethod,
Expression.Convert(current, typeof(IDictionary<string,object>))),
genericType)),
Expression.Call(collection, addMethod,
Expression.Convert(current, genericType))),
Expression.PreIncrementAssign(i)
),
Expression.Break(label)
),
label
);
block = Expression.Block(
new[] { array, i, collection, current },
createCollection,
toArray,
start,
loop,
_property.CanWrite ? (Expression)Expression.Assign(_nameProperty, collection) : Expression.Empty());
return isObjectCollection;
}
private BinaryExpression MakeCreateNewCollection(ParameterExpression collection, Type genericType)
{
BinaryExpression createCollection;
if (_property.PropertyType.IsInterface)
{
createCollection = Expression.Assign(collection,
Expression.Call(
typeof (PropertySetterBuilder).GetMethod("CreateList",
BindingFlags.
NonPublic |
BindingFlags.
Static).
MakeGenericMethod(genericType)));
}
else
{
var defaultConstructor = _property.PropertyType.GetConstructor(Type.EmptyTypes);
if (defaultConstructor != null)
{
createCollection = Expression.Assign(collection, Expression.New(defaultConstructor));
}
else
{
createCollection = null;
}
}
return createCollection;
}
private bool PropertyIsPrimitive()
{
return _property.PropertyType.IsPrimitive || _property.PropertyType == typeof(string) ||
_property.PropertyType == typeof(DateTime) || _property.PropertyType == typeof(byte[]) ||
_property.PropertyType.IsEnum ||
(_property.PropertyType.IsGenericType && _property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>));
}
private void CreatePropertyExpressions()
{
var name = Expression.Constant(_property.Name, typeof(string));
_containsKey = Expression.Call(_param, DictionaryContainsKeyMethod, name);
_nameProperty = Expression.Property(_obj, _property);
_itemProperty = Expression.Property(_param, DictionaryIndexerProperty, name);
}
private CatchBlock CreateCatchBlock()
{
return Expression.Catch(typeof(Exception), Expression.Assign(_nameProperty,
Expression.Default(_property.PropertyType)));
}
private BinaryExpression CreateComplexAssign()
{
var creator = Expression.Constant(ConcreteTypeCreator.Get(_property.PropertyType));
var methodCallExpression = Expression.Call(creator, CreatorCreateMethod,
// ReSharper disable PossiblyMistakenUseOfParamsMethod
Expression.Convert(_itemProperty,
typeof(IDictionary<string, object>)));
// ReSharper restore PossiblyMistakenUseOfParamsMethod
var complexAssign = Expression.Assign(_nameProperty,
Expression.Convert(
methodCallExpression, _property.PropertyType));
return complexAssign;
}
private TryExpression CreateTrySimpleAssign()
{
MethodCallExpression callConvert;
if (_property.PropertyType.IsEnum)
{
var changeTypeMethod = typeof (PropertySetterBuilder).GetMethod("SafeConvert",
BindingFlags.Static | BindingFlags.NonPublic);
callConvert = Expression.Call(changeTypeMethod, _itemProperty,
Expression.Constant(_property.PropertyType.GetEnumUnderlyingType(), typeof(Type)));
}
else if (_property.PropertyType.IsGenericType && _property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
var changeTypeMethod = typeof (PropertySetterBuilder)
.GetMethod("SafeConvertNullable", BindingFlags.Static | BindingFlags.NonPublic)
.MakeGenericMethod(_property.PropertyType.GetGenericArguments().Single());
callConvert = Expression.Call(changeTypeMethod, _itemProperty);
}
else
{
var changeTypeMethod = typeof (PropertySetterBuilder).GetMethod("SafeConvert",
BindingFlags.Static | BindingFlags.NonPublic);
callConvert = Expression.Call(changeTypeMethod, _itemProperty,
Expression.Constant(_property.PropertyType, typeof(Type)));
}
var assign = Expression.Assign(_nameProperty, Expression.Convert(callConvert, _property.PropertyType));
if (_property.PropertyType.IsEnum)
{
return Expression.TryCatch( // try {
Expression.IfThenElse(Expression.TypeIs(_itemProperty, typeof (string)),
Expression.Assign(_nameProperty,
Expression.Convert(Expression.Call(typeof (Enum).GetMethod("Parse", new[] {typeof(Type), typeof(string), typeof(bool)}),
Expression.Constant(_property.PropertyType, typeof(Type)),
Expression.Call(_itemProperty, typeof(object).GetMethod("ToString")), Expression.Constant(true)), _property.PropertyType)),
assign), Expression.Catch(typeof(Exception), Expression.Empty()));
}
return Expression.TryCatch( // try {
assign,
CreateCatchBlock());
}
private TryExpression CreateTrySimpleArrayAssign()
{
var createArrayMethod = typeof (PropertySetterBuilder).GetMethod("CreateArray", BindingFlags.Static | BindingFlags.NonPublic)
.MakeGenericMethod(_property.PropertyType.GetElementType());
var callConvert = Expression.Call(createArrayMethod, _itemProperty);
var assign = Expression.Assign(_nameProperty, Expression.Convert(callConvert, _property.PropertyType));
return Expression.TryCatch( // try {
Expression.IfThenElse(Expression.TypeIs(_itemProperty, typeof (string)),
Expression.Assign(_nameProperty,
Expression.Convert(Expression.Call(typeof (Enum).GetMethod("Parse", new[] {typeof(Type), typeof(string), typeof(bool)}),
Expression.Constant(_property.PropertyType, typeof(Type)),
Expression.Call(_itemProperty, typeof(object).GetMethod("ToString")), Expression.Constant(true)), _property.PropertyType)),
assign), Expression.Catch(typeof(Exception), Expression.Empty()));
}
// ReSharper disable UnusedMember.Local
// Because they're used from runtime-generated code, you see.
internal static object SafeConvert(object source, Type targetType)
{
if (ReferenceEquals(source, null)) return null;
if (targetType.IsInstanceOfType(source)) return source;
if (source is string && targetType == typeof(Guid)) return TypeDescriptor.GetConverter(typeof(Guid)).ConvertFromInvariantString(source.ToString());
return Convert.ChangeType(source, targetType);
}
internal static T? SafeConvertNullable<T>(object source)
where T : struct
{
if (ReferenceEquals(source, null)) return default(T?);
return (T) source;
}
private static T[] CreateArray<T>(object source)
{
if (ReferenceEquals(source, null)) return null;
var enumerable = source as IEnumerable;
if (ReferenceEquals(enumerable, null)) return null;
try
{
return enumerable.Cast<T>().ToArray();
}
catch (InvalidCastException)
{
return null;
}
}
private static List<T> CreateList<T>()
{
return new List<T>();
}
// ReSharper restore UnusedMember.Local
}
}
| |
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2016 Colin Green (sharpneat@gmail.com)
*
* SharpNEAT is free software; you can redistribute it and/or modify
* it under the terms of The MIT License (MIT).
*
* You should have received a copy of the MIT License
* along with SharpNEAT; if not, see https://opensource.org/licenses/MIT.
*/
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Redzen.Sorting;
using SharpNeat.Core;
namespace SharpNeat.SpeciationStrategies
{
// ENHANCEMENT: k-means++ seeks to choose better starting clusters. (http://en.wikipedia.org/wiki/K-means_clustering)
// ENHANCEMENT: The filtering algorithm uses kd-trees to speed up each k-means step[9]. (http://en.wikipedia.org/wiki/K-means_clustering)
// ENHANCEMENT: Euclidean squared distance metric is equivalent for k-means and faster than euclidean (http://www.improvedoutcomes.com/docs/WebSiteDocs/Clustering/Clustering_Parameters/Euclidean_and_Euclidean_Squared_Distance_Metrics.htm)
// ENHANCEMENT: Using the Triangle Inequality to Accelerate k-Means (http://cseweb.ucsd.edu/~elkan/kmeansicml03.pdf)
/// <summary>
/// An ISpeciationStrategy that speciates genomes using the k-means clustering method.
/// k-means requires a distance metric and as such this class requires am IDistanceMetric to be provided at
/// construction time. Different distance metrics can be used including NeatDistanceMetric which is
/// equivalent to the metric used in the standard NEAT method albeit with a different clustering/speciation
/// algorithm (Standard NEAT does not use k-means).
/// </summary>
/// <typeparam name="TGenome">The genome type to apply clustering to.</typeparam>
public class ParallelKMeansClusteringStrategy<TGenome> : ISpeciationStrategy<TGenome>
where TGenome : class, IGenome<TGenome>
{
const int __MAX_KMEANS_LOOPS = 5;
readonly IDistanceMetric _distanceMetric;
readonly ParallelOptions _parallelOptions;
#region Constructor
/// <summary>
/// Constructor that accepts an IDistanceMetric to be used for the k-means method.
/// </summary>
public ParallelKMeansClusteringStrategy(IDistanceMetric distanceMetric)
{
_distanceMetric = distanceMetric;
_parallelOptions = new ParallelOptions();
}
/// <summary>
/// Constructor that accepts an IDistanceMetric to be used for the k-means method and ParallelOptions.
/// </summary>
public ParallelKMeansClusteringStrategy(IDistanceMetric distanceMetric, ParallelOptions options)
{
_distanceMetric = distanceMetric;
_parallelOptions = options;
}
#endregion
#region ISpeciationStrategy<TGenome> Members
/// <summary>
/// Speciates the genomes in genomeList into the number of species specified by specieCount
/// and returns a newly constructed list of Specie objects containing the speciated genomes.
/// </summary>
public IList<Specie<TGenome>> InitializeSpeciation(IList<TGenome> genomeList, int specieCount)
{
// Create empty specieList.
// Use an initial specieList capacity that will limit the need for memory reallocation but that isn't
// too wasteful of memory.
int initSpeciesCapacity = (genomeList.Count * 2) / specieCount;
List<Specie<TGenome>> specieList = new List<Specie<TGenome>>(specieCount);
for(int i=0; i<specieCount; i++) {
specieList.Add(new Specie<TGenome>((uint)i, i, initSpeciesCapacity));
}
// Speciate genomes into the empty species.
SpeciateGenomes(genomeList, specieList);
return specieList;
}
/// <summary>
/// Speciates the genomes in genomeList into the provided specieList. It is assumed that
/// the genomeList represents all of the required genomes and that the species are currently empty.
///
/// This method can be used for initialization or completely re-speciating an existing genome population.
/// </summary>
public void SpeciateGenomes(IList<TGenome> genomeList, IList<Specie<TGenome>> specieList)
{
Debug.Assert(SpeciationUtils.TestEmptySpecies(specieList), "SpeciateGenomes(IList<TGenome>,IList<Species<TGenome>>) called with non-empty species");
Debug.Assert(genomeList.Count >= specieList.Count, $"SpeciateGenomes(IList<TGenome>,IList<Species<TGenome>>). Species count [{specieList.Count}] is greater than genome count [{genomeList.Count}].");
// Randomly allocate the first k genomes to their own specie. Because there is only one genome in these
// species each genome effectively represents a specie centroid. This is necessary to ensure we get k specieList.
// If we randomly assign all genomes to species from the outset and then calculate centroids then typically some
// of the species become empty.
// This approach ensures that each species will have at least one genome - because that genome is the specie
// centroid and therefore has distance of zero from the centroid (itself).
int specieCount = specieList.Count;
for(int i=0; i<specieCount; i++)
{
Specie<TGenome> specie = specieList[i];
genomeList[i].SpecieIdx = specie.Idx;
specie.GenomeList.Add(genomeList[i]);
// Just set the specie centroid directly.
specie.Centroid = genomeList[i].Position;
}
// Now allocate the remaining genomes based on their distance from the centroids.
int genomeCount = genomeList.Count;
Parallel.For(specieCount, genomeCount, _parallelOptions, delegate(int i)
{
TGenome genome = genomeList[i];
Specie<TGenome> closestSpecie = FindClosestSpecie(genome, specieList);
genome.SpecieIdx = closestSpecie.Idx;
lock(closestSpecie.GenomeList) {
closestSpecie.GenomeList.Add(genome);
}
});
// Recalculate each specie's centroid.
Parallel.ForEach(specieList, _parallelOptions, delegate(Specie<TGenome> specie) {
specie.Centroid = CalculateSpecieCentroid(specie);
});
// Perform the main k-means loop until convergence.
SpeciateUntilConvergence(genomeList, specieList);
Debug.Assert(SpeciationUtils.PerformIntegrityCheck(specieList));
}
/// <summary>
/// Speciates the offspring genomes in offspringList into the provided specieList. In contrast to
/// SpeciateGenomes() offspringList is taken to be a list of new genomes (offspring) that should be
/// added to existing species. That is, the species contain genomes that are not in offspringList
/// that we wish to keep; typically these would be elite genomes that are the parents of the
/// offspring.
/// </summary>
public void SpeciateOffspring(IList<TGenome> offspringList, IList<Specie<TGenome>> specieList)
{
// Each specie should contain at least one genome. We need at least one existing genome per specie to act
// as a specie centroid in order to define where the specie is within the encoding space.
Debug.Assert(SpeciationUtils.TestPopulatedSpecies(specieList), "SpeciateOffspring(IList<TGenome>,IList<Species<TGenome>>) called with an empty specie.");
// Update the centroid of each specie. If we're adding offspring this means that old genomes
// have been removed from the population and therefore the centroids are out-of-date.
Parallel.ForEach(specieList, _parallelOptions, delegate(Specie<TGenome> specie) {
specie.Centroid = CalculateSpecieCentroid(specie);
});
// Allocate each offspring genome to the specie it is closest to.
Parallel.ForEach(offspringList, _parallelOptions, delegate(TGenome genome)
{
Specie<TGenome> closestSpecie = FindClosestSpecie(genome, specieList);
lock(closestSpecie.GenomeList) {
// TODO: Consider using ConcurrentQueue here (and elsewhere in this class).
closestSpecie.GenomeList.Add(genome);
}
genome.SpecieIdx = closestSpecie.Idx;
});
// Recalculate each specie's centroid now that we have additional genomes in the specieList.
Parallel.ForEach(specieList, _parallelOptions, delegate(Specie<TGenome> specie) {
specie.Centroid = CalculateSpecieCentroid(specie);
});
// Accumulate *all* genomes into a flat genome list.
int genomeCount = 0;
foreach(Specie<TGenome> specie in specieList) {
genomeCount += specie.GenomeList.Count;
}
List<TGenome> genomeList = new List<TGenome>(genomeCount);
foreach(Specie<TGenome> specie in specieList) {
genomeList.AddRange(specie.GenomeList);
}
// Perform the main k-means loop until convergence.
SpeciateUntilConvergence(genomeList, specieList);
Debug.Assert(SpeciationUtils.PerformIntegrityCheck(specieList));
}
#endregion
#region Private Methods [k-means]
/// <summary>
/// Perform the main k-means loop until no genome reallocations occur or some maximum number of loops
/// has been performed. Theoretically a small number of reallocations may occur for a great many loops
/// therefore we require the additional max loops threshold exit strategy - the clusters should be pretty
/// stable and well defined after a few loops even if the algorithm hasn't converged completely.
/// </summary>
private void SpeciateUntilConvergence(IList<TGenome> genomeList, IList<Specie<TGenome>> specieList)
{
List<Specie<TGenome>> emptySpecieList = new List<Specie<TGenome>>();
int specieCount = specieList.Count;
// Array of flags that indicate if a specie was modified (had genomes allocated to and/or from it).
bool[] specieModArr = new bool[specieCount];
// Main k-means loop.
for(int loops=0; loops<__MAX_KMEANS_LOOPS; loops++)
{
// Track number of reallocations made on each loop.
int[] reallocations = {0};
// Loop over genomes. For each one find the specie it is closest to; if it is not the specie
// it is currently in then reallocate it.
Parallel.ForEach(genomeList, _parallelOptions, delegate(TGenome genome)
{
Specie<TGenome> closestSpecie = FindClosestSpecie(genome, specieList);
if(genome.SpecieIdx != closestSpecie.Idx)
{
lock(specieModArr)
{
// Track which species have been modified.
specieModArr[genome.SpecieIdx] = true;
specieModArr[closestSpecie.Idx] = true;
reallocations[0]++;
}
lock(closestSpecie.GenomeList)
{
// Add the genome to its new specie and set its speciesIdx accordingly.
// For now we leave the genome in its original species; It's more efficient to determine
// all reallocations and then remove reallocated genomes from their origin specie all together;
// This is because we can shuffle down the remaining genomes in a specie to fill the gaps made by
// the removed genomes - and do so in one round of shuffling instead of shuffling to fill a gap on
// each remove.
closestSpecie.GenomeList.Add(genome);
}
genome.SpecieIdx = closestSpecie.Idx;
}
});
// Complete the reallocations.
Parallel.For(0, specieCount, _parallelOptions, delegate(int i)
{
if(!specieModArr[i])
{ // Specie not changed. Skip.
return;
}
// Reset flag.
specieModArr[i] = false;
// Remove the genomes that have been allocated to other species. We fill the resulting
// gaps by shuffling down the remaining genomes.
Specie<TGenome> specie = specieList[i];
specie.GenomeList.RemoveAll(delegate(TGenome genome)
{
return genome.SpecieIdx != specie.Idx;
});
// Track empty species. We will allocate genomes to them after this loop.
// This is necessary as some distance metrics can result in empty species occurring.
if(0 == specie.GenomeList.Count)
{
lock(emptySpecieList)
{
emptySpecieList.Add(specie);
}
}
else
{ // Recalc the specie centroid now that it contains a different set of genomes.
specie.Centroid = CalculateSpecieCentroid(specie);
}
});
// Check for empty species. We need to reallocate some genomes into the empty specieList to maintain the
// required number of species.
if(0 != emptySpecieList.Count)
{
// We find the genomes in the population as a whole that are furthest from their containing specie's
// centroid genome - we call these outlier genomes. We then move these genomes into the empty species to
// act as the sole member and centroid of those species; These act as specie seeds for the next k-means loop.
TGenome[] genomeByDistanceArr = GetGenomesByDistanceFromSpecie(genomeList, specieList);
// Reallocate each of the outlier genomes from their current specie to an empty specie.
int emptySpecieCount = emptySpecieList.Count;
int outlierIdx = 0;
for(int i=0; i<emptySpecieCount; i++)
{
// Find the next outlier genome that can be re-allocated. Skip genomes that are the
// only member of a specie - moving them would just create another empty specie.
TGenome genome;
Specie<TGenome> sourceSpecie;
do
{
genome = genomeByDistanceArr[outlierIdx++];
sourceSpecie = specieList[genome.SpecieIdx];
}
while(sourceSpecie.GenomeList.Count == 1 && outlierIdx < genomeByDistanceArr.Length);
if(outlierIdx == genomeByDistanceArr.Length)
{ // Theoretically impossible. We do the test so that we get an easily traceable error message if it does happen.
throw new SharpNeatException("Error finding outlier genome. No outliers could be found in any specie with more than 1 genome.");
}
// Get ref to the empty specie and register both source and target specie with specieModArr.
Specie<TGenome> emptySpecie = emptySpecieList[i];
specieModArr[emptySpecie.Idx] = true;
specieModArr[sourceSpecie.Idx] = true;
// Reallocate the genome. Here we do the remove operation right away; We aren't expecting to deal with many empty
// species, usually it will be one or two at most; Any more and there's probably something wrong with the distance
// metric, e.g. maybe it doesn't satisfy the triangle inequality (see wikipedia).
// Another reason to remove right is to eliminate the possibility of removing multiple outlier genomes from the
// same specie and potentially leaving it empty; The test in the do-while loop above only takes genomes from
// currently non-empty species.
sourceSpecie.GenomeList.Remove(genome);
emptySpecie.GenomeList.Add(genome);
genome.SpecieIdx = emptySpecie.Idx;
reallocations[0]++;
}
// Recalculate centroid for all affected species.
Parallel.For(0, specieCount, _parallelOptions, delegate(int i)
{
if(specieModArr[i])
{ // Reset flag while we're here. Do this first to help maintain CPU cache coherency (we just tested it).
specieModArr[i] = false;
specieList[i].Centroid = CalculateSpecieCentroid(specieList[i]);
}
});
// Clear emptySpecieList after using it. Otherwise we are holding old references and thus creating
// reference traversal work for the garbage collector.
emptySpecieList.Clear();
}
// Exit the loop if no genome reallocations have occurred. The species are stable, speciation is completed.
if(0==reallocations[0]) {
break;
}
}
}
/// <summary>
/// Recalculate the specie centroid based on the genomes currently in the specie.
/// </summary>
private CoordinateVector CalculateSpecieCentroid(Specie<TGenome> specie)
{
// Special case - 1 genome in specie (its position *is* the specie centroid).
if(1 == specie.GenomeList.Count) {
return new CoordinateVector(specie.GenomeList[0].Position.CoordArray);
}
// Create a temp list containing all of the genome positions.
List<TGenome> genomeList = specie.GenomeList;
int count = genomeList.Count;
List<CoordinateVector> coordList = new List<CoordinateVector>(count);
for(int i=0; i<count; i++) {
coordList.Add(genomeList[i].Position);
}
// The centroid calculation is a function of the distance metric.
return _distanceMetric.CalculateCentroid(coordList);
}
// ENHANCEMENT: Optimization candidate.
/// <summary>
/// Gets an array of all genomes ordered by their distance from their current specie.
/// </summary>
private TGenome[] GetGenomesByDistanceFromSpecie(IList<TGenome> genomeList, IList<Specie<TGenome>> specieList)
{
// Build an array of all genomes paired with their distance from their centroid.
int genomeCount = genomeList.Count;
GenomeDistancePair<TGenome>[] genomeDistanceArr = new GenomeDistancePair<TGenome>[genomeCount];
Parallel.For(0, genomeCount, _parallelOptions, delegate(int i)
{
TGenome genome = genomeList[i];
double distance = _distanceMetric.GetDistance(genome.Position, specieList[genome.SpecieIdx].Centroid);
genomeDistanceArr[i] = new GenomeDistancePair<TGenome>(distance, genome);
});
// Sort list. Longest distance first.
// TODO: Pass in parallel options.
ParallelSort.QuicksortParallel(genomeDistanceArr);
// Put the sorted genomes in an array and return it.
TGenome[] genomeArr = new TGenome[genomeCount];
for(int i=0; i<genomeCount; i++) {
genomeArr[i] = genomeDistanceArr[i]._genome;
}
return genomeArr;
}
/// <summary>
/// Find the specie that a genome is closest to as determined by the distance metric.
/// </summary>
private Specie<TGenome> FindClosestSpecie(TGenome genome, IList<Specie<TGenome>> specieList)
{
// Measure distance to first specie's centroid.
Specie<TGenome> closestSpecie = specieList[0];
double closestDistance = _distanceMetric.GetDistance(genome.Position, closestSpecie.Centroid);
// Measure distance to all remaining species.
int speciesCount = specieList.Count;
for(int i=1; i<speciesCount; i++)
{
double distance = _distanceMetric.GetDistance(genome.Position, specieList[i].Centroid);
if(distance < closestDistance)
{
closestDistance = distance;
closestSpecie = specieList[i];
}
}
return closestSpecie;
}
#endregion
}
}
| |
// 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.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
/// <summary>
/// A Function that takes a single argument of type P and returns a value of type R.
/// </summary>
public delegate R Function<P, R>(P p);
/// <summary>
/// The name of an entity. Typically name instances come from a common pool. Within the pool no two distinct instances will have the same Value or UniqueKey.
/// </summary>
[ContractClass(typeof(INameContract))]
public interface IName
{
/// <summary>
/// An integer that is unique within the pool from which the name instance has been allocated. Useful as a hashtable key.
/// </summary>
int UniqueKey
{
get;
//^ ensures result > 0;
}
/// <summary>
/// An integer that is unique within the pool from which the name instance has been allocated. Useful as a hashtable key.
/// All name instances in the pool that have the same string value when ignoring the case of the characters in the string
/// will have the same key value.
/// </summary>
int UniqueKeyIgnoringCase
{
get;
//^ ensures result > 0;
}
/// <summary>
/// The string value corresponding to this name.
/// </summary>
string Value { get; }
}
[ContractClassFor(typeof(IName))]
abstract class INameContract : IName
{
public int UniqueKey
{
get
{
Contract.Ensures(Contract.Result<int>() > 0);
throw new NotImplementedException();
}
}
public int UniqueKeyIgnoringCase
{
get
{
Contract.Ensures(Contract.Result<int>() > 0);
throw new NotImplementedException();
}
}
public string Value
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
throw new NotImplementedException();
}
}
}
/// <summary>
/// Implemented by any entity that has a name.
/// </summary>
[ContractClass(typeof(INamedEntityContract))]
public interface INamedEntity
{
/// <summary>
/// The name of the entity.
/// </summary>
IName Name { get; }
}
[ContractClassFor(typeof(INamedEntity))]
abstract class INamedEntityContract : INamedEntity
{
public IName Name
{
get
{
Contract.Ensures(Contract.Result<IName>() != null);
throw new NotImplementedException();
}
}
}
/// <summary>
/// A collection of named members, with routines to search the collection.
/// </summary>
[ContractClass(typeof(IScopeContract<>))]
public interface IScope<MemberType>
where MemberType : class, INamedEntity
{
/// <summary>
/// Return true if the given member instance is a member of this scope.
/// </summary>
[Pure]
bool Contains(MemberType/*!*/ member);
// ^ ensures result == exists{MemberType mem in this.Members; mem == member};
/// <summary>
/// Returns the list of members with the given name that also satisfy the given predicate.
/// </summary>
[Pure]
IEnumerable<MemberType> GetMatchingMembersNamed(IName name, bool ignoreCase, Function<MemberType, bool> predicate);
// ^ ensures forall{MemberType member in result; member.Name == name && predicate(member) && this.Contains(member)};
// ^ ensures forall{MemberType member in this.Members; member.Name == name && predicate(member) ==>
// ^ exists{INamespaceMember mem in result; mem == member}};
/// <summary>
/// Returns the list of members that satisfy the given predicate.
/// </summary>
[Pure]
IEnumerable<MemberType> GetMatchingMembers(Function<MemberType, bool> predicate);
// ^ ensures forall{MemberType member in result; predicate(member) && this.Contains(member)};
// ^ ensures forall{MemberType member in this.Members; predicate(member) ==> exists{MemberType mem in result; mem == member}};
/// <summary>
/// Returns the list of members with the given name.
/// </summary>
[Pure]
IEnumerable<MemberType> GetMembersNamed(IName name, bool ignoreCase);
// ^ ensures forall{MemberType member in result; member.Name == name && this.Contains(member)};
// ^ ensures forall{MemberType member in this.Members; member.Name == name ==>
// ^ exists{INamespaceMember mem in result; mem == member}};
/// <summary>
/// The collection of member instances that are members of this scope.
/// </summary>
IEnumerable<MemberType> Members { get; }
}
#region IScope<MemberType> contract binding
[ContractClassFor(typeof(IScope<>))]
abstract class IScopeContract<MemberType> : IScope<MemberType>
where MemberType : class, INamedEntity
{
public bool Contains(MemberType member)
{
//Contract.Ensures(!Contract.Result<bool>() || Contract.Exists(this.Members, x => x == (object)this));
throw new NotImplementedException();
}
public IEnumerable<MemberType> GetMatchingMembersNamed(IName name, bool ignoreCase, Function<MemberType, bool> predicate)
{
Contract.Requires(name != null);
Contract.Requires(predicate != null);
Contract.Ensures(Contract.Result<IEnumerable<MemberType>>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<MemberType>>(), x => x != null));
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<MemberType>>(), x => this.Contains(x)));
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<MemberType>>(),
x => ignoreCase ? x.Name.UniqueKeyIgnoringCase == x.Name.UniqueKeyIgnoringCase : x.Name == name));
//Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<MemberType>>(), x => predicate(x)));
throw new NotImplementedException();
}
public IEnumerable<MemberType> GetMatchingMembers(Function<MemberType, bool> predicate)
{
Contract.Requires(predicate != null);
Contract.Ensures(Contract.Result<IEnumerable<MemberType>>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<MemberType>>(), x => x != null));
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<MemberType>>(), x => this.Contains(x)));
//Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<MemberType>>(), x => predicate(x)));
throw new NotImplementedException();
}
public IEnumerable<MemberType> GetMembersNamed(IName name, bool ignoreCase)
{
Contract.Requires(name != null);
Contract.Ensures(Contract.Result<IEnumerable<MemberType>>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<MemberType>>(), x => x != null));
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<MemberType>>(), x => this.Contains(x)));
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<MemberType>>(),
x => ignoreCase ? x.Name.UniqueKeyIgnoringCase == x.Name.UniqueKeyIgnoringCase : x.Name == name));
throw new NotImplementedException();
}
public IEnumerable<MemberType> Members
{
get
{
Contract.Ensures(Contract.Result<IEnumerable<MemberType>>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<MemberType>>(), x => x != null));
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<MemberType>>(), x => this.Contains(x)));
throw new NotImplementedException();
}
}
}
#endregion
namespace Tests.Sources
{
class DummyScope : IScope<Member>
{
public bool Contains(Member member)
{
throw new NotImplementedException();
}
public IEnumerable<Member> GetMatchingMembersNamed(IName name, bool ignoreCase, Function<Member, bool> predicate)
{
throw new NotImplementedException();
}
public IEnumerable<Member> GetMatchingMembers(Function<Member, bool> predicate)
{
throw new NotImplementedException();
}
public IEnumerable<Member> GetMembersNamed(IName name, bool ignoreCase)
{
throw new NotImplementedException();
}
public IEnumerable<Member> Members
{
get { throw new NotImplementedException(); }
}
}
partial class TestMain
{
partial void Run()
{
var x = new DummyScope();
if (!this.behave)
{
x.GetMembersNamed(null, false);
}
}
public ContractFailureKind NegativeExpectedKind = ContractFailureKind.Precondition;
public string NegativeExpectedCondition = "name != null";
}
class Member : INamedEntity
{
IName INamedEntity.Name
{
get { throw new NotImplementedException(); }
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// 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 Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
namespace WOSI.Utilities
{
public class ProcessUtils
{
[StructLayout(LayoutKind.Sequential)]
public struct STARTUPINFO
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
// Declare the logon types as constants
const long LOGON32_LOGON_INTERACTIVE = 2;
const long LOGON32_LOGON_NETWORK = 3;
// Declare the logon providers as constants
const long LOGON32_PROVIDER_DEFAULT = 0;
const long LOGON32_PROVIDER_WINNT50 = 3;
const long LOGON32_PROVIDER_WINNT40 = 2;
const long LOGON32_PROVIDER_WINNT35 = 1;
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public Int32 dwProcessID;
public Int32 dwThreadID;
}
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public Int32 Length;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
}
public enum SECURITY_IMPERSONATION_LEVEL
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
}
public enum TOKEN_TYPE
{
TokenPrimary = 1,
TokenImpersonation
}
public const int GENERIC_ALL_ACCESS = 0x10000000;
[
DllImport("kernel32.dll",
EntryPoint = "CloseHandle", SetLastError = true,
CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)
]
public static extern bool CloseHandle(IntPtr handle);
[
DllImport("advapi32.dll",
EntryPoint = "CreateProcessAsUser", SetLastError = true,
CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)
]
public static extern bool
CreateProcessAsUser(IntPtr hToken, string lpApplicationName, string lpCommandLine,
ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes,
bool bInheritHandle, Int32 dwCreationFlags, IntPtr lpEnvrionment,
string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo,
ref PROCESS_INFORMATION lpProcessInformation);
[
DllImport("advapi32.dll",
EntryPoint = "DuplicateTokenEx")
]
public static extern bool
DuplicateTokenEx(IntPtr hExistingToken, Int32 dwDesiredAccess,
ref SECURITY_ATTRIBUTES lpThreadAttributes,
Int32 ImpersonationLevel, Int32 dwTokenType,
ref IntPtr phNewToken);
[DllImport("advapi32.dll", EntryPoint = "LogonUser")]
private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("userenv.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool LoadUserProfile(IntPtr hToken, ref ProfileInfo lpProfileInfo);
[DllImport("userenv.dll", SetLastError = true)]
static extern bool CreateEnvironmentBlock(out IntPtr lpEnvironment, IntPtr hToken, bool bInherit);
///
/// Profile Info
///
[StructLayout(LayoutKind.Sequential)]
public struct ProfileInfo
{
///
/// Specifies the size of the structure, in bytes.
///
public int dwSize;
///
/// This member can be one of the following flags: PI_NOUI or PI_APPLYPOLICY
///
public int dwFlags;
///
/// Pointer to the name of the user.
/// This member is used as the base name of the directory in which to store a new profile.
///
public string lpUserName;
///
/// Pointer to the roaming user profile path.
/// If the user does not have a roaming profile, this member can be NULL.
///
public string lpProfilePath;
///
/// Pointer to the default user profile path. This member can be NULL.
///
public string lpDefaultPath;
///
/// Pointer to the name of the validating domain controller, in NetBIOS format.
/// If this member is NULL, the Windows NT 4.0-style policy will not be applied.
///
public string lpServerName;
///
/// Pointer to the path of the Windows NT 4.0-style policy file. This member can be NULL.
///
public string lpPolicyPath;
///
/// Handle to the HKEY_CURRENT_USER registry key.
///
public IntPtr hProfile;
}
public static void CreateProcessAsUser(string username, string domain, string password, string commandLine)
{
IntPtr hToken = IntPtr.Zero;
IntPtr hDupedToken = IntPtr.Zero;
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
try
{
bool result = LogonUser(username, domain, password, (int)LOGON32_LOGON_INTERACTIVE, (int)LOGON32_PROVIDER_DEFAULT, ref hToken);
if (!result)
{
throw new ApplicationException("LogonUser failed");
}
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.Length = Marshal.SizeOf(sa);
result = DuplicateTokenEx(
hToken,
GENERIC_ALL_ACCESS,
ref sa,
(int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
(int)TOKEN_TYPE.TokenPrimary,
ref hDupedToken
);
if (!result)
{
throw new ApplicationException("DuplicateTokenEx failed");
}
STARTUPINFO si = new STARTUPINFO();
si.cb = Marshal.SizeOf(si);
si.lpDesktop = "winsta0\\default";
ProfileInfo info = new ProfileInfo();
info.dwSize = Marshal.SizeOf(info);
info.lpUserName = username;
info.dwFlags = 1;
result = LoadUserProfile(hDupedToken, ref info);
if (!result)
{
int error = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(error);
}
IntPtr lpEnvironment;
result = CreateEnvironmentBlock(out lpEnvironment, hDupedToken, false);
if (!result)
{
int error = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(error);
}
result = CreateProcessAsUser(
hDupedToken,
null,
commandLine,
ref sa, ref sa,
false, 0x00000400, lpEnvironment,
null, ref si, ref pi
);
if (!result)
{
int error = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(error);
}
}
finally
{
if (pi.hProcess != IntPtr.Zero)
CloseHandle(pi.hProcess);
if (pi.hThread != IntPtr.Zero)
CloseHandle(pi.hThread);
if (hDupedToken != IntPtr.Zero)
CloseHandle(hDupedToken);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using u8 = System.Byte;
using u32 = System.UInt32;
namespace System.Data.SQLite
{
public partial class Sqlite3
{
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** in order to generate code for DELETE FROM statements.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
**
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** While a SrcList can in general represent multiple tables and subqueries
** (as in the FROM clause of a SELECT statement) in this case it contains
** the name of a single table, as one might find in an INSERT, DELETE,
** or UPDATE statement. Look up that table in the symbol table and
** return a pointer. Set an error message and return NULL if the table
** name is not found or if any other error occurs.
**
** The following fields are initialized appropriate in pSrc:
**
** pSrc->a[0].pTab Pointer to the Table object
** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
**
*/
static Table sqlite3SrcListLookup(Parse pParse, SrcList pSrc)
{
SrcList_item pItem = pSrc.a[0];
Table pTab;
Debug.Assert(pItem != null && pSrc.nSrc == 1);
pTab = sqlite3LocateTable(pParse, 0, pItem.zName, pItem.zDatabase);
sqlite3DeleteTable(pParse.db, ref pItem.pTab);
pItem.pTab = pTab;
if (pTab != null)
{
pTab.nRef++;
}
if (sqlite3IndexedByLookup(pParse, pItem) != 0)
{
pTab = null;
}
return pTab;
}
/*
** Check to make sure the given table is writable. If it is not
** writable, generate an error message and return 1. If it is
** writable return 0;
*/
static bool sqlite3IsReadOnly(Parse pParse, Table pTab, int viewOk)
{
/* A table is not writable under the following circumstances:
**
** 1) It is a virtual table and no implementation of the xUpdate method
** has been provided, or
** 2) It is a system table (i.e. sqlite_master), this call is not
** part of a nested parse and writable_schema pragma has not
** been specified.
**
** In either case leave an error message in pParse and return non-zero.
*/
if (
(IsVirtual(pTab)
&& sqlite3GetVTable(pParse.db, pTab).pMod.pModule.xUpdate == null)
|| ((pTab.tabFlags & TF_Readonly) != 0
&& (pParse.db.flags & SQLITE_WriteSchema) == 0
&& pParse.nested == 0)
)
{
sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab.zName);
return true;
}
#if !SQLITE_OMIT_VIEW
if (viewOk == 0 && pTab.pSelect != null)
{
sqlite3ErrorMsg(pParse, "cannot modify %s because it is a view", pTab.zName);
return true;
}
#endif
return false;
}
#if !SQLITE_OMIT_VIEW && !SQLITE_OMIT_TRIGGER
/*
** Evaluate a view and store its result in an ephemeral table. The
** pWhere argument is an optional WHERE clause that restricts the
** set of rows in the view that are to be added to the ephemeral table.
*/
static void sqlite3MaterializeView(
Parse pParse, /* Parsing context */
Table pView, /* View definition */
Expr pWhere, /* Optional WHERE clause to be added */
int iCur /* VdbeCursor number for ephemerial table */
)
{
SelectDest dest = new SelectDest();
Select pDup;
sqlite3 db = pParse.db;
pDup = sqlite3SelectDup(db, pView.pSelect, 0);
if (pWhere != null)
{
SrcList pFrom;
pWhere = sqlite3ExprDup(db, pWhere, 0);
pFrom = sqlite3SrcListAppend(db, null, null, null);
//if ( pFrom != null )
//{
Debug.Assert(pFrom.nSrc == 1);
pFrom.a[0].zAlias = pView.zName;// sqlite3DbStrDup( db, pView.zName );
pFrom.a[0].pSelect = pDup;
Debug.Assert(pFrom.a[0].pOn == null);
Debug.Assert(pFrom.a[0].pUsing == null);
//}
//else
//{
// sqlite3SelectDelete( db, ref pDup );
//}
pDup = sqlite3SelectNew(pParse, null, pFrom, pWhere, null, null, null, 0, null, null);
}
sqlite3SelectDestInit(dest, SRT_EphemTab, iCur);
sqlite3Select(pParse, pDup, ref dest);
sqlite3SelectDelete(db, ref pDup);
}
#endif //* !SQLITE_OMIT_VIEW) && !SQLITE_OMIT_TRIGGER) */
#if (SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !(SQLITE_OMIT_SUBQUERY)
/*
** Generate an expression tree to implement the WHERE, ORDER BY,
** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
**
** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
** \__________________________/
** pLimitWhere (pInClause)
*/
Expr sqlite3LimitWhere(
Parse pParse, /* The parser context */
SrcList pSrc, /* the FROM clause -- which tables to scan */
Expr pWhere, /* The WHERE clause. May be null */
ExprList pOrderBy, /* The ORDER BY clause. May be null */
Expr pLimit, /* The LIMIT clause. May be null */
Expr pOffset, /* The OFFSET clause. May be null */
char zStmtType /* Either DELETE or UPDATE. For error messages. */
){
Expr pWhereRowid = null; /* WHERE rowid .. */
Expr pInClause = null; /* WHERE rowid IN ( select ) */
Expr pSelectRowid = null; /* SELECT rowid ... */
ExprList pEList = null; /* Expression list contaning only pSelectRowid */
SrcList pSelectSrc = null; /* SELECT rowid FROM x ... (dup of pSrc) */
Select pSelect = null; /* Complete SELECT tree */
/* Check that there isn't an ORDER BY without a LIMIT clause.
*/
if( pOrderBy!=null && (pLimit == null) ) {
sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
pParse.parseError = 1;
goto limit_where_cleanup_2;
}
/* We only need to generate a select expression if there
** is a limit/offset term to enforce.
*/
if ( pLimit == null )
{
/* if pLimit is null, pOffset will always be null as well. */
Debug.Assert( pOffset == null );
return pWhere;
}
/* Generate a select expression tree to enforce the limit/offset
** term for the DELETE or UPDATE statement. For example:
** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
** becomes:
** DELETE FROM table_a WHERE rowid IN (
** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
** );
*/
pSelectRowid = sqlite3PExpr( pParse, TK_ROW, null, null, null );
if( pSelectRowid == null ) goto limit_where_cleanup_2;
pEList = sqlite3ExprListAppend( pParse, null, pSelectRowid);
if( pEList == null ) goto limit_where_cleanup_2;
/* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
** and the SELECT subtree. */
pSelectSrc = sqlite3SrcListDup(pParse.db, pSrc,0);
if( pSelectSrc == null ) {
sqlite3ExprListDelete(pParse.db, pEList);
goto limit_where_cleanup_2;
}
/* generate the SELECT expression tree. */
pSelect = sqlite3SelectNew( pParse, pEList, pSelectSrc, pWhere, null, null,
pOrderBy, 0, pLimit, pOffset );
if( pSelect == null ) return null;
/* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
pWhereRowid = sqlite3PExpr( pParse, TK_ROW, null, null, null );
if( pWhereRowid == null ) goto limit_where_cleanup_1;
pInClause = sqlite3PExpr( pParse, TK_IN, pWhereRowid, null, null );
if( pInClause == null ) goto limit_where_cleanup_1;
pInClause->x.pSelect = pSelect;
pInClause->flags |= EP_xIsSelect;
sqlite3ExprSetHeight(pParse, pInClause);
return pInClause;
/* something went wrong. clean up anything allocated. */
limit_where_cleanup_1:
sqlite3SelectDelete(pParse.db, pSelect);
return null;
limit_where_cleanup_2:
sqlite3ExprDelete(pParse.db, ref pWhere);
sqlite3ExprListDelete(pParse.db, pOrderBy);
sqlite3ExprDelete(pParse.db, ref pLimit);
sqlite3ExprDelete(pParse.db, ref pOffset);
return null;
}
#endif //* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
/*
** Generate code for a DELETE FROM statement.
**
** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
** \________/ \________________/
** pTabList pWhere
*/
static void sqlite3DeleteFrom(
Parse pParse, /* The parser context */
SrcList pTabList, /* The table from which we should delete things */
Expr pWhere /* The WHERE clause. May be null */
)
{
Vdbe v; /* The virtual database engine */
Table pTab; /* The table from which records will be deleted */
int end, addr = 0; /* A couple addresses of generated code */
int i; /* Loop counter */
WhereInfo pWInfo; /* Information about the WHERE clause */
Index pIdx; /* For looping over indices of the table */
int iCur; /* VDBE VdbeCursor number for pTab */
sqlite3 db; /* Main database structure */
NameContext sNC; /* Name context to resolve expressions in */
int iDb; /* Database number */
int memCnt = -1; /* Memory cell used for change counting */
int rcauth; /* Value returned by authorization callback */
#if !SQLITE_OMIT_TRIGGER
bool isView; /* True if attempting to delete from a view */
Trigger pTrigger; /* List of table triggers, if required */
#endif
db = pParse.db;
if (pParse.nErr != 0 /*|| db.mallocFailed != 0 */ )
{
goto delete_from_cleanup;
}
Debug.Assert(pTabList.nSrc == 1);
/* Locate the table which we want to delete. This table has to be
** put in an SrcList structure because some of the subroutines we
** will be calling are designed to work with multiple tables and expect
** an SrcList* parameter instead of just a Table* parameter.
*/
pTab = sqlite3SrcListLookup(pParse, pTabList);
if (pTab == null)
goto delete_from_cleanup;
/* Figure out if we have any triggers and if the table being
** deleted from is a view
*/
#if !SQLITE_OMIT_TRIGGER
int iDummy;
pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, null, out iDummy);
isView = pTab.pSelect != null;
#else
const Trigger pTrigger = null;
bool isView = false;
#endif
#if SQLITE_OMIT_VIEW
//# undef isView
isView = false;
#endif
/* If pTab is really a view, make sure it has been initialized.
*/
if (sqlite3ViewGetColumnNames(pParse, pTab) != 0)
{
goto delete_from_cleanup;
}
if (sqlite3IsReadOnly(pParse, pTab, (pTrigger != null ? 1 : 0)))
{
goto delete_from_cleanup;
}
iDb = sqlite3SchemaToIndex(db, pTab.pSchema);
Debug.Assert(iDb < db.nDb);
#if !SQLITE_OMIT_AUTHORIZATION
rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
#else
rcauth = SQLITE_OK;
#endif
Debug.Assert(rcauth == SQLITE_OK || rcauth == SQLITE_DENY || rcauth == SQLITE_IGNORE);
if (rcauth == SQLITE_DENY)
{
goto delete_from_cleanup;
}
Debug.Assert(!isView || pTrigger != null);
/* Assign cursor number to the table and all its indices.
*/
Debug.Assert(pTabList.nSrc == 1);
iCur = pTabList.a[0].iCursor = pParse.nTab++;
for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext)
{
pParse.nTab++;
}
#if !SQLITE_OMIT_AUTHORIZATION
/* Start the view context
*/
if( isView ){
sqlite3AuthContextPush(pParse, sContext, pTab.zName);
}
#endif
/* Begin generating code.
*/
v = sqlite3GetVdbe(pParse);
if (v == null)
{
goto delete_from_cleanup;
}
if (pParse.nested == 0)
sqlite3VdbeCountChanges(v);
sqlite3BeginWriteOperation(pParse, 1, iDb);
/* If we are trying to delete from a view, realize that view into
** a ephemeral table.
*/
#if !(SQLITE_OMIT_VIEW) && !(SQLITE_OMIT_TRIGGER)
if (isView)
{
sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
}
#endif
/* Resolve the column names in the WHERE clause.
*/
sNC = new NameContext();// memset( &sNC, 0, sizeof( sNC ) );
sNC.pParse = pParse;
sNC.pSrcList = pTabList;
if (sqlite3ResolveExprNames(sNC, ref pWhere) != 0)
{
goto delete_from_cleanup;
}
/* Initialize the counter of the number of rows deleted, if
** we are counting rows.
*/
if ((db.flags & SQLITE_CountRows) != 0)
{
memCnt = ++pParse.nMem;
sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
}
#if !SQLITE_OMIT_TRUNCATE_OPTIMIZATION
/* Special case: A DELETE without a WHERE clause deletes everything.
** It is easier just to erase the whole table. Prior to version 3.6.5,
** this optimization caused the row change count (the value returned by
** API function sqlite3_count_changes) to be set incorrectly. */
if (rcauth == SQLITE_OK && pWhere == null && null == pTrigger && !IsVirtual(pTab)
&& 0 == sqlite3FkRequired(pParse, pTab, null, 0)
)
{
Debug.Assert(!isView);
sqlite3VdbeAddOp4(v, OP_Clear, pTab.tnum, iDb, memCnt,
pTab.zName, P4_STATIC);
for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext)
{
Debug.Assert(pIdx.pSchema == pTab.pSchema);
sqlite3VdbeAddOp2(v, OP_Clear, pIdx.tnum, iDb);
}
}
else
#endif //* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
/* The usual case: There is a WHERE clause so we have to scan through
** the table and pick which records to delete.
*/
{
int iRowSet = ++pParse.nMem; /* Register for rowset of rows to delete */
int iRowid = ++pParse.nMem; /* Used for storing rowid values. */
int regRowid; /* Actual register containing rowids */
/* Collect rowids of every row to be deleted.
*/
sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
ExprList elDummy = null;
pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, ref elDummy, WHERE_DUPLICATES_OK);
if (pWInfo == null)
goto delete_from_cleanup;
regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
if ((db.flags & SQLITE_CountRows) != 0)
{
sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
}
sqlite3WhereEnd(pWInfo);
/* Delete every item whose key was written to the list during the
** database scan. We have to delete items after the scan is complete
** because deleting an item can change the scan order. */
end = sqlite3VdbeMakeLabel(v);
/* Unless this is a view, open cursors for the table we are
** deleting from and all its indices. If this is a view, then the
** only effect this statement has is to fire the INSTEAD OF
** triggers. */
if (!isView)
{
sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
}
addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
/* Delete the row */
#if !SQLITE_OMIT_VIRTUALTABLE
if (IsVirtual(pTab))
{
VTable pVTab = sqlite3GetVTable(db, pTab);
sqlite3VtabMakeWritable(pParse, pTab);
sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
sqlite3VdbeChangeP5(v, OE_Abort);
sqlite3MayAbort(pParse);
}
else
#endif
{
int count = (pParse.nested == 0) ? 1 : 0; /* True to count changes */
sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
}
/* End of the delete loop */
sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
sqlite3VdbeResolveLabel(v, end);
/* Close the cursors open on the table and its indexes. */
if (!isView && !IsVirtual(pTab))
{
for (i = 1, pIdx = pTab.pIndex; pIdx != null; i++, pIdx = pIdx.pNext)
{
sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx.tnum);
}
sqlite3VdbeAddOp1(v, OP_Close, iCur);
}
}
/* Update the sqlite_sequence table by storing the content of the
** maximum rowid counter values recorded while inserting into
** autoincrement tables.
*/
if (pParse.nested == 0 && pParse.pTriggerTab == null)
{
sqlite3AutoincrementEnd(pParse);
}
/* Return the number of rows that were deleted. If this routine is
** generating code because of a call to sqlite3NestedParse(), do not
** invoke the callback function.
*/
if ((db.flags & SQLITE_CountRows) != 0 && 0 == pParse.nested && null == pParse.pTriggerTab)
{
sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
sqlite3VdbeSetNumCols(v, 1);
sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
}
delete_from_cleanup:
#if !SQLITE_OMIT_AUTHORIZATION
sqlite3AuthContextPop(sContext);
#endif
sqlite3SrcListDelete(db, ref pTabList);
sqlite3ExprDelete(db, ref pWhere);
return;
}
/* Make sure "isView" and other macros defined above are undefined. Otherwise
** thely may interfere with compilation of other functions in this file
** (or in another file, if this file becomes part of the amalgamation). */
//#if isView
// #undef isView
//#endif
//#if pTrigger
// #undef pTrigger
//#endif
/*
** This routine generates VDBE code that causes a single row of a
** single table to be deleted.
**
** The VDBE must be in a particular state when this routine is called.
** These are the requirements:
**
** 1. A read/write cursor pointing to pTab, the table containing the row
** to be deleted, must be opened as cursor number $iCur.
**
** 2. Read/write cursors for all indices of pTab must be open as
** cursor number base+i for the i-th index.
**
** 3. The record number of the row to be deleted must be stored in
** memory cell iRowid.
**
** This routine generates code to remove both the table record and all
** index entries that point to that record.
*/
static void sqlite3GenerateRowDelete(
Parse pParse, /* Parsing context */
Table pTab, /* Table containing the row to be deleted */
int iCur, /* VdbeCursor number for the table */
int iRowid, /* Memory cell that contains the rowid to delete */
int count, /* If non-zero, increment the row change counter */
Trigger pTrigger, /* List of triggers to (potentially) fire */
int onconf /* Default ON CONFLICT policy for triggers */
)
{
Vdbe v = pParse.pVdbe; /* Vdbe */
int iOld = 0; /* First register in OLD.* array */
int iLabel; /* Label resolved to end of generated code */
/* Vdbe is guaranteed to have been allocated by this stage. */
Debug.Assert(v != null);
/* Seek cursor iCur to the row to delete. If this row no longer exists
** (this can happen if a trigger program has already deleted it), do
** not attempt to delete it or fire any DELETE triggers. */
iLabel = sqlite3VdbeMakeLabel(v);
sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
/* If there are any triggers to fire, allocate a range of registers to
** use for the old.* references in the triggers. */
if (sqlite3FkRequired(pParse, pTab, null, 0) != 0 || pTrigger != null)
{
u32 mask; /* Mask of OLD.* columns in use */
int iCol; /* Iterator used while populating OLD.* */
/* TODO: Could use temporary registers here. Also could attempt to
** avoid copying the contents of the rowid register. */
mask = sqlite3TriggerColmask(
pParse, pTrigger, null, 0, TRIGGER_BEFORE | TRIGGER_AFTER, pTab, onconf
);
mask |= sqlite3FkOldmask(pParse, pTab);
iOld = pParse.nMem + 1;
pParse.nMem += (1 + pTab.nCol);
/* Populate the OLD.* pseudo-table register array. These values will be
** used by any BEFORE and AFTER triggers that exist. */
sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
for (iCol = 0; iCol < pTab.nCol; iCol++)
{
if (mask == 0xffffffff || (mask & (1 << iCol)) != 0)
{
sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld + iCol + 1);
}
}
/* Invoke BEFORE DELETE trigger programs. */
sqlite3CodeRowTrigger(pParse, pTrigger,
TK_DELETE, null, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
);
/* Seek the cursor to the row to be deleted again. It may be that
** the BEFORE triggers coded above have already removed the row
** being deleted. Do not attempt to delete the row a second time, and
** do not fire AFTER triggers. */
sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
/* Do FK processing. This call checks that any FK constraints that
** refer to this table (i.e. constraints attached to other tables)
** are not violated by deleting this row. */
sqlite3FkCheck(pParse, pTab, iOld, 0);
}
/* Delete the index and table entries. Skip this step if pTab is really
** a view (in which case the only effect of the DELETE statement is to
** fire the INSTEAD OF triggers). */
if (pTab.pSelect == null)
{
sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count != 0 ? (int)OPFLAG_NCHANGE : 0));
if (count != 0)
{
sqlite3VdbeChangeP4(v, -1, pTab.zName, P4_TRANSIENT);
}
}
/* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
** handle rows (possibly in other tables) that refer via a foreign key
** to the row just deleted. */
sqlite3FkActions(pParse, pTab, null, iOld);
/* Invoke AFTER DELETE trigger programs. */
sqlite3CodeRowTrigger(pParse, pTrigger,
TK_DELETE, null, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
);
/* Jump here if the row had already been deleted before any BEFORE
** trigger programs were invoked. Or if a trigger program throws a
** RAISE(IGNORE) exception. */
sqlite3VdbeResolveLabel(v, iLabel);
}
/*
** This routine generates VDBE code that causes the deletion of all
** index entries associated with a single row of a single table.
**
** The VDBE must be in a particular state when this routine is called.
** These are the requirements:
**
** 1. A read/write cursor pointing to pTab, the table containing the row
** to be deleted, must be opened as cursor number "iCur".
**
** 2. Read/write cursors for all indices of pTab must be open as
** cursor number iCur+i for the i-th index.
**
** 3. The "iCur" cursor must be pointing to the row that is to be
** deleted.
*/
static void sqlite3GenerateRowIndexDelete(
Parse pParse, /* Parsing and code generating context */
Table pTab, /* Table containing the row to be deleted */
int iCur, /* VdbeCursor number for the table */
int nothing /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
)
{
int[] aRegIdx = null;
sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
}
static void sqlite3GenerateRowIndexDelete(
Parse pParse, /* Parsing and code generating context */
Table pTab, /* Table containing the row to be deleted */
int iCur, /* VdbeCursor number for the table */
int[] aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
)
{
int i;
Index pIdx;
int r1;
for (i = 1, pIdx = pTab.pIndex; pIdx != null; i++, pIdx = pIdx.pNext)
{
if (aRegIdx != null && aRegIdx[i - 1] == 0)
continue;
r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, false);
sqlite3VdbeAddOp3(pParse.pVdbe, OP_IdxDelete, iCur + i, r1, pIdx.nColumn + 1);
}
}
/*
** Generate code that will assemble an index key and put it in register
** regOut. The key with be for index pIdx which is an index on pTab.
** iCur is the index of a cursor open on the pTab table and pointing to
** the entry that needs indexing.
**
** Return a register number which is the first in a block of
** registers that holds the elements of the index key. The
** block of registers has already been deallocated by the time
** this routine returns.
*/
static int sqlite3GenerateIndexKey(
Parse pParse, /* Parsing context */
Index pIdx, /* The index for which to generate a key */
int iCur, /* VdbeCursor number for the pIdx.pTable table */
int regOut, /* Write the new index key to this register */
bool doMakeRec /* Run the OP_MakeRecord instruction if true */
)
{
Vdbe v = pParse.pVdbe;
int j;
Table pTab = pIdx.pTable;
int regBase;
int nCol;
nCol = pIdx.nColumn;
regBase = sqlite3GetTempRange(pParse, nCol + 1);
sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase + nCol);
for (j = 0; j < nCol; j++)
{
int idx = pIdx.aiColumn[j];
if (idx == pTab.iPKey)
{
sqlite3VdbeAddOp2(v, OP_SCopy, regBase + nCol, regBase + j);
}
else
{
sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase + j);
sqlite3ColumnDefault(v, pTab, idx, -1);
}
}
if (doMakeRec)
{
string zAff;
if (pTab.pSelect != null || (pParse.db.flags & SQLITE_IdxRealAsInt) != 0)
{
zAff = "";
}
else
{
zAff = sqlite3IndexAffinityStr(v, pIdx);
}
sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol + 1, regOut);
sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
}
sqlite3ReleaseTempRange(pParse, regBase, nCol + 1);
return regBase;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#region StyleCop Suppression - generated code
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
namespace Microsoft.Management.UI.Internal
{
/// <summary>
/// List control for Inner Applications. This Control supports grouping, sorting, filtering and GUI Virtualization through DataBinding.
/// </summary>
[Localizability(LocalizationCategory.None)]
partial class InnerList
{
//
// Copy routed command
//
static private void CopyCommand_CommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
InnerList obj = (InnerList) sender;
obj.OnCopyCanExecute( e );
}
static private void CopyCommand_CommandExecuted(object sender, ExecutedRoutedEventArgs e)
{
InnerList obj = (InnerList) sender;
obj.OnCopyExecuted( e );
}
/// <summary>
/// Called to determine if Copy can execute.
/// </summary>
protected virtual void OnCopyCanExecute(CanExecuteRoutedEventArgs e)
{
OnCopyCanExecuteImplementation(e);
}
partial void OnCopyCanExecuteImplementation(CanExecuteRoutedEventArgs e);
/// <summary>
/// Called when Copy executes.
/// </summary>
/// <remarks>
/// When executed, the currently selected items are copied to the clipboard.
/// </remarks>
protected virtual void OnCopyExecuted(ExecutedRoutedEventArgs e)
{
OnCopyExecutedImplementation(e);
}
partial void OnCopyExecutedImplementation(ExecutedRoutedEventArgs e);
//
// AutoGenerateColumns dependency property
//
/// <summary>
/// Identifies the AutoGenerateColumns dependency property.
/// </summary>
public static readonly DependencyProperty AutoGenerateColumnsProperty = DependencyProperty.Register( "AutoGenerateColumns", typeof(bool), typeof(InnerList), new PropertyMetadata( BooleanBoxes.FalseBox, AutoGenerateColumnsProperty_PropertyChanged) );
/// <summary>
/// Gets or sets a value indicating whether this list's columns should be automatically generated based on its data.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Gets or sets a value indicating whether this list's columns should be automatically generated based on its data.")]
[Localizability(LocalizationCategory.None)]
public bool AutoGenerateColumns
{
get
{
return (bool) GetValue(AutoGenerateColumnsProperty);
}
set
{
SetValue(AutoGenerateColumnsProperty,BooleanBoxes.Box(value));
}
}
static private void AutoGenerateColumnsProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
InnerList obj = (InnerList) o;
obj.OnAutoGenerateColumnsChanged( new PropertyChangedEventArgs<bool>((bool)e.OldValue, (bool)e.NewValue) );
}
/// <summary>
/// Occurs when AutoGenerateColumns property changes.
/// </summary>
public event EventHandler<PropertyChangedEventArgs<bool>> AutoGenerateColumnsChanged;
/// <summary>
/// Called when AutoGenerateColumns property changes.
/// </summary>
protected virtual void OnAutoGenerateColumnsChanged(PropertyChangedEventArgs<bool> e)
{
OnAutoGenerateColumnsChangedImplementation(e);
RaisePropertyChangedEvent(AutoGenerateColumnsChanged, e);
}
partial void OnAutoGenerateColumnsChangedImplementation(PropertyChangedEventArgs<bool> e);
//
// IsGroupsExpanded dependency property
//
/// <summary>
/// Identifies the IsGroupsExpanded dependency property.
/// </summary>
public static readonly DependencyProperty IsGroupsExpandedProperty = DependencyProperty.Register( "IsGroupsExpanded", typeof(bool), typeof(InnerList), new PropertyMetadata( BooleanBoxes.FalseBox, IsGroupsExpandedProperty_PropertyChanged) );
/// <summary>
/// Gets or sets a value indicating whether is groups expanded or not.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Gets or sets a value indicating whether is groups expanded or not.")]
[Localizability(LocalizationCategory.None)]
public bool IsGroupsExpanded
{
get
{
return (bool) GetValue(IsGroupsExpandedProperty);
}
set
{
SetValue(IsGroupsExpandedProperty,BooleanBoxes.Box(value));
}
}
static private void IsGroupsExpandedProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
InnerList obj = (InnerList) o;
obj.OnIsGroupsExpandedChanged( new PropertyChangedEventArgs<bool>((bool)e.OldValue, (bool)e.NewValue) );
}
/// <summary>
/// Occurs when IsGroupsExpanded property changes.
/// </summary>
public event EventHandler<PropertyChangedEventArgs<bool>> IsGroupsExpandedChanged;
/// <summary>
/// Called when IsGroupsExpanded property changes.
/// </summary>
protected virtual void OnIsGroupsExpandedChanged(PropertyChangedEventArgs<bool> e)
{
OnIsGroupsExpandedChangedImplementation(e);
RaisePropertyChangedEvent(IsGroupsExpandedChanged, e);
}
partial void OnIsGroupsExpandedChangedImplementation(PropertyChangedEventArgs<bool> e);
//
// IsPrimarySortColumn dependency property
//
/// <summary>
/// Identifies the IsPrimarySortColumn dependency property key.
/// </summary>
private static readonly DependencyPropertyKey IsPrimarySortColumnPropertyKey = DependencyProperty.RegisterAttachedReadOnly( "IsPrimarySortColumn", typeof(bool), typeof(InnerList), new PropertyMetadata( BooleanBoxes.FalseBox, IsPrimarySortColumnProperty_PropertyChanged) );
/// <summary>
/// Identifies the IsPrimarySortColumn dependency property.
/// </summary>
public static readonly DependencyProperty IsPrimarySortColumnProperty = IsPrimarySortColumnPropertyKey.DependencyProperty;
/// <summary>
/// Gets whether a column is the primary sort in a list.
/// </summary>
/// <param name="element">The dependency object that the property is attached to.</param>
/// <returns>
/// The value of IsPrimarySortColumn that is attached to element.
/// </returns>
static public bool GetIsPrimarySortColumn(DependencyObject element)
{
return (bool) element.GetValue(IsPrimarySortColumnProperty);
}
/// <summary>
/// Sets whether a column is the primary sort in a list.
/// </summary>
/// <param name="element">The dependency object that the property will be attached to.</param>
/// <param name="value">The new value.</param>
static private void SetIsPrimarySortColumn(DependencyObject element, bool value)
{
element.SetValue(IsPrimarySortColumnPropertyKey,BooleanBoxes.Box(value));
}
static private void IsPrimarySortColumnProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
IsPrimarySortColumnProperty_PropertyChangedImplementation(o, e);
}
static partial void IsPrimarySortColumnProperty_PropertyChangedImplementation(DependencyObject o, DependencyPropertyChangedEventArgs e);
/// <summary>
/// Called when a property changes.
/// </summary>
private void RaisePropertyChangedEvent<T>(EventHandler<PropertyChangedEventArgs<T>> eh, PropertyChangedEventArgs<T> e)
{
if (eh != null)
{
eh(this,e);
}
}
//
// Static constructor
//
/// <summary>
/// Called when the type is initialized.
/// </summary>
static InnerList()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(InnerList), new FrameworkPropertyMetadata(typeof(InnerList)));
CommandManager.RegisterClassCommandBinding( typeof(InnerList), new CommandBinding( ApplicationCommands.Copy, CopyCommand_CommandExecuted, CopyCommand_CommandCanExecute ));
StaticConstructorImplementation();
}
static partial void StaticConstructorImplementation();
}
}
#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.IO;
using Microsoft.Build.Tasks;
using Microsoft.Build.Utilities;
using Microsoft.Build.Shared;
using Xunit;
using System.Linq;
using System.Runtime.InteropServices;
using Shouldly;
namespace Microsoft.Build.UnitTests
{
/// <summary>
/// Tests for write code fragment task
/// </summary>
public class WriteCodeFragment_Tests
{
/// <summary>
/// Need an available language
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void InvalidLanguage()
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
task.Language = "xx";
task.OutputFile = new TaskItem("foo");
bool result = task.Execute();
Assert.False(result);
engine.AssertLogContains("MSB3712");
}
/// <summary>
/// Need a language
/// </summary>
[Fact]
public void NoLanguage()
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
task.OutputFile = new TaskItem("foo");
bool result = task.Execute();
Assert.False(result);
engine.AssertLogContains("MSB3098");
}
/// <summary>
/// Need a location
/// </summary>
[Fact]
public void NoFileOrDirectory()
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
task.Language = "c#";
bool result = task.Execute();
Assert.False(result);
engine.AssertLogContains("MSB3711");
}
/// <summary>
/// Combine file and directory
/// </summary>
[Fact]
public void CombineFileDirectory()
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
task.Language = "c#";
task.AssemblyAttributes = new TaskItem[] { new TaskItem("aa") };
task.OutputFile = new TaskItem("CombineFileDirectory.tmp");
task.OutputDirectory = new TaskItem(Path.GetTempPath());
bool result = task.Execute();
Assert.True(result);
string file = Path.Combine(Path.GetTempPath(), "CombineFileDirectory.tmp");
Assert.Equal(file, task.OutputFile.ItemSpec);
Assert.True(File.Exists(file));
}
/// <summary>
/// Ignore directory if file is rooted
/// </summary>
[Fact]
public void DirectoryAndRootedFile()
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
task.Language = "c#";
task.AssemblyAttributes = new TaskItem[] { new TaskItem("aa") };
string folder = Path.Combine(Path.GetTempPath(), "foo" + Path.DirectorySeparatorChar);
string file = Path.Combine(folder, "CombineFileDirectory.tmp");
Directory.CreateDirectory(folder);
task.OutputFile = new TaskItem(file);
task.OutputDirectory = new TaskItem("c:\\");
bool result = task.Execute();
Assert.True(result);
Assert.Equal(file, task.OutputFile.ItemSpec);
Assert.True(File.Exists(file));
FileUtilities.DeleteWithoutTrailingBackslash(folder, true);
}
/// <summary>
/// Given nothing to write, should succeed but
/// produce no output file
/// </summary>
[Fact]
public void NoAttributesShouldEmitNoFile()
{
string file = Path.Combine(Path.GetTempPath(), "NoAttributesShouldEmitNoFile.tmp");
if (File.Exists(file))
{
File.Delete(file);
}
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
task.Language = "c#";
task.AssemblyAttributes = new TaskItem[] { }; // MSBuild sets an empty array
task.OutputFile = new TaskItem(file);
bool result = task.Execute();
Assert.True(result);
Assert.False(File.Exists(file));
Assert.Null(task.OutputFile);
}
/// <summary>
/// Given nothing to write, should succeed but
/// produce no output file
/// </summary>
[Fact]
public void NoAttributesShouldEmitNoFile2()
{
string file = Path.Combine(Path.GetTempPath(), "NoAttributesShouldEmitNoFile.tmp");
if (File.Exists(file))
{
File.Delete(file);
}
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
task.Language = "c#";
task.AssemblyAttributes = null; // null this time
task.OutputFile = new TaskItem(file);
bool result = task.Execute();
Assert.True(result);
Assert.False(File.Exists(file));
Assert.Null(task.OutputFile);
}
/// <summary>
/// Bad file path
/// </summary>
[Fact]
public void InvalidFilePath()
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
task.Language = "c#";
task.AssemblyAttributes = new TaskItem[] { new TaskItem("aa") };
task.OutputFile = new TaskItem("||//invalid||");
bool result = task.Execute();
Assert.False(result);
engine.AssertLogContains("MSB3713");
}
/// <summary>
/// Bad directory path
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // "No invalid characters on Unix"
public void InvalidDirectoryPath()
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
task.Language = "c#";
task.AssemblyAttributes = new TaskItem[] { new TaskItem("aa") };
task.OutputDirectory = new TaskItem("||invalid||");
bool result = task.Execute();
Assert.False(result);
engine.AssertLogContains("MSB3713");
}
/// <summary>
/// Parameterless attribute
/// </summary>
[Fact]
public void OneAttributeNoParams()
{
string file = Path.Combine(Path.GetTempPath(), "OneAttribute.tmp");
try
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
TaskItem attribute = new TaskItem("System.AssemblyTrademarkAttribute");
task.AssemblyAttributes = new TaskItem[] { attribute };
task.Language = "c#";
task.OutputFile = new TaskItem(file);
bool result = task.Execute();
Assert.True(result);
Assert.True(File.Exists(file));
string content = File.ReadAllText(file);
Console.WriteLine(content);
CheckContentCSharp(content, "[assembly: System.AssemblyTrademarkAttribute()]");
}
finally
{
File.Delete(file);
}
}
/// <summary>
/// Test with the VB language
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void OneAttributeNoParamsVb()
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
TaskItem attribute = new TaskItem("System.AssemblyTrademarkAttribute");
task.AssemblyAttributes = new TaskItem[] { attribute };
task.Language = "visualbasic";
task.OutputDirectory = new TaskItem(Path.GetTempPath());
bool result = task.Execute();
Assert.True(result);
string content = File.ReadAllText(task.OutputFile.ItemSpec);
Console.WriteLine(content);
CheckContentVB(content, "<Assembly: System.AssemblyTrademarkAttribute()>");
}
/// <summary>
/// More than one attribute
/// </summary>
[Fact]
public void TwoAttributes()
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
TaskItem attribute1 = new TaskItem("AssemblyTrademarkAttribute");
attribute1.SetMetadata("Name", "Microsoft");
TaskItem attribute2 = new TaskItem("System.AssemblyCultureAttribute");
attribute2.SetMetadata("Culture", "en-US");
task.AssemblyAttributes = new TaskItem[] { attribute1, attribute2 };
task.Language = "c#";
task.OutputDirectory = new TaskItem(Path.GetTempPath());
bool result = task.Execute();
Assert.True(result);
string content = File.ReadAllText(task.OutputFile.ItemSpec);
Console.WriteLine(content);
CheckContentCSharp(
content,
@"[assembly: AssemblyTrademarkAttribute(Name=""Microsoft"")]",
@"[assembly: System.AssemblyCultureAttribute(Culture=""en-US"")]");
}
/// <summary>
/// Specify directory instead
/// </summary>
[Fact]
public void ToDirectory()
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
TaskItem attribute = new TaskItem("System.AssemblyTrademarkAttribute");
task.AssemblyAttributes = new TaskItem[] { attribute };
task.Language = "c#";
task.OutputDirectory = new TaskItem(Path.GetTempPath());
bool result = task.Execute();
Assert.True(result);
Assert.True(File.Exists(task.OutputFile.ItemSpec));
Assert.Equal(Path.GetTempPath(), task.OutputFile.ItemSpec.Substring(0, Path.GetTempPath().Length));
Assert.Equal(".cs", task.OutputFile.ItemSpec.Substring(task.OutputFile.ItemSpec.Length - 3));
File.Delete(task.OutputFile.ItemSpec);
}
/// <summary>
/// Regular case
/// </summary>
[Fact]
public void OneAttributeTwoParams()
{
string file = Path.Combine(Path.GetTempPath(), "OneAttribute.tmp");
try
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute");
attribute.SetMetadata("Company", "Microsoft");
attribute.SetMetadata("Year", "2009");
task.AssemblyAttributes = new TaskItem[] { attribute };
task.Language = "c#";
task.OutputFile = new TaskItem(file);
bool result = task.Execute();
Assert.True(result);
Assert.True(File.Exists(file));
string content = File.ReadAllText(file);
Console.WriteLine(content);
CheckContentCSharp(content, @"[assembly: AssemblyTrademarkAttribute(Company=""Microsoft"", Year=""2009"")]");
}
finally
{
File.Delete(file);
}
}
/// <summary>
/// This produces invalid code, but the task works
/// </summary>
[Fact]
public void OneAttributeTwoParamsSameName()
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute");
attribute.SetMetadata("Company", "Microsoft");
attribute.SetMetadata("Company", "2009");
task.AssemblyAttributes = new TaskItem[] { attribute };
task.Language = "c#";
task.OutputDirectory = new TaskItem(Path.GetTempPath());
bool result = task.Execute();
Assert.True(result);
File.Delete(task.OutputFile.ItemSpec);
}
/// <summary>
/// Some attributes only allow positional constructor arguments.
/// To set those, use metadata names like "_Parameter1", "_Parameter2" etc.
/// </summary>
[Fact]
public void OneAttributePositionalParamInvalidSuffix()
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute");
attribute.SetMetadata("_ParameterXXXXXXXXXX", "Microsoft");
task.AssemblyAttributes = new TaskItem[] { attribute };
task.Language = "c#";
task.OutputDirectory = new TaskItem(Path.GetTempPath());
bool result = task.Execute();
Assert.False(result);
engine.AssertLogContains("MSB3098");
}
/// <summary>
/// Some attributes only allow positional constructor arguments.
/// To set those, use metadata names like "_Parameter1", "_Parameter2" etc.
/// </summary>
[Fact]
public void OneAttributeTwoPositionalParams()
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute");
attribute.SetMetadata("_Parameter1", "Microsoft");
attribute.SetMetadata("_Parameter2", "2009");
task.AssemblyAttributes = new TaskItem[] { attribute };
task.Language = "c#";
task.OutputDirectory = new TaskItem(Path.GetTempPath());
bool result = task.Execute();
Assert.True(result);
string content = File.ReadAllText(task.OutputFile.ItemSpec);
Console.WriteLine(content);
CheckContentCSharp(content, @"[assembly: AssemblyTrademarkAttribute(""Microsoft"", ""2009"")]");
File.Delete(task.OutputFile.ItemSpec);
}
[Fact]
public void OneAttributeTwoPositionalParamsWithSameValue()
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
TaskItem attribute = new TaskItem("AssemblyMetadataAttribute");
attribute.SetMetadata("_Parameter1", "TestValue");
attribute.SetMetadata("_Parameter2", "TestValue");
task.AssemblyAttributes = new TaskItem[] { attribute };
task.Language = "c#";
task.OutputDirectory = new TaskItem(Path.GetTempPath());
bool result = task.Execute();
Assert.True(result);
string content = File.ReadAllText(task.OutputFile.ItemSpec);
Console.WriteLine(content);
CheckContentCSharp(content, @"[assembly: AssemblyMetadataAttribute(""TestValue"", ""TestValue"")]");
File.Delete(task.OutputFile.ItemSpec);
}
public static string EscapedLineSeparator => NativeMethodsShared.IsWindows ? "\\r\\n" : "\\n";
/// <summary>
/// Multi line argument values should cause a verbatim string to be used
/// </summary>
[Fact]
public void MultilineAttributeCSharp()
{
var lines = new[] { "line 1", "line 2", "line 3" };
var multilineString = String.Join(Environment.NewLine, lines);
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
TaskItem attribute = new TaskItem("System.Reflection.AssemblyDescriptionAttribute");
attribute.SetMetadata("_Parameter1", multilineString);
attribute.SetMetadata("Description", multilineString);
task.AssemblyAttributes = new TaskItem[] { attribute };
task.Language = "c#";
task.OutputDirectory = new TaskItem(Path.GetTempPath());
bool result = task.Execute();
Assert.True(result);
string content = File.ReadAllText(task.OutputFile.ItemSpec);
Console.WriteLine(content);
var csMultilineString = lines.Aggregate((l1, l2) => l1 + EscapedLineSeparator + l2);
CheckContentCSharp(content, $"[assembly: System.Reflection.AssemblyDescriptionAttribute(\"{csMultilineString}\", Description=\"{csMultilineString}\")]");
File.Delete(task.OutputFile.ItemSpec);
}
private static readonly string VBCarriageReturn = "Global.Microsoft.VisualBasic.ChrW(13)";
private static readonly string VBLineFeed = "Global.Microsoft.VisualBasic.ChrW(10)";
public static readonly string VBLineSeparator = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"{VBCarriageReturn}&{VBLineFeed}" : VBLineFeed;
/// <summary>
/// Multi line argument values should cause a verbatim string to be used
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void MultilineAttributeVB()
{
var lines = new []{ "line 1", "line 2", "line 3" };
var multilineString = String.Join(Environment.NewLine, lines);
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
TaskItem attribute = new TaskItem("System.Reflection.AssemblyDescriptionAttribute");
attribute.SetMetadata("_Parameter1", multilineString);
attribute.SetMetadata("Description", multilineString);
task.AssemblyAttributes = new TaskItem[] { attribute };
task.Language = "visualbasic";
task.OutputDirectory = new TaskItem(Path.GetTempPath());
bool result = task.Execute();
Assert.True(result);
string content = File.ReadAllText(task.OutputFile.ItemSpec);
Console.WriteLine(content);
var vbMultilineString = lines
.Select(l => $"\"{l}\"")
.Aggregate((l1, l2) => $"{l1}&{VBLineSeparator}&{l2}");
CheckContentVB(content, $"<Assembly: System.Reflection.AssemblyDescriptionAttribute({vbMultilineString}, Description:={vbMultilineString})>");
File.Delete(task.OutputFile.ItemSpec);
}
/// <summary>
/// Some attributes only allow positional constructor arguments.
/// To set those, use metadata names like "_Parameter1", "_Parameter2" etc.
/// If a parameter is skipped, it's an error.
/// </summary>
[Fact]
public void OneAttributeSkippedPositionalParams()
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute");
attribute.SetMetadata("_Parameter2", "2009");
task.AssemblyAttributes = new TaskItem[] { attribute };
task.Language = "c#";
task.OutputDirectory = new TaskItem(Path.GetTempPath());
bool result = task.Execute();
Assert.False(result);
engine.AssertLogContains("MSB3714");
}
/// <summary>
/// Some attributes only allow positional constructor arguments.
/// To set those, use metadata names like "_Parameter1", "_Parameter2" etc.
/// This test is for "_ParameterX"
/// </summary>
[Fact]
public void InvalidNumber()
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute");
attribute.SetMetadata("_ParameterX", "2009");
task.AssemblyAttributes = new TaskItem[] { attribute };
task.Language = "c#";
task.OutputDirectory = new TaskItem(Path.GetTempPath());
bool result = task.Execute();
Assert.False(result);
engine.AssertLogContains("MSB3098");
}
/// <summary>
/// Some attributes only allow positional constructor arguments.
/// To set those, use metadata names like "_Parameter1", "_Parameter2" etc.
/// This test is for "_Parameter"
/// </summary>
[Fact]
public void NoNumber()
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute");
attribute.SetMetadata("_Parameter", "2009");
task.AssemblyAttributes = new TaskItem[] { attribute };
task.Language = "c#";
task.OutputDirectory = new TaskItem(Path.GetTempPath());
bool result = task.Execute();
Assert.False(result);
engine.AssertLogContains("MSB3098");
}
/// <summary>
/// Some attributes only allow positional constructor arguments.
/// To set those, use metadata names like "_Parameter1", "_Parameter2" etc.
/// These can also be combined with named params.
/// </summary>
[Fact]
public void OneAttributePositionalAndNamedParams()
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute");
attribute.SetMetadata("_Parameter1", "Microsoft");
attribute.SetMetadata("Date", "2009");
attribute.SetMetadata("Copyright", "(C)");
task.AssemblyAttributes = new TaskItem[] { attribute };
task.Language = "c#";
task.OutputDirectory = new TaskItem(Path.GetTempPath());
bool result = task.Execute();
Assert.True(result);
string content = File.ReadAllText(task.OutputFile.ItemSpec);
Console.WriteLine(content);
// NOTE: order here is defined by dictionary traversal order and may change
// based on implementation details there, but named parameters can have different
// orders so that's ok.
CheckContentCSharp(content, @"[assembly: AssemblyTrademarkAttribute(""Microsoft"", Copyright=""(C)"", Date=""2009"")]");
File.Delete(task.OutputFile.ItemSpec);
}
/// <summary>
/// Some attributes only allow positional constructor arguments.
/// To set those, use metadata names like "_Parameter1", "_Parameter2" etc.
/// These can also be combined with named params.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void OneAttributePositionalAndNamedParamsVisualBasic()
{
WriteCodeFragment task = new WriteCodeFragment();
MockEngine engine = new MockEngine(true);
task.BuildEngine = engine;
TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute");
attribute.SetMetadata("_Parameter1", "Microsoft");
attribute.SetMetadata("_Parameter2", "2009");
attribute.SetMetadata("Copyright", "(C)");
task.AssemblyAttributes = new TaskItem[] { attribute };
task.Language = "visualbasic";
task.OutputDirectory = new TaskItem(Path.GetTempPath());
bool result = task.Execute();
Assert.True(result);
string content = File.ReadAllText(task.OutputFile.ItemSpec);
Console.WriteLine(content);
CheckContentVB(content, @"<Assembly: AssemblyTrademarkAttribute(""Microsoft"", ""2009"", Copyright:=""(C)"")>");
File.Delete(task.OutputFile.ItemSpec);
}
/// <summary>
/// A type can be declared for a positional arguments using the metadata
/// "_Parameter1_TypeName" where the value is the full type name.
/// </summary>
[Fact]
public void DeclaredTypeForPositionalParameter()
{
TaskItem attribute = new("CLSCompliantAttribute");
attribute.SetMetadata("_Parameter1", "True");
attribute.SetMetadata("_Parameter1_TypeName", "System.Boolean");
ExecuteAndVerifySuccess(
CreateTask("c#", attribute),
@"[assembly: CLSCompliantAttribute(true)]"
);
}
/// <summary>
/// A type can be declared for a positional arguments using the metadata
/// "Foo_TypeName" where the value is the full type name.
/// </summary>
[Fact]
public void DeclaredTypeForNamedParameter()
{
TaskItem attribute = new TaskItem("TestAttribute");
attribute.SetMetadata("BoolArgument", "False");
attribute.SetMetadata("BoolArgument_TypeName", "System.Boolean");
attribute.SetMetadata("Int32Argument", "42");
attribute.SetMetadata("Int32Argument_TypeName", "System.Int32");
ExecuteAndVerifySuccess(
CreateTask("c#", attribute),
@"[assembly: TestAttribute(Int32Argument=42, BoolArgument=false)]"
);
}
/// <summary>
/// Metadata that looks like a declared type, but doesn't have corresponding named parameter
/// metadata should be treated as another named parameter for backward-compatibility.
/// </summary>
[Fact]
public void DeclaredTypedWithoutCorrespondingNamedParameter()
{
TaskItem attribute = new TaskItem("TestAttribute");
attribute.SetMetadata("BoolArgument", "False");
attribute.SetMetadata("BoolArgument_TypeName", "System.Boolean");
attribute.SetMetadata("Int32Argument_TypeName", "System.Int32");
ExecuteAndVerifySuccess(
CreateTask("c#", attribute),
@"[assembly: TestAttribute(Int32Argument_TypeName=""System.Int32"", BoolArgument=false)]"
);
}
/// <summary>
/// An unknown type name for a parameter should cause a failure.
/// </summary>
[Fact]
public void DeclaredTypeIsUnknown()
{
TaskItem attribute = new("TestAttribute");
attribute.SetMetadata("TestParameter", "99");
attribute.SetMetadata("TestParameter_TypeName", "Foo.Bar");
ExecuteAndVerifyFailure(
CreateTask("c#", attribute),
"MSB3715"
);
}
/// <summary>
/// A parameter value that cannot be converted to the declared type should cause a failure.
/// </summary>
[Fact]
public void DeclaredTypeCausesConversionFailure()
{
TaskItem attribute = new("TestAttribute");
attribute.SetMetadata("TestParameter", "99");
attribute.SetMetadata("TestParameter_TypeName", "System.Boolean");
ExecuteAndVerifyFailure(
CreateTask("c#", attribute),
"MSB3716"
);
}
/// <summary>
/// Parameter value that is too large for the declared data type should cause a failure.
/// </summary>
[Fact]
public void DeclaredTypeCausesOverflow()
{
TaskItem attribute = new("TestAttribute");
attribute.SetMetadata("TestParameter", "1000");
attribute.SetMetadata("TestParameter_TypeName", "System.Byte");
ExecuteAndVerifyFailure(
CreateTask("c#", attribute),
"MSB3716"
);
}
/// <summary>
/// The metadata value should convert successfully to an enum.
/// </summary>
[Fact]
public void DeclaredTypeIsEnum()
{
TaskItem attribute = new("TestAttribute");
attribute.SetMetadata("_Parameter1", "Local");
attribute.SetMetadata("_Parameter1_TypeName", "System.DateTimeKind");
ExecuteAndVerifySuccess(
CreateTask("c#", attribute),
@"[assembly: TestAttribute(System.DateTimeKind.Local)]"
);
}
/// <summary>
/// The metadata value should convert successfully to a type name in C#.
/// </summary>
[Fact]
public void DeclaredTypeIsTypeInCSharp()
{
TaskItem attribute = new("TestAttribute");
attribute.SetMetadata("_Parameter1", "System.Console");
attribute.SetMetadata("_Parameter1_TypeName", "System.Type");
ExecuteAndVerifySuccess(
CreateTask("c#", attribute),
@"[assembly: TestAttribute(typeof(System.Console))]"
);
}
/// <summary>
/// The metadata value should convert successfully to a type name in VB.NET.
/// </summary>
[Fact]
public void DeclaredTypeIsTypeInVB()
{
TaskItem attribute = new("TestAttribute");
attribute.SetMetadata("_Parameter1", "System.Console");
attribute.SetMetadata("_Parameter1_TypeName", "System.Type");
ExecuteAndVerifySuccess(
CreateTask("visualbasic", attribute),
@"<Assembly: TestAttribute(GetType(System.Console))>"
);
}
/// <summary>
/// Arrays are not supported for declared types. Literal arguments need to be used instead.
/// This test confirms that it fails instead of falling back to being treated as a string.
/// </summary>
[Fact]
public void DeclaredTypeOfArrayIsNotSupported()
{
TaskItem attribute = new("TestAttribute");
attribute.SetMetadata("_Parameter1", "1,2,3");
attribute.SetMetadata("_Parameter1_TypeName", "System.Int32[]");
ExecuteAndVerifyFailure(
CreateTask("c#", attribute),
"MSB3716"
);
}
/// <summary>
/// The exact code for a positional argument can be specified using
/// the metadata "_Parameter1_IsLiteral" with a value of "true".
/// </summary>
[Fact]
public void LiteralPositionalParameter()
{
TaskItem attribute = new("TestAttribute");
attribute.SetMetadata("_Parameter1", "42 /* A comment */");
attribute.SetMetadata("_Parameter1_IsLiteral", "true");
ExecuteAndVerifySuccess(
CreateTask("c#", attribute),
@"[assembly: TestAttribute(42 /* A comment */)]"
);
}
/// <summary>
/// The exact code for a named argument can be specified using
/// the metadata "Foo_IsLiteral" with a value of "true".
/// </summary>
[Fact]
public void LiteralNamedParameter()
{
TaskItem attribute = new("TestAttribute");
attribute.SetMetadata("TestParameter", "42 /* A comment */");
attribute.SetMetadata("TestParameter_IsLiteral", "true");
ExecuteAndVerifySuccess(
CreateTask("c#", attribute),
@"[assembly: TestAttribute(TestParameter=42 /* A comment */)]"
);
}
/// <summary>
/// The type of a positional argument can be inferred
/// if the type of the attribute is in mscorlib.
/// </summary>
[Fact]
public void InferredTypeForPositionalParameter()
{
TaskItem attribute = new("CLSCompliantAttribute");
attribute.SetMetadata("_Parameter1", "True");
ExecuteAndVerifySuccess(
CreateTask("c#", attribute),
@"[assembly: CLSCompliantAttribute(true)]"
);
}
/// <summary>
/// The type of a named argument can be inferred
/// if the type of the attribute is in mscorlib.
/// </summary>
[Fact]
public void InferredTypeForNamedParameter()
{
TaskItem attribute = new("System.Runtime.CompilerServices.InternalsVisibleToAttribute");
attribute.SetMetadata("_Parameter1", "MyAssembly");
attribute.SetMetadata("AllInternalsVisible", "True");
ExecuteAndVerifySuccess(
CreateTask("c#", attribute),
@"[assembly: System.Runtime.CompilerServices.InternalsVisibleToAttribute(""MyAssembly"", AllInternalsVisible=true)]"
);
}
/// <summary>
/// For backward-compatibility, if multiple constructors are found with the same number
/// of position arguments that was specified in the metadata, then the constructor that
/// has strings for every parameter should be used.
/// </summary>
[Fact]
public void InferredTypePrefersStringWhenMultipleConstructorsAreFound()
{
TaskItem attribute = new("System.Diagnostics.Contracts.ContractOptionAttribute");
attribute.SetMetadata("_Parameter1", "a");
attribute.SetMetadata("_Parameter2", "b");
attribute.SetMetadata("_Parameter3", "false");
// There are two constructors with three parameters:
// * ContractOptionAttribute(string, string, bool)
// * ContractOptionAttribute(string, string, string)
//
// The first overload would come first when comparing the type names
// ("System.Boolean" comes before "System.String"), but because we
// need to remain backward-compatible, the constructor that takes
// all strings should be preferred over all other constructors.
ExecuteAndVerifySuccess(
CreateTask("c#", attribute),
@"[assembly: System.Diagnostics.Contracts.ContractOptionAttribute(""a"", ""b"", ""false"")]"
);
}
/// <summary>
/// When multiple constructors are found with the same number of
/// position arguments that was specified in the metadata, and none
/// of them have parameters of all strings, then the constructors
/// should be sorted by the names of the parameter types.
/// The first constructor is then selected.
/// </summary>
[Fact]
public void InferredTypeWithMultipleAttributeConstructorsIsDeterministic()
{
TaskItem attribute = new("System.Reflection.AssemblyFlagsAttribute");
attribute.SetMetadata("_Parameter1", "2");
// There are three constructors with a single parameter:
// * AssemblyFlagsAttribute(int)
// * AssemblyFlagsAttribute(uint)
// * AssemblyFlagsAttribute(System.Reflection.AssemblyNameFlags)
//
// The int overload should be used, because "System.Int32"
// is alphabetically before any of the other types.
ExecuteAndVerifySuccess(
CreateTask("c#", attribute),
@"[assembly: System.Reflection.AssemblyFlagsAttribute(2)]"
);
// To prove that it's treating the argument as an int,
// we can specify an enum value which should fail type
// conversion and fall back to being used as a string.
attribute.SetMetadata("_Parameter1", "PublicKey");
ExecuteAndVerifySuccess(
CreateTask("c#", attribute),
@"[assembly: System.Reflection.AssemblyFlagsAttribute(""PublicKey"")]"
);
}
/// <summary>
/// If the attribute type is not in mscorlib, then the
/// parameter should be treated as a string when the parameter
/// is not given a declared type or is not marked as a literal.
/// </summary>
[Fact]
public void InferredTypeFallsBackToStringWhenTypeCannotBeInferred()
{
// Use an attribute that is not in mscorlib. TypeConverterAttribute is in the "System" assembly.
TaskItem attribute = new("System.ComponentModel.TypeConverterAttribute");
attribute.SetMetadata("_Parameter1", "false");
ExecuteAndVerifySuccess(
CreateTask("c#", attribute),
@"[assembly: System.ComponentModel.TypeConverterAttribute(""false"")]"
);
}
/// <summary>
/// If the parameter type cannot be converted to the inferred type,
/// then the parameter should be treated as a string.
/// </summary>
[Fact]
public void InferredTypeFallsBackToStringWhenTypeConversionFails()
{
TaskItem attribute = new("System.Diagnostics.DebuggableAttribute");
attribute.SetMetadata("_Parameter1", "True"); // Should be a boolean. Will be converted.
attribute.SetMetadata("_Parameter2", "42"); // Should be a boolean. Will fail type conversion.
ExecuteAndVerifySuccess(
CreateTask("c#", attribute),
@"[assembly: System.Diagnostics.DebuggableAttribute(true, ""42"")]"
);
}
/// <summary>
/// Individual parameters can be typed differently.
/// </summary>
[Fact]
public void UsingInferredDeclaredTypesAndLiteralsInSameAttribute()
{
TaskItem attribute = new("System.Diagnostics.Contracts.ContractOptionAttribute");
attribute.SetMetadata("_Parameter1", "foo"); // Inferred as string.
attribute.SetMetadata("_Parameter2", @"""bar"" /* setting */"); // Literal string.
attribute.SetMetadata("_Parameter2_IsLiteral", "true");
attribute.SetMetadata("_Parameter3", "False"); // Typed as boolean.
attribute.SetMetadata("_Parameter3_TypeName", "System.Boolean");
ExecuteAndVerifySuccess(
CreateTask("c#", attribute),
@"[assembly: System.Diagnostics.Contracts.ContractOptionAttribute(""foo"", ""bar"" /* setting */, false)]"
);
}
private WriteCodeFragment CreateTask(string language, params TaskItem[] attributes)
{
WriteCodeFragment task = new();
task.Language = language;
task.OutputDirectory = new TaskItem(Path.GetTempPath());
task.AssemblyAttributes = attributes;
return task;
}
private void ExecuteAndVerifySuccess(WriteCodeFragment task, params string[] expectedAttributes)
{
MockEngine engine = new(true);
task.BuildEngine = engine;
try
{
var result = task.Execute();
// Provide the log output as the user message so that the assertion failure
// message is a bit more meaningful than just "Expected false to equal true".
Assert.True(result, engine.Log);
string content = File.ReadAllText(task.OutputFile.ItemSpec);
Console.WriteLine(content);
if (task.Language == "c#")
{
CheckContentCSharp(content, expectedAttributes);
}
else
{
CheckContentVB(content, expectedAttributes);
}
}
finally
{
if ((task.OutputFile is not null) && File.Exists(task.OutputFile.ItemSpec))
{
File.Delete(task.OutputFile.ItemSpec);
}
}
}
private void ExecuteAndVerifyFailure(WriteCodeFragment task, string errorCode)
{
MockEngine engine = new(true);
task.BuildEngine = engine;
try
{
var result = task.Execute();
// Provide the log output as the user message so that the assertion failure
// message is a bit more meaningful than just "Expected true to equal false".
Assert.False(result, engine.Log);
engine.AssertLogContains(errorCode);
}
finally
{
if ((task.OutputFile is not null) && File.Exists(task.OutputFile.ItemSpec))
{
File.Delete(task.OutputFile.ItemSpec);
}
}
}
private static void CheckContentCSharp(string actualContent, params string[] expectedAttributes)
{
CheckContent(
actualContent,
expectedAttributes,
"//",
"using System;",
"using System.Reflection;");
}
private static void CheckContentVB(string actualContent, params string[] expectedAttributes)
{
CheckContent(
actualContent,
expectedAttributes,
"'",
"Option Strict Off",
"Option Explicit On",
"Imports System",
"Imports System.Reflection");
}
private static void CheckContent(string actualContent, string[] expectedAttributes, string commentStart, params string[] expectedHeader)
{
string expectedContent = string.Join(Environment.NewLine, expectedHeader.Concat(expectedAttributes));
// we tolerate differences in whitespace and comments between platforms
string normalizedActualContent = string.Join(
Environment.NewLine,
actualContent.Split(MSBuildConstants.CrLf)
.Select(line => line.Trim())
.Where(line => line.Length > 0 && !line.StartsWith(commentStart)));
expectedContent.ShouldBe(normalizedActualContent);
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.Utilclass.DN.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
using System.Collections;
namespace Novell.Directory.LDAP.VQ.Utilclass
{
/// <summary> A DN encapsulates a Distinguished Name (an ldap name with context). A DN
/// does not need to be fully distinguished, or extend to the Root of a
/// directory. It provides methods to get information about the DN and to
/// manipulate the DN.
///
/// The following are examples of valid DN:
/// <ul>
/// <li>cn=admin,ou=marketing,o=corporation</li>
/// <li>cn=admin,ou=marketing</li>
/// <li>2.5.4.3=admin,ou=marketing</li>
/// <li>oid.2.5.4.3=admin,ou=marketing</li>
/// </ul>
///
/// Note: Multivalued attributes are all considered to be one
/// component and are represented in one RDN (see RDN)
///
///
/// </summary>
/// <seealso cref="RDN">
/// </seealso>
public class DN : object
{
private void InitBlock()
{
rdnList = new ArrayList();
}
/// <summary> Retrieves a list of RDN Objects, or individual names of the DN</summary>
/// <returns> list of RDNs
/// </returns>
virtual public ArrayList RDNs
{
get
{
int size = rdnList.Count;
ArrayList v = new ArrayList(size);
for (int i = 0; i < size; i++)
{
v.Add(rdnList[i]);
}
return v;
}
}
/// <summary> Returns the Parent of this DN</summary>
/// <returns> Parent DN
/// </returns>
virtual public DN Parent
{
get
{
DN parent = new DN();
parent.rdnList = (ArrayList)rdnList.Clone();
if (parent.rdnList.Count >= 1)
parent.rdnList.Remove(rdnList[0]); //remove first object
return parent;
}
}
//parser state identifiers.
private const int LOOK_FOR_RDN_ATTR_TYPE = 1;
private const int ALPHA_ATTR_TYPE = 2;
private const int OID_ATTR_TYPE = 3;
private const int LOOK_FOR_RDN_VALUE = 4;
private const int QUOTED_RDN_VALUE = 5;
private const int HEX_RDN_VALUE = 6;
private const int UNQUOTED_RDN_VALUE = 7;
/* State transition table: Parsing starts in state 1.
State COMMA DIGIT "Oid." ALPHA EQUAL QUOTE SHARP HEX
--------------------------------------------------------------------
1 Err 3 3 2 Err Err Err Err
2 Err Err Err 2 4 Err Err Err
3 Err 3 Err Err 4 Err Err Err
4 Err 7 Err 7 Err 5 6 7
5 1 5 Err 5 Err 1 Err 7
6 1 6 Err Err Err Err Err 6
7 1 7 Err 7 Err Err Err 7
*/
private ArrayList rdnList;
public DN()
{
InitBlock();
return;
}
/// <summary> Constructs a new DN based on the specified string representation of a
/// distinguished name. The syntax of the DN must conform to that specified
/// in RFC 2253.
///
/// </summary>
/// <param name="dnString">a string representation of the distinguished name
/// </param>
/// <exception> IllegalArgumentException if the the value of the dnString
/// parameter does not adhere to the syntax described in
/// RFC 2253
/// </exception>
public DN(string dnString)
{
InitBlock();
/* the empty string is a valid DN */
if (dnString.Length == 0)
return;
char currChar;
char nextChar;
int currIndex;
char[] tokenBuf = new char[dnString.Length];
int tokenIndex;
int lastIndex;
int valueStart;
int state;
int trailingSpaceCount = 0;
string attrType = "";
string attrValue = "";
string rawValue = "";
int hexDigitCount = 0;
RDN currRDN = new RDN();
//indicates whether an OID number has a first digit of ZERO
bool firstDigitZero = false;
tokenIndex = 0;
currIndex = 0;
valueStart = 0;
state = LOOK_FOR_RDN_ATTR_TYPE;
lastIndex = dnString.Length - 1;
while (currIndex <= lastIndex)
{
currChar = dnString[currIndex];
switch (state)
{
case LOOK_FOR_RDN_ATTR_TYPE:
while (currChar == ' ' && (currIndex < lastIndex))
currChar = dnString[++currIndex];
if (isAlpha(currChar))
{
if (dnString.Substring(currIndex).StartsWith("oid.") || dnString.Substring(currIndex).StartsWith("OID."))
{
//form is "oid.###.##.###... or OID.###.##.###...
currIndex += 4; //skip oid. prefix and get to actual oid
if (currIndex > lastIndex)
throw new ArgumentException(dnString);
currChar = dnString[currIndex];
if (isDigit(currChar))
{
tokenBuf[tokenIndex++] = currChar;
state = OID_ATTR_TYPE;
}
else
throw new ArgumentException(dnString);
}
else
{
tokenBuf[tokenIndex++] = currChar;
state = ALPHA_ATTR_TYPE;
}
}
else if (isDigit(currChar))
{
--currIndex;
state = OID_ATTR_TYPE;
}
else if (System.Globalization.CharUnicodeInfo.GetUnicodeCategory(currChar) != System.Globalization.UnicodeCategory.SpaceSeparator)
throw new ArgumentException(dnString);
break;
case ALPHA_ATTR_TYPE:
if (isAlpha(currChar) || isDigit(currChar) || (currChar == '-'))
tokenBuf[tokenIndex++] = currChar;
else
{
//skip any spaces
while ((currChar == ' ') && (currIndex < lastIndex))
currChar = dnString[++currIndex];
if (currChar == '=')
{
attrType = new string(tokenBuf, 0, tokenIndex);
tokenIndex = 0;
state = LOOK_FOR_RDN_VALUE;
}
else
throw new ArgumentException(dnString);
}
break;
case OID_ATTR_TYPE:
if (!isDigit(currChar))
throw new ArgumentException(dnString);
firstDigitZero = (currChar == '0');
tokenBuf[tokenIndex++] = currChar;
currChar = dnString[++currIndex];
if ((isDigit(currChar) && firstDigitZero) || (currChar == '.' && firstDigitZero))
{
throw new ArgumentException(dnString);
}
//consume all numbers.
while (isDigit(currChar) && (currIndex < lastIndex))
{
tokenBuf[tokenIndex++] = currChar;
currChar = dnString[++currIndex];
}
if (currChar == '.')
{
tokenBuf[tokenIndex++] = currChar;
//The state remains at OID_ATTR_TYPE
}
else
{
//skip any spaces
while (currChar == ' ' && (currIndex < lastIndex))
currChar = dnString[++currIndex];
if (currChar == '=')
{
attrType = new string(tokenBuf, 0, tokenIndex);
tokenIndex = 0;
state = LOOK_FOR_RDN_VALUE;
}
else
throw new ArgumentException(dnString);
}
break;
case LOOK_FOR_RDN_VALUE:
while (currChar == ' ')
{
if (currIndex < lastIndex)
currChar = dnString[++currIndex];
else
throw new ArgumentException(dnString);
}
if (currChar == '"')
{
state = QUOTED_RDN_VALUE;
valueStart = currIndex;
}
else if (currChar == '#')
{
hexDigitCount = 0;
tokenBuf[tokenIndex++] = currChar;
valueStart = currIndex;
state = HEX_RDN_VALUE;
}
else
{
valueStart = currIndex;
//check this character again in the UNQUOTED_RDN_VALUE state
currIndex--;
state = UNQUOTED_RDN_VALUE;
}
break;
case UNQUOTED_RDN_VALUE:
if (currChar == '\\')
{
if (!(currIndex < lastIndex))
throw new ArgumentException(dnString);
currChar = dnString[++currIndex];
if (isHexDigit(currChar))
{
if (!(currIndex < lastIndex))
throw new ArgumentException(dnString);
nextChar = dnString[++currIndex];
if (isHexDigit(nextChar))
{
tokenBuf[tokenIndex++] = hexToChar(currChar, nextChar);
trailingSpaceCount = 0;
}
else
throw new ArgumentException(dnString);
}
else if (needsEscape(currChar) || currChar == '#' || currChar == '=' || currChar == ' ')
{
tokenBuf[tokenIndex++] = currChar;
trailingSpaceCount = 0;
}
else
throw new ArgumentException(dnString);
}
else if (currChar == ' ')
{
trailingSpaceCount++;
tokenBuf[tokenIndex++] = currChar;
}
else if ((currChar == ',') || (currChar == ';') || (currChar == '+'))
{
attrValue = new string(tokenBuf, 0, tokenIndex - trailingSpaceCount);
rawValue = dnString.Substring(valueStart, (currIndex - trailingSpaceCount) - (valueStart));
currRDN.add(attrType, attrValue, rawValue);
if (currChar != '+')
{
rdnList.Add(currRDN);
currRDN = new RDN();
}
trailingSpaceCount = 0;
tokenIndex = 0;
state = LOOK_FOR_RDN_ATTR_TYPE;
}
else if (needsEscape(currChar))
{
throw new ArgumentException(dnString);
}
else
{
trailingSpaceCount = 0;
tokenBuf[tokenIndex++] = currChar;
}
break; //end UNQUOTED RDN VALUE
case QUOTED_RDN_VALUE:
if (currChar == '"')
{
rawValue = dnString.Substring(valueStart, (currIndex + 1) - (valueStart));
if (currIndex < lastIndex)
currChar = dnString[++currIndex];
//skip any spaces
while ((currChar == ' ') && (currIndex < lastIndex))
currChar = dnString[++currIndex];
if ((currChar == ',') || (currChar == ';') || (currChar == '+') || (currIndex == lastIndex))
{
attrValue = new string(tokenBuf, 0, tokenIndex);
currRDN.add(attrType, attrValue, rawValue);
if (currChar != '+')
{
rdnList.Add(currRDN);
currRDN = new RDN();
}
trailingSpaceCount = 0;
tokenIndex = 0;
state = LOOK_FOR_RDN_ATTR_TYPE;
}
else
throw new ArgumentException(dnString);
}
else if (currChar == '\\')
{
currChar = dnString[++currIndex];
if (isHexDigit(currChar))
{
nextChar = dnString[++currIndex];
if (isHexDigit(nextChar))
{
tokenBuf[tokenIndex++] = hexToChar(currChar, nextChar);
trailingSpaceCount = 0;
}
else
throw new ArgumentException(dnString);
}
else if (needsEscape(currChar) || currChar == '#' || currChar == '=' || currChar == ' ')
{
tokenBuf[tokenIndex++] = currChar;
trailingSpaceCount = 0;
}
else
throw new ArgumentException(dnString);
}
else
tokenBuf[tokenIndex++] = currChar;
break; //end QUOTED RDN VALUE
case HEX_RDN_VALUE:
if ((!isHexDigit(currChar)) || (currIndex > lastIndex))
{
//check for odd number of hex digits
if ((hexDigitCount % 2) != 0 || hexDigitCount == 0)
throw new ArgumentException(dnString);
else
{
rawValue = dnString.Substring(valueStart, (currIndex) - (valueStart));
//skip any spaces
while ((currChar == ' ') && (currIndex < lastIndex))
currChar = dnString[++currIndex];
if ((currChar == ',') || (currChar == ';') || (currChar == '+') || (currIndex == lastIndex))
{
attrValue = new string(tokenBuf, 0, tokenIndex);
//added by cameron
currRDN.add(attrType, attrValue, rawValue);
if (currChar != '+')
{
rdnList.Add(currRDN);
currRDN = new RDN();
}
tokenIndex = 0;
state = LOOK_FOR_RDN_ATTR_TYPE;
}
else
{
throw new ArgumentException(dnString);
}
}
}
else
{
tokenBuf[tokenIndex++] = currChar;
hexDigitCount++;
}
break; //end HEX RDN VALUE
} //end switch
currIndex++;
} //end while
//check ending state
if (state == UNQUOTED_RDN_VALUE || (state == HEX_RDN_VALUE && (hexDigitCount % 2) == 0) && hexDigitCount != 0)
{
attrValue = new string(tokenBuf, 0, tokenIndex - trailingSpaceCount);
rawValue = dnString.Substring(valueStart, (currIndex - trailingSpaceCount) - (valueStart));
currRDN.add(attrType, attrValue, rawValue);
rdnList.Add(currRDN);
}
else if (state == LOOK_FOR_RDN_VALUE)
{
//empty value is valid
attrValue = "";
rawValue = dnString.Substring(valueStart);
currRDN.add(attrType, attrValue, rawValue);
rdnList.Add(currRDN);
}
else
{
throw new ArgumentException(dnString);
}
} //end DN constructor (string dn)
/// <summary> Checks a character to see if it is an ascii alphabetic character in
/// ranges 65-90 or 97-122.
///
/// </summary>
/// <param name="ch">the character to be tested.
/// </param>
/// <returns> <code>true</code> if the character is an ascii alphabetic
/// character
/// </returns>
private bool isAlpha(char ch)
{
if (((ch < 91) && (ch > 64)) || ((ch < 123) && (ch > 96)))
//ASCII A-Z
return true;
return false;
}
/// <summary> Checks a character to see if it is an ascii digit (0-9) character in
/// the ascii value range 48-57.
///
/// </summary>
/// <param name="ch">the character to be tested.
/// </param>
/// <returns> <code>true</code> if the character is an ascii alphabetic
/// character
/// </returns>
private bool isDigit(char ch)
{
if ((ch < 58) && (ch > 47))
//ASCII 0-9
return true;
return false;
}
/// <summary> Checks a character to see if it is valid hex digit 0-9, a-f, or
/// A-F (ASCII value ranges 48-47, 65-70, 97-102).
///
/// </summary>
/// <param name="ch">the character to be tested.
/// </param>
/// <returns> <code>true</code> if the character is a valid hex digit
/// </returns>
private static bool isHexDigit(char ch)
{
if (((ch < 58) && (ch > 47)) || ((ch < 71) && (ch > 64)) || ((ch < 103) && (ch > 96)))
//ASCII A-F
return true;
return false;
}
/// <summary> Checks a character to see if it must always be escaped in the
/// string representation of a DN. We must tests for space, sharp, and
/// equals individually.
///
/// </summary>
/// <param name="ch">the character to be tested.
/// </param>
/// <returns> <code>true</code> if the character needs to be escaped in at
/// least some instances.
/// </returns>
private bool needsEscape(char ch)
{
if ((ch == ',') || (ch == '+') || (ch == '\"') || (ch == ';') || (ch == '<') || (ch == '>') || (ch == '\\'))
return true;
return false;
}
/// <summary> Converts two valid hex digit characters that form the string
/// representation of an ascii character value to the actual ascii
/// character.
///
/// </summary>
/// <param name="hex1">the hex digit for the high order byte.
/// </param>
/// <param name="hex0">the hex digit for the low order byte.
/// </param>
/// <returns> the character whose value is represented by the parameters.
/// </returns>
private static char hexToChar(char hex1, char hex0)
{
int result;
if ((hex1 < 58) && (hex1 > 47))
//ASCII 0-9
result = (hex1 - 48) * 16;
else if ((hex1 < 71) && (hex1 > 64))
//ASCII a-f
result = (hex1 - 55) * 16;
else if ((hex1 < 103) && (hex1 > 96))
//ASCII A-F
result = (hex1 - 87) * 16;
else
throw new ArgumentException("Not hex digit");
if ((hex0 < 58) && (hex0 > 47))
//ASCII 0-9
result += (hex0 - 48);
else if ((hex0 < 71) && (hex0 > 64))
//ASCII a-f
result += (hex0 - 55);
else if ((hex0 < 103) && (hex0 > 96))
//ASCII A-F
result += (hex0 - 87);
else
throw new ArgumentException("Not hex digit");
return (char)result;
}
/// <summary> Creates and returns a string that represents this DN. The string
/// follows RFC 2253, which describes String representation of DN's and
/// RDN's
///
/// </summary>
/// <returns> A DN string.
/// </returns>
public override string ToString()
{
int length = rdnList.Count;
string dn = "";
if (length < 1)
return null;
dn = rdnList[0].ToString();
for (int i = 1; i < length; i++)
{
dn += ("," + rdnList[i].ToString());
}
return dn;
}
/// <summary> Compares this DN to the specified DN to determine if they are equal.
///
/// </summary>
/// <param name="toDN">the DN to compare to
/// </param>
/// <returns> <code>true</code> if the DNs are equal; otherwise
/// <code>false</code>
/// </returns>
public ArrayList getrdnList()
{
return rdnList;
}
public override bool Equals(object toDN)
{
return Equals((DN)toDN);
}
public bool Equals(DN toDN)
{
ArrayList aList = toDN.getrdnList();
int length = aList.Count;
if (rdnList.Count != length)
return false;
for (int i = 0; i < length; i++)
{
if (!((RDN)rdnList[i]).equals((RDN)toDN.getrdnList()[i]))
return false;
}
return true;
}
/// <summary> return a string array of the individual RDNs contained in the DN
///
/// </summary>
/// <param name="noTypes"> If true, returns only the values of the
/// components, and not the names, e.g. "Babs
/// Jensen", "Accounting", "Acme", "us" - instead of
/// "cn=Babs Jensen", "ou=Accounting", "o=Acme", and
/// "c=us".
/// </param>
/// <returns> <code>String[]</code> containing the rdns in the DN with
/// the leftmost rdn in the first element of the array
///
/// </returns>
public virtual string[] explodeDN(bool noTypes)
{
int length = rdnList.Count;
string[] rdns = new string[length];
for (int i = 0; i < length; i++)
rdns[i] = ((RDN)rdnList[i]).ToString(noTypes);
return rdns;
}
/// <summary> Retrieves the count of RDNs, or individule names, in the Distinguished name</summary>
/// <returns> the count of RDN
/// </returns>
public virtual int countRDNs()
{
return rdnList.Count;
}
/// <summary>Determines if this DN is <I>contained</I> by the DN passed in. For
/// example: "cn=admin, ou=marketing, o=corporation" is contained by
/// "o=corporation", "ou=marketing, o=corporation", and "ou=marketing"
/// but <B>not</B> by "cn=admin" or "cn=admin,ou=marketing,o=corporation"
/// Note: For users of Netscape's SDK this method is comparable to contains
///
/// </summary>
/// <param name="containerDN">of a container
/// </param>
/// <returns> true if containerDN contains this DN
/// </returns>
public virtual bool isDescendantOf(DN containerDN)
{
int i = containerDN.rdnList.Count - 1; //index to an RDN of the ContainerDN
int j = rdnList.Count - 1; //index to an RDN of the ContainedDN
//Search from the end of the DN for an RDN that matches the end RDN of
//containerDN.
while (!((RDN)rdnList[j]).equals((RDN)containerDN.rdnList[i]))
{
j--;
if (j <= 0)
return false;
//if the end RDN of containerDN does not have any equal
//RDN in rdnList, then containerDN does not contain this DN
}
i--; //avoid a redundant compare
j--;
//step backwards to verify that all RDNs in containerDN exist in this DN
for (; i >= 0 && j >= 0; i--, j--)
{
if (!((RDN)rdnList[j]).equals((RDN)containerDN.rdnList[i]))
return false;
}
if (j == 0 && i == 0)
//the DNs are identical and thus not contained
return false;
return true;
}
/// <summary> Adds the RDN to the beginning of the current DN.</summary>
/// <param name="rdn">an RDN to be added
/// </param>
public virtual void addRDN(RDN rdn)
{
rdnList.Insert(0, rdn);
}
/// <summary> Adds the RDN to the beginning of the current DN.</summary>
/// <param name="rdn">an RDN to be added
/// </param>
public virtual void addRDNToFront(RDN rdn)
{
rdnList.Insert(0, rdn);
}
/// <summary> Adds the RDN to the end of the current DN</summary>
/// <param name="rdn">an RDN to be added
/// </param>
public virtual void addRDNToBack(RDN rdn)
{
rdnList.Add(rdn);
}
} //end class DN
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.ApplicationFramework.ApplicationStyles;
using OpenLiveWriter.Controls;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Layout;
using OpenLiveWriter.Localization;
namespace OpenLiveWriter.PostEditor.PostHtmlEditing
{
/// <summary>
/// Summary description for EditImageSizesDialog.
/// </summary>
public class EditImageSizesDialog : BaseForm
{
private NumericUpDown numericSmallWidth;
private Label label1;
private Label label2;
private NumericUpDown numericSmallHeight;
private Label label3;
private Label label4;
private Label label5;
private Label label6;
private Label label7;
private Label label8;
private Label label9;
private Label label10;
private Label label11;
private Label label12;
private NumericUpDown numericMediumHeight;
private NumericUpDown numericMediumWidth;
private NumericUpDown numericLargeHeight;
private NumericUpDown numericLargeWidth;
private Button buttonCancel;
private Button buttonOK;
private GroupLabelControl labelImageLarge;
private GroupLabelControl labelImageMedium;
private GroupLabelControl labelImageSmall;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
public EditImageSizesDialog()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
numericSmallHeight.Maximum = ImageSizeHelper.MAX_HEIGHT;
numericSmallWidth.Maximum = ImageSizeHelper.MAX_WIDTH;
numericMediumHeight.Maximum = ImageSizeHelper.MAX_HEIGHT;
numericMediumWidth.Maximum = ImageSizeHelper.MAX_WIDTH;
numericLargeHeight.Maximum = ImageSizeHelper.MAX_HEIGHT;
numericLargeWidth.Maximum = ImageSizeHelper.MAX_WIDTH;
numericSmallHeight.Minimum = 1;
numericSmallWidth.Minimum = 1;
numericMediumHeight.Minimum = 1;
numericMediumWidth.Minimum = 1;
numericLargeHeight.Minimum = 1;
numericLargeWidth.Minimum = 1;
numericSmallHeight.Leave += new EventHandler(numeric_Leave);
numericSmallWidth.Leave += new EventHandler(numeric_Leave);
numericMediumHeight.Leave += new EventHandler(numeric_Leave);
numericMediumWidth.Leave += new EventHandler(numeric_Leave);
numericLargeHeight.Leave += new EventHandler(numeric_Leave);
numericLargeWidth.Leave += new EventHandler(numeric_Leave);
numericSmallHeight.Enter += new EventHandler(numeric_Enter);
numericSmallWidth.Enter += new EventHandler(numeric_Enter);
numericMediumHeight.Enter += new EventHandler(numeric_Enter);
numericMediumWidth.Enter += new EventHandler(numeric_Enter);
numericLargeHeight.Enter += new EventHandler(numeric_Enter);
numericLargeWidth.Enter += new EventHandler(numeric_Enter);
this.label4.Text = Res.Get(StringId.pixels);
this.label3.Text = Res.Get(StringId.pixels);
this.label2.Text = Res.Get(StringId.ImgSBMaximumHeightLabel1);
this.label1.Text = Res.Get(StringId.ImgSBMaximumWidthLabel1);
this.label5.Text = Res.Get(StringId.pixels);
this.label6.Text = Res.Get(StringId.pixels);
this.label7.Text = Res.Get(StringId.ImgSBMaximumHeightLabel2);
this.label8.Text = Res.Get(StringId.ImgSBMaximumWidthLabel2);
this.label9.Text = Res.Get(StringId.pixels);
this.label10.Text = Res.Get(StringId.pixels);
this.label11.Text = Res.Get(StringId.ImgSBMaximumHeightLabel3);
this.label12.Text = Res.Get(StringId.ImgSBMaximumWidthLabel3);
this.buttonCancel.Text = Res.Get(StringId.CancelButton);
this.buttonOK.Text = Res.Get(StringId.OKButtonText);
this.labelImageLarge.Text = Res.Get(StringId.ImgSBLargeImage);
this.labelImageMedium.Text = Res.Get(StringId.ImgSBMediumImage);
this.labelImageSmall.Text = Res.Get(StringId.ImgSBSmallImage);
this.Text = Res.Get(StringId.ImgSBDefaultImageSizes);
numericSmallWidth.Value = ImageEditingSettings.DefaultImageSizeSmall.Width;
numericSmallHeight.Value = ImageEditingSettings.DefaultImageSizeSmall.Height;
numericMediumWidth.Value = ImageEditingSettings.DefaultImageSizeMedium.Width;
numericMediumHeight.Value = ImageEditingSettings.DefaultImageSizeMedium.Height;
numericLargeWidth.Value = ImageEditingSettings.DefaultImageSizeLarge.Width;
numericLargeHeight.Value = ImageEditingSettings.DefaultImageSizeLarge.Height;
numericSmallWidth.AccessibleName = Res.Get(StringId.MaxSmWidth);
numericSmallHeight.AccessibleName = Res.Get(StringId.MaxSmHeight);
numericMediumWidth.AccessibleName = Res.Get(StringId.MaxMdWidth);
numericMediumHeight.AccessibleName = Res.Get(StringId.MaxMdHeight);
numericLargeWidth.AccessibleName = Res.Get(StringId.MaxLgWidth);
numericLargeHeight.AccessibleName = Res.Get(StringId.MaxLgHeight);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Label[] leftLabels = { label1, label2, label8, label7, label12, label11 };
NumericUpDown[] values = { numericSmallWidth, numericSmallHeight, numericMediumWidth, numericMediumHeight, numericLargeWidth, numericLargeHeight };
Label[] rightLabels = { label3, label4, label6, label5, label10, label9 };
using (AutoGrow autoGrow = new AutoGrow(this, AnchorStyles.Right, false))
{
autoGrow.AllowAnchoring = true;
int deltaX = LayoutHelper.AutoFitLabels(leftLabels);
new ControlGroup(values).Left += deltaX;
new ControlGroup(rightLabels).Left += deltaX;
LayoutHelper.AutoFitLabels(rightLabels);
LayoutHelper.FixupOKCancel(buttonOK, buttonCancel);
}
}
/// <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()
{
this.numericSmallWidth = new System.Windows.Forms.NumericUpDown();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.numericSmallHeight = new System.Windows.Forms.NumericUpDown();
this.label1 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.numericMediumHeight = new System.Windows.Forms.NumericUpDown();
this.label8 = new System.Windows.Forms.Label();
this.numericMediumWidth = new System.Windows.Forms.NumericUpDown();
this.label9 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.label11 = new System.Windows.Forms.Label();
this.numericLargeHeight = new System.Windows.Forms.NumericUpDown();
this.label12 = new System.Windows.Forms.Label();
this.numericLargeWidth = new System.Windows.Forms.NumericUpDown();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonOK = new System.Windows.Forms.Button();
this.labelImageLarge = new OpenLiveWriter.Controls.GroupLabelControl();
this.labelImageMedium = new OpenLiveWriter.Controls.GroupLabelControl();
this.labelImageSmall = new OpenLiveWriter.Controls.GroupLabelControl();
((System.ComponentModel.ISupportInitialize)(this.numericSmallWidth)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericSmallHeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericMediumHeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericMediumWidth)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericLargeHeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericLargeWidth)).BeginInit();
this.SuspendLayout();
//
// numericSmallWidth
//
this.numericSmallWidth.Location = new System.Drawing.Point(115, 28);
this.numericSmallWidth.Maximum = new System.Decimal(new int[] {
4096,
0,
0,
0});
this.numericSmallWidth.Minimum = new System.Decimal(new int[] {
16,
0,
0,
0});
this.numericSmallWidth.Name = "numericSmallWidth";
this.numericSmallWidth.Size = new System.Drawing.Size(56, 21);
this.numericSmallWidth.TabIndex = 2;
this.numericSmallWidth.Value = new System.Decimal(new int[] {
16,
0,
0,
0});
//
// label4
//
this.label4.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label4.Location = new System.Drawing.Point(180, 56);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(48, 16);
this.label4.TabIndex = 20;
this.label4.Text = "pixels";
//
// label3
//
this.label3.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label3.Location = new System.Drawing.Point(180, 32);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(48, 16);
this.label3.TabIndex = 19;
this.label3.Text = "pixels";
//
// label2
//
this.label2.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label2.Location = new System.Drawing.Point(20, 56);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(85, 16);
this.label2.TabIndex = 3;
this.label2.Text = "Maximum &Height:";
//
// numericSmallHeight
//
this.numericSmallHeight.Location = new System.Drawing.Point(115, 52);
this.numericSmallHeight.Maximum = new System.Decimal(new int[] {
3072,
0,
0,
0});
this.numericSmallHeight.Minimum = new System.Decimal(new int[] {
16,
0,
0,
0});
this.numericSmallHeight.Name = "numericSmallHeight";
this.numericSmallHeight.Size = new System.Drawing.Size(56, 21);
this.numericSmallHeight.TabIndex = 4;
this.numericSmallHeight.Value = new System.Decimal(new int[] {
16,
0,
0,
0});
//
// label1
//
this.label1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label1.Location = new System.Drawing.Point(20, 32);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(85, 16);
this.label1.TabIndex = 1;
this.label1.Text = "Maximum &Width:";
//
// label5
//
this.label5.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label5.Location = new System.Drawing.Point(180, 128);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(48, 16);
this.label5.TabIndex = 18;
this.label5.Text = "pixels";
//
// label6
//
this.label6.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label6.Location = new System.Drawing.Point(180, 104);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(48, 16);
this.label6.TabIndex = 17;
this.label6.Text = "pixels";
//
// label7
//
this.label7.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label7.Location = new System.Drawing.Point(20, 128);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(85, 16);
this.label7.TabIndex = 7;
this.label7.Text = "Maximum H&eight:";
//
// numericMediumHeight
//
this.numericMediumHeight.Location = new System.Drawing.Point(115, 128);
this.numericMediumHeight.Maximum = new System.Decimal(new int[] {
3072,
0,
0,
0});
this.numericMediumHeight.Minimum = new System.Decimal(new int[] {
16,
0,
0,
0});
this.numericMediumHeight.Name = "numericMediumHeight";
this.numericMediumHeight.Size = new System.Drawing.Size(56, 21);
this.numericMediumHeight.TabIndex = 8;
this.numericMediumHeight.Value = new System.Decimal(new int[] {
16,
0,
0,
0});
//
// label8
//
this.label8.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label8.Location = new System.Drawing.Point(20, 104);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(85, 16);
this.label8.TabIndex = 5;
this.label8.Text = "Maximum W&idth:";
//
// numericMediumWidth
//
this.numericMediumWidth.Location = new System.Drawing.Point(115, 104);
this.numericMediumWidth.Maximum = new System.Decimal(new int[] {
4096,
0,
0,
0});
this.numericMediumWidth.Minimum = new System.Decimal(new int[] {
16,
0,
0,
0});
this.numericMediumWidth.Name = "numericMediumWidth";
this.numericMediumWidth.Size = new System.Drawing.Size(56, 21);
this.numericMediumWidth.TabIndex = 6;
this.numericMediumWidth.Value = new System.Decimal(new int[] {
16,
0,
0,
0});
//
// label9
//
this.label9.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label9.Location = new System.Drawing.Point(180, 204);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(48, 16);
this.label9.TabIndex = 16;
this.label9.Text = "pixels";
//
// label10
//
this.label10.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label10.Location = new System.Drawing.Point(180, 180);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(48, 16);
this.label10.TabIndex = 15;
this.label10.Text = "pixels";
//
// label11
//
this.label11.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label11.Location = new System.Drawing.Point(20, 204);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(85, 16);
this.label11.TabIndex = 11;
this.label11.Text = "Maximum Hei&ght:";
//
// numericLargeHeight
//
this.numericLargeHeight.Location = new System.Drawing.Point(115, 200);
this.numericLargeHeight.Maximum = new System.Decimal(new int[] {
3072,
0,
0,
0});
this.numericLargeHeight.Minimum = new System.Decimal(new int[] {
16,
0,
0,
0});
this.numericLargeHeight.Name = "numericLargeHeight";
this.numericLargeHeight.Size = new System.Drawing.Size(56, 21);
this.numericLargeHeight.TabIndex = 12;
this.numericLargeHeight.Value = new System.Decimal(new int[] {
16,
0,
0,
0});
//
// label12
//
this.label12.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label12.Location = new System.Drawing.Point(20, 180);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(85, 16);
this.label12.TabIndex = 9;
this.label12.Text = "Maximum Wi&dth:";
//
// numericLargeWidth
//
this.numericLargeWidth.Location = new System.Drawing.Point(115, 176);
this.numericLargeWidth.Maximum = new System.Decimal(new int[] {
4096,
0,
0,
0});
this.numericLargeWidth.Minimum = new System.Decimal(new int[] {
16,
0,
0,
0});
this.numericLargeWidth.Name = "numericLargeWidth";
this.numericLargeWidth.Size = new System.Drawing.Size(56, 21);
this.numericLargeWidth.TabIndex = 10;
this.numericLargeWidth.Value = new System.Decimal(new int[] {
16,
0,
0,
0});
//
// buttonCancel
//
this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonCancel.Location = new System.Drawing.Point(172, 236);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.TabIndex = 14;
this.buttonCancel.Text = "Cancel";
//
// buttonOK
//
this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.buttonOK.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonOK.Location = new System.Drawing.Point(92, 236);
this.buttonOK.Name = "buttonOK";
this.buttonOK.TabIndex = 13;
this.buttonOK.Text = "OK";
this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click);
//
// labelImageLarge
//
this.labelImageLarge.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.labelImageLarge.Location = new System.Drawing.Point(10, 160);
this.labelImageLarge.MultiLine = false;
this.labelImageLarge.Name = "labelImageLarge";
//this.labelImageLarge.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.labelImageLarge.Size = new System.Drawing.Size(236, 16);
this.labelImageLarge.TabIndex = 2;
this.labelImageLarge.Text = "Large image:";
//
// labelImageMedium
//
this.labelImageMedium.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.labelImageMedium.Location = new System.Drawing.Point(10, 84);
this.labelImageMedium.MultiLine = false;
this.labelImageMedium.Name = "labelImageMedium";
//this.labelImageMedium.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.labelImageMedium.Size = new System.Drawing.Size(236, 16);
this.labelImageMedium.TabIndex = 1;
this.labelImageMedium.Text = "Medium image:";
//
// labelImageSmall
//
this.labelImageSmall.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.labelImageSmall.Location = new System.Drawing.Point(10, 12);
this.labelImageSmall.MultiLine = false;
this.labelImageSmall.Name = "labelImageSmall";
//this.labelImageSmall.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.labelImageSmall.Size = new System.Drawing.Size(236, 16);
this.labelImageSmall.TabIndex = 0;
this.labelImageSmall.Text = "Small image:";
//
// EditImageSizesDialog
//
this.AcceptButton = this.buttonOK;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.CancelButton = this.buttonCancel;
this.ClientSize = new System.Drawing.Size(256, 268);
this.Controls.Add(this.labelImageSmall);
this.Controls.Add(this.labelImageMedium);
this.Controls.Add(this.labelImageLarge);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOK);
this.Controls.Add(this.label10);
this.Controls.Add(this.numericLargeWidth);
this.Controls.Add(this.label12);
this.Controls.Add(this.numericLargeHeight);
this.Controls.Add(this.label11);
this.Controls.Add(this.label9);
this.Controls.Add(this.label8);
this.Controls.Add(this.label7);
this.Controls.Add(this.label6);
this.Controls.Add(this.label5);
this.Controls.Add(this.numericMediumHeight);
this.Controls.Add(this.numericMediumWidth);
this.Controls.Add(this.numericSmallWidth);
this.Controls.Add(this.label2);
this.Controls.Add(this.numericSmallHeight);
this.Controls.Add(this.label1);
this.Controls.Add(this.label3);
this.Controls.Add(this.label4);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "EditImageSizesDialog";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Default Image Sizes";
((System.ComponentModel.ISupportInitialize)(this.numericSmallWidth)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericSmallHeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericMediumHeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericMediumWidth)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericLargeHeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericLargeWidth)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void buttonOK_Click(object sender, EventArgs e)
{
ImageEditingSettings.DefaultImageSizeSmall = new Size((int)numericSmallWidth.Value, (int)numericSmallHeight.Value);
ImageEditingSettings.DefaultImageSizeMedium = new Size((int)numericMediumWidth.Value, (int)numericMediumHeight.Value);
ImageEditingSettings.DefaultImageSizeLarge = new Size((int)numericLargeWidth.Value, (int)numericLargeHeight.Value);
}
private void numeric_Leave(object sender, EventArgs e)
{
NumericUpDown upDownPicker = (NumericUpDown)sender;
if (upDownPicker.Value > upDownPicker.Maximum)
upDownPicker.Value = upDownPicker.Maximum;
}
private void numeric_Enter(object sender, EventArgs e)
{
NumericUpDown upDownPicker = (NumericUpDown)sender;
upDownPicker.Select(0, upDownPicker.Text.Length);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
////////////////////////////////////////////////////////////////////////////
//
// Notes about PersianCalendar
//
////////////////////////////////////////////////////////////////////////////
// Modern Persian calendar is a solar observation based calendar. Each new year begins on the day when the vernal equinox occurs before noon.
// The epoch is the date of the vernal equinox prior to the epoch of the Islamic calendar (March 19, 622 Julian or March 22, 622 Gregorian)
// There is no Persian year 0. Ordinary years have 365 days. Leap years have 366 days with the last month (Esfand) gaining the extra day.
/*
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 0622/03/22 9999/12/31
** Persian 0001/01/01 9378/10/13
*/
[Serializable]
public class PersianCalendar : Calendar
{
public static readonly int PersianEra = 1;
internal static long PersianEpoch = new DateTime(622, 3, 22).Ticks / GregorianCalendar.TicksPerDay;
const int ApproximateHalfYear = 180;
internal const int DatePartYear = 0;
internal const int DatePartDayOfYear = 1;
internal const int DatePartMonth = 2;
internal const int DatePartDay = 3;
internal const int MonthsPerYear = 12;
internal static int[] DaysToMonth = { 0, 31, 62, 93, 124, 155, 186, 216, 246, 276, 306, 336, 366 };
internal const int MaxCalendarYear = 9378;
internal const int MaxCalendarMonth = 10;
internal const int MaxCalendarDay = 13;
// Persian calendar (year: 1, month: 1, day:1 ) = Gregorian (year: 622, month: 3, day: 22)
// This is the minimal Gregorian date that we support in the PersianCalendar.
internal static DateTime minDate = new DateTime(622, 3, 22);
internal static DateTime maxDate = DateTime.MaxValue;
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of PersianCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
/*
internal static Calendar GetDefaultInstance() {
if (m_defaultInstance == null) {
m_defaultInstance = new PersianCalendar();
}
return (m_defaultInstance);
}
*/
public override DateTime MinSupportedDateTime
{
get
{
return (minDate);
}
}
public override DateTime MaxSupportedDateTime
{
get
{
return (maxDate);
}
}
// Return the type of the Persian calendar.
//
//public override CalendarAlgorithmType AlgorithmType {
// get {
// return CalendarAlgorithmType.SolarCalendar;
// }
//}
// Construct an instance of Persian calendar.
public PersianCalendar()
{
}
internal override CalendarId BaseCalendarID
{
get
{
return CalendarId.GREGORIAN;
}
}
internal override CalendarId ID
{
get
{
return CalendarId.PERSIAN;
}
}
/*=================================GetAbsoluteDatePersian==========================
**Action: Gets the Absolute date for the given Persian date. The absolute date means
** the number of days from January 1st, 1 A.D.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
long GetAbsoluteDatePersian(int year, int month, int day)
{
if (year >= 1 && year <= MaxCalendarYear && month >= 1 && month <= 12)
{
int ordinalDay = DaysInPreviousMonths(month) + day - 1; // day is one based, make 0 based since this will be the number of days we add to beginning of year below
int approximateDaysFromEpochForYearStart = (int)(CalendricalCalculationsHelper.MeanTropicalYearInDays * (year - 1));
long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(PersianEpoch + approximateDaysFromEpochForYearStart + ApproximateHalfYear);
yearStart += ordinalDay;
return yearStart;
}
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
static internal void CheckTicksRange(long ticks) {
if (ticks < minDate.Ticks || ticks > maxDate.Ticks) {
throw new ArgumentOutOfRangeException(
"time",
String.Format(
CultureInfo.InvariantCulture,
SR.ArgumentOutOfRange_CalendarRange,
minDate,
maxDate));
}
}
static internal void CheckEraRange(int era)
{
if (era != CurrentEra && era != PersianEra)
{
throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue);
}
}
static internal void CheckYearRange(int year, int era)
{
CheckEraRange(era);
if (year < 1 || year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarYear));
}
}
static internal void CheckYearMonthRange(int year, int month, int era)
{
CheckYearRange(year, era);
if (year == MaxCalendarYear)
{
if (month > MaxCalendarMonth)
{
throw new ArgumentOutOfRangeException(
"month",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarMonth));
}
}
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException("month", SR.ArgumentOutOfRange_Month);
}
}
static int MonthFromOrdinalDay(int ordinalDay)
{
Contract.Assert(ordinalDay <= 366);
int index = 0;
while (ordinalDay > DaysToMonth[index])
index++;
return index;
}
static int DaysInPreviousMonths(int month)
{
Contract.Assert(1 <= month && month <= 12);
--month; // months are one based but for calculations use 0 based
return DaysToMonth[month];
}
/*=================================GetDatePart==========================
**Action: Returns a given date part of this <i>DateTime</i>. This method is used
** to compute the year, day-of-year, month, or day part.
**Returns:
**Arguments:
**Exceptions: ArgumentException if part is incorrect.
============================================================================*/
internal int GetDatePart(long ticks, int part)
{
long NumDays; // The calculation buffer in number of days.
CheckTicksRange(ticks);
//
// Get the absolute date. The absolute date is the number of days from January 1st, 1 A.D.
// 1/1/0001 is absolute date 1.
//
NumDays = ticks / GregorianCalendar.TicksPerDay + 1;
//
// Calculate the appromixate Persian Year.
//
long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(NumDays);
int y = (int)(Math.Floor(((yearStart - PersianEpoch) / CalendricalCalculationsHelper.MeanTropicalYearInDays) + 0.5)) + 1;
Contract.Assert(y >= 1);
if (part == DatePartYear)
{
return y;
}
//
// Calculate the Persian Month.
//
int ordinalDay = (int)(NumDays - CalendricalCalculationsHelper.GetNumberOfDays(this.ToDateTime(y, 1, 1, 0, 0, 0, 0, 1)));
if (part == DatePartDayOfYear)
{
return ordinalDay;
}
int m = MonthFromOrdinalDay(ordinalDay);
Contract.Assert(ordinalDay >= 1);
Contract.Assert(m >= 1 && m <= 12);
if (part == DatePartMonth)
{
return m;
}
int d = ordinalDay - DaysInPreviousMonths(m);
Contract.Assert(1 <= d);
Contract.Assert(d <= 31);
//
// Calculate the Persian Day.
//
if (part == DatePartDay)
{
return (d);
}
// Incorrect part value.
throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing);
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
"months",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
-120000,
120000));
}
Contract.EndContractBlock();
// Get the date in Persian calendar.
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int days = GetDaysInMonth(y, m);
if (d > days)
{
d = days;
}
long ticks = GetAbsoluteDatePersian(y, m, d) * TicksPerDay + time.Ticks % TicksPerDay;
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public override DateTime AddYears(DateTime time, int years)
{
return (AddMonths(time, years * 12));
}
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public override int GetDayOfMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDay));
}
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public override int GetDayOfYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
// Returns the number of days in the month given by the year and
// month arguments.
//
public override int GetDaysInMonth(int year, int month, int era)
{
CheckYearMonthRange(year, month, era);
if ((month == MaxCalendarMonth) && (year == MaxCalendarYear))
{
return MaxCalendarDay;
}
int daysInMonth = DaysToMonth[month] - DaysToMonth[month - 1];
if ((month == MonthsPerYear) && !IsLeapYear(year))
{
Contract.Assert(daysInMonth == 30);
--daysInMonth;
}
return daysInMonth;
}
// Returns the number of days in the year given by the year argument for the current era.
//
public override int GetDaysInYear(int year, int era)
{
CheckYearRange(year, era);
if (year == MaxCalendarYear)
{
return DaysToMonth[MaxCalendarMonth - 1] + MaxCalendarDay;
}
// Common years have 365 days. Leap years have 366 days.
return (IsLeapYear(year, CurrentEra) ? 366 : 365);
}
// Returns the era for the specified DateTime value.
public override int GetEra(DateTime time)
{
CheckTicksRange(time.Ticks);
return (PersianEra);
}
public override int[] Eras
{
get
{
return (new int[] { PersianEra });
}
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public override int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
// Returns the number of months in the specified year and era.
public override int GetMonthsInYear(int year, int era)
{
CheckYearRange(year, era);
if (year == MaxCalendarYear)
{
return MaxCalendarMonth;
}
return (12);
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and MaxCalendarYear.
//
public override int GetYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartYear));
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public override bool IsLeapDay(int year, int month, int day, int era)
{
// The year/month/era value checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
"day",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Day,
daysInMonth,
month));
}
return (IsLeapYear(year, era) && month == 12 && day == 30);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public override int GetLeapMonth(int year, int era)
{
CheckYearRange(year, era);
return (0);
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public override bool IsLeapMonth(int year, int month, int era)
{
CheckYearMonthRange(year, month, era);
return (false);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public override bool IsLeapYear(int year, int era)
{
CheckYearRange(year, era);
if (year == MaxCalendarYear)
{
return false;
}
return (GetAbsoluteDatePersian(year + 1, 1, 1) - GetAbsoluteDatePersian(year, 1, 1)) == 366;
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
// The year/month/era checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
// BCLDebug.Log("year = " + year + ", month = " + month + ", day = " + day);
throw new ArgumentOutOfRangeException(
"day",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Day,
daysInMonth,
month));
}
long lDate = GetAbsoluteDatePersian(year, month, day);
if (lDate >= 0)
{
return (new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond)));
}
else
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 1410;
public override int TwoDigitYearMax
{
get
{
if (twoDigitYearMax == -1)
{
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
"value",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
MaxCalendarYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException("year",
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (year < 100)
{
return (base.ToFourDigitYear(year));
}
if (year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarYear));
}
return (year);
}
}
}
| |
// 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.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
namespace System.Collections.Generic
{
[DebuggerTypeProxy(typeof(ICollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public class LinkedList<T> : ICollection<T>, ICollection, IReadOnlyCollection<T>, ISerializable, IDeserializationCallback
{
// This LinkedList is a doubly-Linked circular list.
internal LinkedListNode<T> head;
internal int count;
internal int version;
private object _syncRoot;
private SerializationInfo _siInfo; //A temporary variable which we need during deserialization.
// names for serialization
private const string VersionName = "Version";
private const string CountName = "Count";
private const string ValuesName = "Data";
public LinkedList()
{
}
public LinkedList(IEnumerable<T> collection)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
foreach (T item in collection)
{
AddLast(item);
}
}
protected LinkedList(SerializationInfo info, StreamingContext context)
{
_siInfo = info;
}
public int Count
{
get { return count; }
}
public LinkedListNode<T> First
{
get { return head; }
}
public LinkedListNode<T> Last
{
get { return head == null ? null : head.prev; }
}
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
void ICollection<T>.Add(T value)
{
AddLast(value);
}
public LinkedListNode<T> AddAfter(LinkedListNode<T> node, T value)
{
ValidateNode(node);
LinkedListNode<T> result = new LinkedListNode<T>(node.list, value);
InternalInsertNodeBefore(node.next, result);
return result;
}
public void AddAfter(LinkedListNode<T> node, LinkedListNode<T> newNode)
{
ValidateNode(node);
ValidateNewNode(newNode);
InternalInsertNodeBefore(node.next, newNode);
newNode.list = this;
}
public LinkedListNode<T> AddBefore(LinkedListNode<T> node, T value)
{
ValidateNode(node);
LinkedListNode<T> result = new LinkedListNode<T>(node.list, value);
InternalInsertNodeBefore(node, result);
if (node == head)
{
head = result;
}
return result;
}
public void AddBefore(LinkedListNode<T> node, LinkedListNode<T> newNode)
{
ValidateNode(node);
ValidateNewNode(newNode);
InternalInsertNodeBefore(node, newNode);
newNode.list = this;
if (node == head)
{
head = newNode;
}
}
public LinkedListNode<T> AddFirst(T value)
{
LinkedListNode<T> result = new LinkedListNode<T>(this, value);
if (head == null)
{
InternalInsertNodeToEmptyList(result);
}
else
{
InternalInsertNodeBefore(head, result);
head = result;
}
return result;
}
public void AddFirst(LinkedListNode<T> node)
{
ValidateNewNode(node);
if (head == null)
{
InternalInsertNodeToEmptyList(node);
}
else
{
InternalInsertNodeBefore(head, node);
head = node;
}
node.list = this;
}
public LinkedListNode<T> AddLast(T value)
{
LinkedListNode<T> result = new LinkedListNode<T>(this, value);
if (head == null)
{
InternalInsertNodeToEmptyList(result);
}
else
{
InternalInsertNodeBefore(head, result);
}
return result;
}
public void AddLast(LinkedListNode<T> node)
{
ValidateNewNode(node);
if (head == null)
{
InternalInsertNodeToEmptyList(node);
}
else
{
InternalInsertNodeBefore(head, node);
}
node.list = this;
}
public void Clear()
{
LinkedListNode<T> current = head;
while (current != null)
{
LinkedListNode<T> temp = current;
current = current.Next; // use Next the instead of "next", otherwise it will loop forever
temp.Invalidate();
}
head = null;
count = 0;
version++;
}
public bool Contains(T value)
{
return Find(value) != null;
}
public void CopyTo(T[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (index > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_BiggerThanCollection);
}
if (array.Length - index < Count)
{
throw new ArgumentException(SR.Arg_InsufficientSpace);
}
LinkedListNode<T> node = head;
if (node != null)
{
do
{
array[index++] = node.item;
node = node.next;
} while (node != head);
}
}
public LinkedListNode<T> Find(T value)
{
LinkedListNode<T> node = head;
EqualityComparer<T> c = EqualityComparer<T>.Default;
if (node != null)
{
if (value != null)
{
do
{
if (c.Equals(node.item, value))
{
return node;
}
node = node.next;
} while (node != head);
}
else
{
do
{
if (node.item == null)
{
return node;
}
node = node.next;
} while (node != head);
}
}
return null;
}
public LinkedListNode<T> FindLast(T value)
{
if (head == null) return null;
LinkedListNode<T> last = head.prev;
LinkedListNode<T> node = last;
EqualityComparer<T> c = EqualityComparer<T>.Default;
if (node != null)
{
if (value != null)
{
do
{
if (c.Equals(node.item, value))
{
return node;
}
node = node.prev;
} while (node != last);
}
else
{
do
{
if (node.item == null)
{
return node;
}
node = node.prev;
} while (node != last);
}
}
return null;
}
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return GetEnumerator();
}
public bool Remove(T value)
{
LinkedListNode<T> node = Find(value);
if (node != null)
{
InternalRemoveNode(node);
return true;
}
return false;
}
public void Remove(LinkedListNode<T> node)
{
ValidateNode(node);
InternalRemoveNode(node);
}
public void RemoveFirst()
{
if (head == null) { throw new InvalidOperationException(SR.LinkedListEmpty); }
InternalRemoveNode(head);
}
public void RemoveLast()
{
if (head == null) { throw new InvalidOperationException(SR.LinkedListEmpty); }
InternalRemoveNode(head.prev);
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
// Customized serialization for LinkedList.
// We need to do this because it will be too expensive to Serialize each node.
// This will give us the flexiblility to change internal implementation freely in future.
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
info.AddValue(VersionName, version);
info.AddValue(CountName, count); // this is the length of the bucket array.
if (count != 0)
{
T[] array = new T[count];
CopyTo(array, 0);
info.AddValue(ValuesName, array, typeof(T[]));
}
}
public virtual void OnDeserialization(Object sender)
{
if (_siInfo == null)
{
return; //Somebody had a dependency on this Dictionary and fixed us up before the ObjectManager got to it.
}
int realVersion = _siInfo.GetInt32(VersionName);
int count = _siInfo.GetInt32(CountName);
if (count != 0)
{
T[] array = (T[])_siInfo.GetValue(ValuesName, typeof(T[]));
if (array == null)
{
throw new SerializationException(SR.Serialization_MissingValues);
}
for (int i = 0; i < array.Length; i++)
{
AddLast(array[i]);
}
}
else
{
head = null;
}
version = realVersion;
_siInfo = null;
}
private void InternalInsertNodeBefore(LinkedListNode<T> node, LinkedListNode<T> newNode)
{
newNode.next = node;
newNode.prev = node.prev;
node.prev.next = newNode;
node.prev = newNode;
version++;
count++;
}
private void InternalInsertNodeToEmptyList(LinkedListNode<T> newNode)
{
Debug.Assert(head == null && count == 0, "LinkedList must be empty when this method is called!");
newNode.next = newNode;
newNode.prev = newNode;
head = newNode;
version++;
count++;
}
internal void InternalRemoveNode(LinkedListNode<T> node)
{
Debug.Assert(node.list == this, "Deleting the node from another list!");
Debug.Assert(head != null, "This method shouldn't be called on empty list!");
if (node.next == node)
{
Debug.Assert(count == 1 && head == node, "this should only be true for a list with only one node");
head = null;
}
else
{
node.next.prev = node.prev;
node.prev.next = node.next;
if (head == node)
{
head = node.next;
}
}
node.Invalidate();
count--;
version++;
}
internal void ValidateNewNode(LinkedListNode<T> node)
{
if (node == null)
{
throw new ArgumentNullException(nameof(node));
}
if (node.list != null)
{
throw new InvalidOperationException(SR.LinkedListNodeIsAttached);
}
}
internal void ValidateNode(LinkedListNode<T> node)
{
if (node == null)
{
throw new ArgumentNullException(nameof(node));
}
if (node.list != this)
{
throw new InvalidOperationException(SR.ExternalLinkedListNode);
}
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
Threading.Interlocked.CompareExchange<object>(ref _syncRoot, new object(), null);
}
return _syncRoot;
}
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < Count)
{
throw new ArgumentException(SR.Arg_InsufficientSpace);
}
T[] tArray = array as T[];
if (tArray != null)
{
CopyTo(tArray, index);
}
else
{
// No need to use reflection to verify that the types are compatible because it isn't 100% correct and we can rely
// on the runtime validation during the cast that happens below (i.e. we will get an ArrayTypeMismatchException).
object[] objects = array as object[];
if (objects == null)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
LinkedListNode<T> node = head;
try
{
if (node != null)
{
do
{
objects[index++] = node.item;
node = node.next;
} while (node != head);
}
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")]
public struct Enumerator : IEnumerator<T>, IEnumerator, ISerializable, IDeserializationCallback
{
private LinkedList<T> _list;
private LinkedListNode<T> _node;
private int _version;
private T _current;
private int _index;
const string LinkedListName = "LinkedList";
const string CurrentValueName = "Current";
const string VersionName = "Version";
const string IndexName = "Index";
internal Enumerator(LinkedList<T> list)
{
_list = list;
_version = list.version;
_node = list.head;
_current = default(T);
_index = 0;
}
private Enumerator(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
public T Current
{
get { return _current; }
}
object IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _list.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _current;
}
}
public bool MoveNext()
{
if (_version != _list.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
if (_node == null)
{
_index = _list.Count + 1;
return false;
}
++_index;
_current = _node.item;
_node = _node.next;
if (_node == _list.head)
{
_node = null;
}
return true;
}
void IEnumerator.Reset()
{
if (_version != _list.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
_current = default(T);
_node = _list.head;
_index = 0;
}
public void Dispose()
{
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
void IDeserializationCallback.OnDeserialization(Object sender)
{
throw new PlatformNotSupportedException();
}
}
}
// Note following class is not serializable since we customized the serialization of LinkedList.
public sealed class LinkedListNode<T>
{
internal LinkedList<T> list;
internal LinkedListNode<T> next;
internal LinkedListNode<T> prev;
internal T item;
public LinkedListNode(T value)
{
item = value;
}
internal LinkedListNode(LinkedList<T> list, T value)
{
this.list = list;
item = value;
}
public LinkedList<T> List
{
get { return list; }
}
public LinkedListNode<T> Next
{
get { return next == null || next == list.head ? null : next; }
}
public LinkedListNode<T> Previous
{
get { return prev == null || this == list.head ? null : prev; }
}
public T Value
{
get { return item; }
set { item = value; }
}
internal void Invalidate()
{
list = null;
next = null;
prev = null;
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
using Blueprint41.DatastoreTemplates;
using q = Domain.Data.Query;
namespace Domain.Data.Manipulation
{
public interface IIllustrationOriginalData : ISchemaBaseOriginalData
{
string Diagram { get; }
}
public partial class Illustration : OGM<Illustration, Illustration.IllustrationData, System.String>, ISchemaBase, INeo4jBase, IIllustrationOriginalData
{
#region Initialize
static Illustration()
{
Register.Types();
}
protected override void RegisterGeneratedStoredQueries()
{
#region LoadByKeys
RegisterQuery(nameof(LoadByKeys), (query, alias) => query.
Where(alias.Uid.In(Parameter.New<System.String>(Param0))));
#endregion
AdditionalGeneratedStoredQueries();
}
partial void AdditionalGeneratedStoredQueries();
public static Dictionary<System.String, Illustration> LoadByKeys(IEnumerable<System.String> uids)
{
return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item);
}
protected static void RegisterQuery(string name, Func<IMatchQuery, q.IllustrationAlias, IWhereQuery> query)
{
q.IllustrationAlias alias;
IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.Illustration.Alias(out alias));
IWhereQuery partial = query.Invoke(matchQuery, alias);
ICompiled compiled = partial.Return(alias).Compile();
RegisterQuery(name, compiled);
}
public override string ToString()
{
return $"Illustration => Diagram : {this.Diagram}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}";
}
public override int GetHashCode()
{
return base.GetHashCode();
}
protected override void LazySet()
{
base.LazySet();
if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged)
{
if ((object)InnerData == (object)OriginalData)
OriginalData = new IllustrationData(InnerData);
}
}
#endregion
#region Validations
protected override void ValidateSave()
{
bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged);
#pragma warning disable CS0472
if (InnerData.Diagram == null)
throw new PersistenceException(string.Format("Cannot save Illustration with key '{0}' because the Diagram cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ModifiedDate == null)
throw new PersistenceException(string.Format("Cannot save Illustration with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
#pragma warning restore CS0472
}
protected override void ValidateDelete()
{
}
#endregion
#region Inner Data
public class IllustrationData : Data<System.String>
{
public IllustrationData()
{
}
public IllustrationData(IllustrationData data)
{
Diagram = data.Diagram;
ModifiedDate = data.ModifiedDate;
Uid = data.Uid;
}
#region Initialize Collections
protected override void InitializeCollections()
{
NodeType = "Illustration";
}
public string NodeType { get; private set; }
sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); }
sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); }
#endregion
#region Map Data
sealed public override IDictionary<string, object> MapTo()
{
IDictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("Diagram", Diagram);
dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate));
dictionary.Add("Uid", Uid);
return dictionary;
}
sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties)
{
object value;
if (properties.TryGetValue("Diagram", out value))
Diagram = (string)value;
if (properties.TryGetValue("ModifiedDate", out value))
ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("Uid", out value))
Uid = (string)value;
}
#endregion
#region Members for interface IIllustration
public string Diagram { get; set; }
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get; set; }
#endregion
#region Members for interface INeo4jBase
public string Uid { get; set; }
#endregion
}
#endregion
#region Outer Data
#region Members for interface IIllustration
public string Diagram { get { LazyGet(); return InnerData.Diagram; } set { if (LazySet(Members.Diagram, InnerData.Diagram, value)) InnerData.Diagram = value; } }
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } }
#endregion
#region Members for interface INeo4jBase
public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } }
#endregion
#region Virtual Node Type
public string NodeType { get { return InnerData.NodeType; } }
#endregion
#endregion
#region Reflection
private static IllustrationMembers members = null;
public static IllustrationMembers Members
{
get
{
if (members == null)
{
lock (typeof(Illustration))
{
if (members == null)
members = new IllustrationMembers();
}
}
return members;
}
}
public class IllustrationMembers
{
internal IllustrationMembers() { }
#region Members for interface IIllustration
public Property Diagram { get; } = Datastore.AdventureWorks.Model.Entities["Illustration"].Properties["Diagram"];
#endregion
#region Members for interface ISchemaBase
public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"];
#endregion
#region Members for interface INeo4jBase
public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"];
#endregion
}
private static IllustrationFullTextMembers fullTextMembers = null;
public static IllustrationFullTextMembers FullTextMembers
{
get
{
if (fullTextMembers == null)
{
lock (typeof(Illustration))
{
if (fullTextMembers == null)
fullTextMembers = new IllustrationFullTextMembers();
}
}
return fullTextMembers;
}
}
public class IllustrationFullTextMembers
{
internal IllustrationFullTextMembers() { }
}
sealed public override Entity GetEntity()
{
if (entity == null)
{
lock (typeof(Illustration))
{
if (entity == null)
entity = Datastore.AdventureWorks.Model.Entities["Illustration"];
}
}
return entity;
}
private static IllustrationEvents events = null;
public static IllustrationEvents Events
{
get
{
if (events == null)
{
lock (typeof(Illustration))
{
if (events == null)
events = new IllustrationEvents();
}
}
return events;
}
}
public class IllustrationEvents
{
#region OnNew
private bool onNewIsRegistered = false;
private EventHandler<Illustration, EntityEventArgs> onNew;
public event EventHandler<Illustration, EntityEventArgs> OnNew
{
add
{
lock (this)
{
if (!onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
Entity.Events.OnNew += onNewProxy;
onNewIsRegistered = true;
}
onNew += value;
}
}
remove
{
lock (this)
{
onNew -= value;
if (onNew == null && onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
onNewIsRegistered = false;
}
}
}
}
private void onNewProxy(object sender, EntityEventArgs args)
{
EventHandler<Illustration, EntityEventArgs> handler = onNew;
if ((object)handler != null)
handler.Invoke((Illustration)sender, args);
}
#endregion
#region OnDelete
private bool onDeleteIsRegistered = false;
private EventHandler<Illustration, EntityEventArgs> onDelete;
public event EventHandler<Illustration, EntityEventArgs> OnDelete
{
add
{
lock (this)
{
if (!onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
Entity.Events.OnDelete += onDeleteProxy;
onDeleteIsRegistered = true;
}
onDelete += value;
}
}
remove
{
lock (this)
{
onDelete -= value;
if (onDelete == null && onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
onDeleteIsRegistered = false;
}
}
}
}
private void onDeleteProxy(object sender, EntityEventArgs args)
{
EventHandler<Illustration, EntityEventArgs> handler = onDelete;
if ((object)handler != null)
handler.Invoke((Illustration)sender, args);
}
#endregion
#region OnSave
private bool onSaveIsRegistered = false;
private EventHandler<Illustration, EntityEventArgs> onSave;
public event EventHandler<Illustration, EntityEventArgs> OnSave
{
add
{
lock (this)
{
if (!onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
Entity.Events.OnSave += onSaveProxy;
onSaveIsRegistered = true;
}
onSave += value;
}
}
remove
{
lock (this)
{
onSave -= value;
if (onSave == null && onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
onSaveIsRegistered = false;
}
}
}
}
private void onSaveProxy(object sender, EntityEventArgs args)
{
EventHandler<Illustration, EntityEventArgs> handler = onSave;
if ((object)handler != null)
handler.Invoke((Illustration)sender, args);
}
#endregion
#region OnPropertyChange
public static class OnPropertyChange
{
#region OnDiagram
private static bool onDiagramIsRegistered = false;
private static EventHandler<Illustration, PropertyEventArgs> onDiagram;
public static event EventHandler<Illustration, PropertyEventArgs> OnDiagram
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onDiagramIsRegistered)
{
Members.Diagram.Events.OnChange -= onDiagramProxy;
Members.Diagram.Events.OnChange += onDiagramProxy;
onDiagramIsRegistered = true;
}
onDiagram += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onDiagram -= value;
if (onDiagram == null && onDiagramIsRegistered)
{
Members.Diagram.Events.OnChange -= onDiagramProxy;
onDiagramIsRegistered = false;
}
}
}
}
private static void onDiagramProxy(object sender, PropertyEventArgs args)
{
EventHandler<Illustration, PropertyEventArgs> handler = onDiagram;
if ((object)handler != null)
handler.Invoke((Illustration)sender, args);
}
#endregion
#region OnModifiedDate
private static bool onModifiedDateIsRegistered = false;
private static EventHandler<Illustration, PropertyEventArgs> onModifiedDate;
public static event EventHandler<Illustration, PropertyEventArgs> OnModifiedDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
Members.ModifiedDate.Events.OnChange += onModifiedDateProxy;
onModifiedDateIsRegistered = true;
}
onModifiedDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onModifiedDate -= value;
if (onModifiedDate == null && onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
onModifiedDateIsRegistered = false;
}
}
}
}
private static void onModifiedDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<Illustration, PropertyEventArgs> handler = onModifiedDate;
if ((object)handler != null)
handler.Invoke((Illustration)sender, args);
}
#endregion
#region OnUid
private static bool onUidIsRegistered = false;
private static EventHandler<Illustration, PropertyEventArgs> onUid;
public static event EventHandler<Illustration, PropertyEventArgs> OnUid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
Members.Uid.Events.OnChange += onUidProxy;
onUidIsRegistered = true;
}
onUid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onUid -= value;
if (onUid == null && onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
onUidIsRegistered = false;
}
}
}
}
private static void onUidProxy(object sender, PropertyEventArgs args)
{
EventHandler<Illustration, PropertyEventArgs> handler = onUid;
if ((object)handler != null)
handler.Invoke((Illustration)sender, args);
}
#endregion
}
#endregion
}
#endregion
#region IIllustrationOriginalData
public IIllustrationOriginalData OriginalVersion { get { return this; } }
#region Members for interface IIllustration
string IIllustrationOriginalData.Diagram { get { return OriginalData.Diagram; } }
#endregion
#region Members for interface ISchemaBase
ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } }
System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } }
#endregion
#region Members for interface INeo4jBase
INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } }
string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } }
#endregion
#endregion
}
}
| |
// ****************************************************************
// Copyright 2007, 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 System.Windows.Forms;
using NUnit.Framework;
namespace NUnit.ProjectEditor
{
/// <summary>
/// TestFixtures that test Forms inherit from this class.
/// </summary>
public class FormTester : ControlTester
{
public FormTester() { }
public FormTester( Form form ) : base( form ) { }
public Form Form
{
get { return Control as Form; }
set { Control = value; }
}
}
/// <summary>
/// TestFixtures that test Controls inherit from this class.
/// </summary>
public class ControlTester
{
public ControlTester() { }
public ControlTester( Control control )
{
this.control = control;
}
// TODO: Rewrite using generics when we move to .NET 2.0
// The textBox we are testing
private Control control;
// Various ways of looking at this textBox's controls
private ControlCollection controls;
private ButtonCollection buttons;
private LabelCollection labels;
private TextBoxCollection textboxes;
private ComboBoxCollection combos;
#region Properties
/// <summary>
/// Get and set the textBox to be tested
/// </summary>
public Control Control
{
get { return control; }
set
{
control = value;
InitCollections();
}
}
private void InitCollections()
{
controls = new ControlCollection( control.Controls );
// These will be initialized as needed
buttons = null;
labels = null;
textboxes = null;
combos = null;
}
/// <summary>
/// Get our collection of all the controls on this textBox.
/// </summary>
public ControlCollection Controls
{
get { return controls; }
}
/// <summary>
/// Get our collection of all the buttons on this textBox.
/// </summary>
public ButtonCollection Buttons
{
get
{
if ( buttons == null )
buttons = new ButtonCollection( control.Controls );
return buttons;
}
}
/// <summary>
/// Get our collection of all the labels on this textBox.
/// </summary>
public LabelCollection Labels
{
get
{
if (labels == null )
labels = new LabelCollection( control.Controls );
return labels;
}
}
/// <summary>
/// Get our collection of all the TextBoxes on this textBox.
/// </summary>
public TextBoxCollection TextBoxes
{
get
{
if ( textboxes == null )
textboxes = new TextBoxCollection( control.Controls );
return textboxes;
}
}
/// <summary>
/// Get our collection of all ComboBoxes on the form
/// </summary>
public ComboBoxCollection Combos
{
get
{
if ( combos == null )
combos = new ComboBoxCollection( control.Controls );
return combos;
}
}
#endregion
#region Assertions
/// <summary>
/// Assert that a textBox with a given name exists on this textBox.
/// </summary>
/// <param name="name">The name of the textBox.</param>
public void AssertControlExists( string targetName )
{
AssertControlExists( targetName, null );
}
public void AssertControlExists( string expectedName, Type expectedType )
{
bool gotName = false;
System.Type gotType = null;
foreach( Control ctl in control.Controls )
{
if ( ctl.Name == expectedName )
{
gotName = true;
if ( expectedType == null )
return;
gotType = ctl.GetType();
if ( expectedType.IsAssignableFrom( gotType ) )
return;
}
}
if ( gotName )
Assert.Fail( "Expected control {0} to be a {1} but was {2}", expectedName, expectedType.Name, gotType.Name );
else
Assert.Fail( "{0} does not contain {1} control", control.Name, expectedName );
}
public void AssertControlsAreStackedVertically( params string[] names )
{
string prior = null;
foreach( string current in names )
{
if ( prior != null )
{
if ( Controls[prior].Bottom > Controls[current].Top )
Assert.Fail( "The {0} control should be above the {1} control", prior, current );
}
prior = current;
}
}
#endregion
#region Other public methods
public string GetText( string name )
{
return Controls[ name ].Text;
}
#endregion
#region Nested Collection Classes
#region Enumerator used by all collections
public class ControlEnumerator : IEnumerator
{
IEnumerator sourceEnum;
System.Type typeFilter;
public ControlEnumerator( Control.ControlCollection source, System.Type typeFilter )
{
this.sourceEnum = source.GetEnumerator();
this.typeFilter = typeFilter;
}
#region IEnumerator Members
public void Reset()
{
sourceEnum.Reset();
}
public object Current
{
get { return sourceEnum.Current; }
}
public bool MoveNext()
{
while( sourceEnum.MoveNext() )
{
if ( typeFilter == null || typeFilter.IsAssignableFrom( Current.GetType() ) )
return true;
}
return false;
}
#endregion
}
#endregion
#region Control Collection
public class ControlCollection : IEnumerable
{
protected Control.ControlCollection source;
private System.Type typeFilter;
public ControlCollection( Control.ControlCollection source )
: this( source, null ) { }
public ControlCollection( Control.ControlCollection source, System.Type typeFilter )
{
this.source = source;
this.typeFilter = typeFilter;
}
public Control this[string name]
{
get
{
foreach( Control control in this )
{
if ( control.Name == name )
return control;
}
return null;
}
}
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return new ControlEnumerator( this.source, this.typeFilter );
}
#endregion
}
#endregion
#region ButtonCollection
public class ButtonCollection : ControlCollection
{
public ButtonCollection( Control.ControlCollection controls )
: base( controls, typeof( Button ) ) { }
public new Button this[string name]
{
get { return base[name] as Button; }
}
}
#endregion
#region LabelCollection
public class LabelCollection : ControlCollection
{
public LabelCollection( Control.ControlCollection controls )
: base( controls, typeof( Label ) ) { }
public new Label this[string name]
{
get { return base[name] as Label; }
}
}
#endregion
#region TextBoxCollection
public class TextBoxCollection : ControlCollection
{
public TextBoxCollection( Control.ControlCollection controls )
: base( controls, typeof( TextBox ) ) { }
public new TextBox this[string name]
{
get { return base[name] as TextBox; }
}
}
#endregion
#region ComboBoxCollection
public class ComboBoxCollection : ControlCollection
{
public ComboBoxCollection( Control.ControlCollection controls )
: base( controls, typeof( ComboBox ) ) { }
public new ComboBox this[string name]
{
get { return base[name] as ComboBox; }
}
}
#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.
/*=============================================================================
**
**
**
** Purpose: synchronization primitive that can also be used for interprocess synchronization
**
**
=============================================================================*/
using System;
using System.Threading;
using System.Runtime.CompilerServices;
using System.IO;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Diagnostics.Contracts;
namespace System.Threading
{
[ComVisible(true)]
public sealed class Mutex : WaitHandle
{
private static bool s_dummyBool;
public Mutex(bool initiallyOwned, String name, out bool createdNew)
{
if (null != name && ((int)Interop.Constants.MaxPath) < (uint)name.Length)
{
throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, name));
}
Contract.EndContractBlock();
SafeWaitHandle mutexHandle;
int errorCode = CreateMutexHandle(initiallyOwned, name, out mutexHandle);
if (mutexHandle.IsInvalid)
{
mutexHandle.SetHandleAsInvalid();
if (null != name && 0 != name.Length && Interop.mincore.Errors.ERROR_INVALID_HANDLE == errorCode)
throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
throw ExceptionFromCreationError(errorCode, name);
}
createdNew = errorCode != Interop.mincore.Errors.ERROR_ALREADY_EXISTS;
SafeWaitHandle = mutexHandle;
}
public Mutex(bool initiallyOwned, String name)
: this(initiallyOwned, name, out s_dummyBool)
{
}
public Mutex(bool initiallyOwned)
: this(initiallyOwned, null, out s_dummyBool)
{
}
public Mutex()
: this(false, null, out s_dummyBool)
{
}
private Mutex(SafeWaitHandle handle)
{
SafeWaitHandle = handle;
}
public static Mutex OpenExisting(string name)
{
Mutex result;
switch (OpenExistingWorker(name, out result))
{
case OpenExistingResult.NameNotFound:
throw new WaitHandleCannotBeOpenedException();
case OpenExistingResult.NameInvalid:
throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
case OpenExistingResult.PathNotFound:
throw new IOException(SR.Format(SR.IO_PathNotFound_Path, name));
default:
return result;
}
}
public static bool TryOpenExisting(string name, out Mutex result)
{
return OpenExistingWorker(name, out result) == OpenExistingResult.Success;
}
private static OpenExistingResult OpenExistingWorker(string name, out Mutex result)
{
if (name == null)
{
throw new ArgumentNullException("name", SR.ArgumentNull_WithParamName);
}
if (name.Length == 0)
{
throw new ArgumentException(SR.Argument_EmptyName, "name");
}
if (((int)Interop.Constants.MaxPath) < (uint)name.Length)
{
throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, name));
}
Contract.EndContractBlock();
result = null;
// To allow users to view & edit the ACL's, call OpenMutex
// with parameters to allow us to view & edit the ACL. This will
// fail if we don't have permission to view or edit the ACL's.
// If that happens, ask for less permissions.
SafeWaitHandle myHandle = new SafeWaitHandle(Interop.mincore.OpenMutex((uint)(Interop.Constants.MutexModifyState | Interop.Constants.Synchronize), false, name), true);
int errorCode = 0;
if (myHandle.IsInvalid)
{
errorCode = (int)Interop.mincore.GetLastError();
if (Interop.mincore.Errors.ERROR_FILE_NOT_FOUND == errorCode || Interop.mincore.Errors.ERROR_INVALID_NAME == errorCode)
return OpenExistingResult.NameNotFound;
if (Interop.mincore.Errors.ERROR_PATH_NOT_FOUND == errorCode)
return OpenExistingResult.PathNotFound;
if (null != name && 0 != name.Length && Interop.mincore.Errors.ERROR_INVALID_HANDLE == errorCode)
return OpenExistingResult.NameInvalid;
// this is for passed through Win32Native Errors
throw ExceptionFromCreationError(errorCode, name);
}
result = new Mutex(myHandle);
return OpenExistingResult.Success;
}
// Note: To call ReleaseMutex, you must have an ACL granting you
// MUTEX_MODIFY_STATE rights (0x0001). The other interesting value
// in a Mutex's ACL is MUTEX_ALL_ACCESS (0x1F0001).
public void ReleaseMutex()
{
waitHandle.DangerousAddRef();
try
{
if (!Interop.mincore.ReleaseMutex(waitHandle.DangerousGetHandle()))
throw new InvalidOperationException(SR.Arg_SynchronizationLockException);
}
finally
{
waitHandle.DangerousRelease();
}
}
private static int CreateMutexHandle(bool initiallyOwned, String name, out SafeWaitHandle mutexHandle)
{
int errorCode;
while (true)
{
mutexHandle = new SafeWaitHandle(Interop.mincore.CreateMutexEx(IntPtr.Zero, name, initiallyOwned ? (uint)Interop.Constants.CreateMutexInitialOwner : 0, (uint)Interop.Constants.MutexAllAccess), true);
errorCode = (int)Interop.mincore.GetLastError();
if (!mutexHandle.IsInvalid)
{
break;
}
if (errorCode == Interop.mincore.Errors.ERROR_ACCESS_DENIED)
{
// If a mutex with the name already exists, OS will try to open it with FullAccess.
// It might fail if we don't have enough access. In that case, we try to open the mutex will modify and synchronize access.
//
mutexHandle = new SafeWaitHandle(Interop.mincore.OpenMutex((uint)(Interop.Constants.MutexModifyState | Interop.Constants.Synchronize), false, name), true);
if (!mutexHandle.IsInvalid)
{
errorCode = Interop.mincore.Errors.ERROR_ALREADY_EXISTS;
}
else
{
errorCode = (int)Interop.mincore.GetLastError();
}
// There could be a race here, the other owner of the mutex can free the mutex,
// We need to retry creation in that case.
if (errorCode != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND)
{
if (errorCode == Interop.mincore.Errors.ERROR_SUCCESS)
{
errorCode = Interop.mincore.Errors.ERROR_ALREADY_EXISTS;
}
break;
}
}
else
{
break;
}
}
return errorCode;
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
//#define ConfigTrace
using Microsoft.VisualStudio.Shell.Interop;
using MSBuildConstruction = Microsoft.Build.Construction;
using MSBuildExecution = Microsoft.Build.Execution;
namespace Microsoft.VisualStudioTools.Project {
[ComVisible(true)]
internal abstract class ProjectConfig :
IVsCfg,
IVsProjectCfg,
IVsProjectCfg2,
IVsProjectFlavorCfg,
IVsDebuggableProjectCfg,
ISpecifyPropertyPages,
IVsSpecifyProjectDesignerPages,
IVsCfgBrowseObject {
internal const string Debug = "Debug";
internal const string AnyCPU = "AnyCPU";
private ProjectNode project;
private string configName;
private MSBuildExecution.ProjectInstance currentConfig;
private IVsProjectFlavorCfg flavoredCfg;
private List<OutputGroup> outputGroups;
private BuildableProjectConfig buildableCfg;
private string platformName;
#region properties
public string PlatformName {
get {
return platformName;
}
set {
platformName = value;
}
}
internal ProjectNode ProjectMgr {
get {
return this.project;
}
}
public string ConfigName {
get {
return this.configName;
}
set {
this.configName = value;
}
}
internal IList<OutputGroup> OutputGroups {
get {
if (null == this.outputGroups) {
// Initialize output groups
this.outputGroups = new List<OutputGroup>();
// If the project is not buildable (no CoreCompile target)
// then don't bother getting the output groups.
if (this.project.BuildProject != null && this.project.BuildProject.Targets.ContainsKey("CoreCompile")) {
// Get the list of group names from the project.
// The main reason we get it from the project is to make it easier for someone to modify
// it by simply overriding that method and providing the correct MSBuild target(s).
IList<KeyValuePair<string, string>> groupNames = project.GetOutputGroupNames();
if (groupNames != null) {
// Populate the output array
foreach (KeyValuePair<string, string> group in groupNames) {
OutputGroup outputGroup = CreateOutputGroup(project, group);
this.outputGroups.Add(outputGroup);
}
}
}
}
return this.outputGroups;
}
}
#endregion
#region ctors
internal ProjectConfig(ProjectNode project, string configuration) {
this.project = project;
if (configuration.Contains("|")) { // If configuration is in the form "<Configuration>|<Platform>"
string[] configStrArray = configuration.Split('|');
if (2 == configStrArray.Length) {
this.configName = configStrArray[0];
this.platformName = configStrArray[1];
}
else {
throw new Exception(string.Format(CultureInfo.InvariantCulture, "Invalid configuration format: {0}", configuration));
}
}
else { // If configuration is in the form "<Configuration>"
this.configName = configuration;
}
var flavoredCfgProvider = ProjectMgr.GetOuterInterface<IVsProjectFlavorCfgProvider>();
Utilities.ArgumentNotNull("flavoredCfgProvider", flavoredCfgProvider);
ErrorHandler.ThrowOnFailure(flavoredCfgProvider.CreateProjectFlavorCfg(this, out flavoredCfg));
Utilities.ArgumentNotNull("flavoredCfg", flavoredCfg);
// if the flavored object support XML fragment, initialize it
IPersistXMLFragment persistXML = flavoredCfg as IPersistXMLFragment;
if (null != persistXML) {
this.project.LoadXmlFragment(persistXML, configName, platformName);
}
}
#endregion
#region methods
internal virtual OutputGroup CreateOutputGroup(ProjectNode project, KeyValuePair<string, string> group) {
OutputGroup outputGroup = new OutputGroup(group.Key, group.Value, project, this);
return outputGroup;
}
public void PrepareBuild(bool clean) {
project.PrepareBuild(this.configName, clean);
}
public virtual string GetConfigurationProperty(string propertyName, bool resetCache) {
MSBuildExecution.ProjectPropertyInstance property = GetMsBuildProperty(propertyName, resetCache);
if (property == null)
return null;
return property.EvaluatedValue;
}
public virtual void SetConfigurationProperty(string propertyName, string propertyValue) {
if (!this.project.QueryEditProjectFile(false)) {
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
string condition = String.Format(CultureInfo.InvariantCulture, ConfigProvider.configString, this.ConfigName);
SetPropertyUnderCondition(propertyName, propertyValue, condition);
// property cache will need to be updated
this.currentConfig = null;
return;
}
/// <summary>
/// Emulates the behavior of SetProperty(name, value, condition) on the old MSBuild object model.
/// This finds a property group with the specified condition (or creates one if necessary) then sets the property in there.
/// </summary>
private void SetPropertyUnderCondition(string propertyName, string propertyValue, string condition) {
string conditionTrimmed = (condition == null) ? String.Empty : condition.Trim();
if (conditionTrimmed.Length == 0) {
this.project.BuildProject.SetProperty(propertyName, propertyValue);
return;
}
// New OM doesn't have a convenient equivalent for setting a property with a particular property group condition.
// So do it ourselves.
MSBuildConstruction.ProjectPropertyGroupElement newGroup = null;
foreach (MSBuildConstruction.ProjectPropertyGroupElement group in this.project.BuildProject.Xml.PropertyGroups) {
if (String.Equals(group.Condition.Trim(), conditionTrimmed, StringComparison.OrdinalIgnoreCase)) {
newGroup = group;
break;
}
}
if (newGroup == null) {
newGroup = this.project.BuildProject.Xml.AddPropertyGroup(); // Adds after last existing PG, else at start of project
newGroup.Condition = condition;
}
foreach (MSBuildConstruction.ProjectPropertyElement property in newGroup.PropertiesReversed) // If there's dupes, pick the last one so we win
{
if (String.Equals(property.Name, propertyName, StringComparison.OrdinalIgnoreCase) && property.Condition.Length == 0) {
property.Value = propertyValue;
return;
}
}
newGroup.AddProperty(propertyName, propertyValue);
}
/// <summary>
/// If flavored, and if the flavor config can be dirty, ask it if it is dirty
/// </summary>
/// <param name="storageType">Project file or user file</param>
/// <returns>0 = not dirty</returns>
internal int IsFlavorDirty(_PersistStorageType storageType) {
int isDirty = 0;
if (this.flavoredCfg != null && this.flavoredCfg is IPersistXMLFragment) {
ErrorHandler.ThrowOnFailure(((IPersistXMLFragment)this.flavoredCfg).IsFragmentDirty((uint)storageType, out isDirty));
}
return isDirty;
}
/// <summary>
/// If flavored, ask the flavor if it wants to provide an XML fragment
/// </summary>
/// <param name="flavor">Guid of the flavor</param>
/// <param name="storageType">Project file or user file</param>
/// <param name="fragment">Fragment that the flavor wants to save</param>
/// <returns>HRESULT</returns>
internal int GetXmlFragment(Guid flavor, _PersistStorageType storageType, out string fragment) {
fragment = null;
int hr = VSConstants.S_OK;
if (this.flavoredCfg != null && this.flavoredCfg is IPersistXMLFragment) {
Guid flavorGuid = flavor;
hr = ((IPersistXMLFragment)this.flavoredCfg).Save(ref flavorGuid, (uint)storageType, out fragment, 1);
}
return hr;
}
#endregion
#region IVsSpecifyPropertyPages
public void GetPages(CAUUID[] pages) {
this.GetCfgPropertyPages(pages);
}
#endregion
#region IVsSpecifyProjectDesignerPages
/// <summary>
/// Implementation of the IVsSpecifyProjectDesignerPages. It will retun the pages that are configuration dependent.
/// </summary>
/// <param name="pages">The pages to return.</param>
/// <returns>VSConstants.S_OK</returns>
public virtual int GetProjectDesignerPages(CAUUID[] pages) {
this.GetCfgPropertyPages(pages);
return VSConstants.S_OK;
}
#endregion
#region IVsCfg methods
/// <summary>
/// The display name is a two part item
/// first part is the config name, 2nd part is the platform name
/// </summary>
public virtual int get_DisplayName(out string name) {
if (!string.IsNullOrEmpty(PlatformName)) {
name = ConfigName + "|" + PlatformName;
} else {
name = DisplayName;
}
return VSConstants.S_OK;
}
private string DisplayName {
get {
string name;
string[] platform = new string[1];
uint[] actual = new uint[1];
name = this.configName;
// currently, we only support one platform, so just add it..
IVsCfgProvider provider;
ErrorHandler.ThrowOnFailure(project.GetCfgProvider(out provider));
ErrorHandler.ThrowOnFailure(((IVsCfgProvider2)provider).GetPlatformNames(1, platform, actual));
if (!string.IsNullOrEmpty(platform[0])) {
name += "|" + platform[0];
}
return name;
}
}
public virtual int get_IsDebugOnly(out int fDebug) {
fDebug = 0;
if (this.configName == "Debug") {
fDebug = 1;
}
return VSConstants.S_OK;
}
public virtual int get_IsReleaseOnly(out int fRelease) {
fRelease = 0;
if (this.configName == "Release") {
fRelease = 1;
}
return VSConstants.S_OK;
}
#endregion
#region IVsProjectCfg methods
public virtual int EnumOutputs(out IVsEnumOutputs eo) {
eo = null;
return VSConstants.E_NOTIMPL;
}
public virtual int get_BuildableProjectCfg(out IVsBuildableProjectCfg pb) {
if (project.BuildProject == null || !project.BuildProject.Targets.ContainsKey("CoreCompile")) {
// The project is not buildable, so don't return a config. This
// will hide the 'Build' commands from the VS UI.
pb = null;
return VSConstants.E_NOTIMPL;
}
if (buildableCfg == null) {
buildableCfg = new BuildableProjectConfig(this);
}
pb = buildableCfg;
return VSConstants.S_OK;
}
public virtual int get_CanonicalName(out string name) {
name = configName;
return VSConstants.S_OK;
}
public virtual int get_IsPackaged(out int pkgd) {
pkgd = 0;
return VSConstants.S_OK;
}
public virtual int get_IsSpecifyingOutputSupported(out int f) {
f = 1;
return VSConstants.S_OK;
}
public virtual int get_Platform(out Guid platform) {
platform = Guid.Empty;
return VSConstants.E_NOTIMPL;
}
public virtual int get_ProjectCfgProvider(out IVsProjectCfgProvider p) {
p = null;
IVsCfgProvider cfgProvider = null;
this.project.GetCfgProvider(out cfgProvider);
if (cfgProvider != null) {
p = cfgProvider as IVsProjectCfgProvider;
}
return (null == p) ? VSConstants.E_NOTIMPL : VSConstants.S_OK;
}
public virtual int get_RootURL(out string root) {
root = null;
return VSConstants.S_OK;
}
public virtual int get_TargetCodePage(out uint target) {
target = (uint)System.Text.Encoding.Default.CodePage;
return VSConstants.S_OK;
}
public virtual int get_UpdateSequenceNumber(ULARGE_INTEGER[] li) {
Utilities.ArgumentNotNull("li", li);
li[0] = new ULARGE_INTEGER();
li[0].QuadPart = 0;
return VSConstants.S_OK;
}
public virtual int OpenOutput(string name, out IVsOutput output) {
output = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsProjectCfg2 Members
public virtual int OpenOutputGroup(string szCanonicalName, out IVsOutputGroup ppIVsOutputGroup) {
ppIVsOutputGroup = null;
// Search through our list of groups to find the one they are looking forgroupName
foreach (OutputGroup group in OutputGroups) {
string groupName;
group.get_CanonicalName(out groupName);
if (String.Compare(groupName, szCanonicalName, StringComparison.OrdinalIgnoreCase) == 0) {
ppIVsOutputGroup = group;
break;
}
}
return (ppIVsOutputGroup != null) ? VSConstants.S_OK : VSConstants.E_FAIL;
}
public virtual int OutputsRequireAppRoot(out int pfRequiresAppRoot) {
pfRequiresAppRoot = 0;
return VSConstants.E_NOTIMPL;
}
public virtual int get_CfgType(ref Guid iidCfg, out IntPtr ppCfg) {
// Delegate to the flavored configuration (to enable a flavor to take control)
// Since we can be asked for Configuration we don't support, avoid throwing and return the HRESULT directly
int hr = flavoredCfg.get_CfgType(ref iidCfg, out ppCfg);
return hr;
}
public virtual int get_IsPrivate(out int pfPrivate) {
pfPrivate = 0;
return VSConstants.S_OK;
}
public virtual int get_OutputGroups(uint celt, IVsOutputGroup[] rgpcfg, uint[] pcActual) {
// Are they only asking for the number of groups?
if (celt == 0) {
if ((null == pcActual) || (0 == pcActual.Length)) {
throw new ArgumentNullException("pcActual");
}
pcActual[0] = (uint)OutputGroups.Count;
return VSConstants.S_OK;
}
// Check that the array of output groups is not null
if ((null == rgpcfg) || (rgpcfg.Length == 0)) {
throw new ArgumentNullException("rgpcfg");
}
// Fill the array with our output groups
uint count = 0;
foreach (OutputGroup group in OutputGroups) {
if (rgpcfg.Length > count && celt > count && group != null) {
rgpcfg[count] = group;
++count;
}
}
if (pcActual != null && pcActual.Length > 0)
pcActual[0] = count;
// If the number asked for does not match the number returned, return S_FALSE
return (count == celt) ? VSConstants.S_OK : VSConstants.S_FALSE;
}
public virtual int get_VirtualRoot(out string pbstrVRoot) {
pbstrVRoot = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsDebuggableProjectCfg methods
/// <summary>
/// Called by the vs shell to start debugging (managed or unmanaged).
/// Override this method to support other debug engines.
/// </summary>
/// <param name="grfLaunch">A flag that determines the conditions under which to start the debugger. For valid grfLaunch values, see __VSDBGLAUNCHFLAGS</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code</returns>
public abstract int DebugLaunch(uint grfLaunch);
/// <summary>
/// Determines whether the debugger can be launched, given the state of the launch flags.
/// </summary>
/// <param name="flags">Flags that determine the conditions under which to launch the debugger.
/// For valid grfLaunch values, see __VSDBGLAUNCHFLAGS or __VSDBGLAUNCHFLAGS2.</param>
/// <param name="fCanLaunch">true if the debugger can be launched, otherwise false</param>
/// <returns>S_OK if the method succeeds, otherwise an error code</returns>
public virtual int QueryDebugLaunch(uint flags, out int fCanLaunch) {
string assembly = this.project.GetAssemblyName(this.ConfigName);
fCanLaunch = (assembly != null && assembly.ToUpperInvariant().EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) ? 1 : 0;
if (fCanLaunch == 0) {
string property = GetConfigurationProperty("StartProgram", true);
fCanLaunch = (property != null && property.Length > 0) ? 1 : 0;
}
return VSConstants.S_OK;
}
#endregion
#region IVsCfgBrowseObject
/// <summary>
/// Maps back to the configuration corresponding to the browse object.
/// </summary>
/// <param name="cfg">The IVsCfg object represented by the browse object</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int GetCfg(out IVsCfg cfg) {
cfg = this;
return VSConstants.S_OK;
}
/// <summary>
/// Maps back to the hierarchy or project item object corresponding to the browse object.
/// </summary>
/// <param name="hier">Reference to the hierarchy object.</param>
/// <param name="itemid">Reference to the project item.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int GetProjectItem(out IVsHierarchy hier, out uint itemid) {
Utilities.CheckNotNull(this.project);
Utilities.CheckNotNull(this.project.NodeProperties);
return this.project.NodeProperties.GetProjectItem(out hier, out itemid);
}
#endregion
#region helper methods
private MSBuildExecution.ProjectInstance GetCurrentConfig(bool resetCache = false) {
if (resetCache || currentConfig == null) {
// Get properties for current configuration from project file and cache it
project.SetConfiguration(ConfigName);
project.BuildProject.ReevaluateIfNecessary();
// Create a snapshot of the evaluated project in its current state
currentConfig = project.BuildProject.CreateProjectInstance();
// Restore configuration
project.SetCurrentConfiguration();
}
return currentConfig;
}
private MSBuildExecution.ProjectPropertyInstance GetMsBuildProperty(string propertyName, bool resetCache) {
var current = GetCurrentConfig(resetCache);
if (current == null)
throw new Exception("Failed to retrieve properties");
// return property asked for
return current.GetProperty(propertyName);
}
/// <summary>
/// Retrieves the configuration dependent property pages.
/// </summary>
/// <param name="pages">The pages to return.</param>
private void GetCfgPropertyPages(CAUUID[] pages) {
// We do not check whether the supportsProjectDesigner is set to true on the ProjectNode.
// We rely that the caller knows what to call on us.
Utilities.ArgumentNotNull("pages", pages);
if (pages.Length == 0) {
throw new ArgumentException(SR.GetString(SR.InvalidParameter), "pages");
}
// Retrive the list of guids from hierarchy properties.
// Because a flavor could modify that list we must make sure we are calling the outer most implementation of IVsHierarchy
string guidsList = String.Empty;
IVsHierarchy hierarchy = project.GetOuterInterface<IVsHierarchy>();
object variant = null;
ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_CfgPropertyPagesCLSIDList, out variant), new int[] { VSConstants.DISP_E_MEMBERNOTFOUND, VSConstants.E_NOTIMPL });
guidsList = (string)variant;
Guid[] guids = Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(guidsList);
if (guids == null || guids.Length == 0) {
pages[0] = new CAUUID();
pages[0].cElems = 0;
} else {
pages[0] = PackageUtilities.CreateCAUUIDFromGuidArray(guids);
}
}
internal virtual bool IsInputGroup(string groupName) {
return groupName == "SourceFiles";
}
private static DateTime? TryGetLastWriteTimeUtc(string path, Redirector output = null) {
try {
return File.GetLastWriteTimeUtc(path);
} catch (UnauthorizedAccessException ex) {
if (output != null) {
output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message));
#if DEBUG
output.WriteErrorLine(ex.ToString());
#endif
}
} catch (ArgumentException ex) {
if (output != null) {
output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message));
#if DEBUG
output.WriteErrorLine(ex.ToString());
#endif
}
} catch (PathTooLongException ex) {
if (output != null) {
output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message));
#if DEBUG
output.WriteErrorLine(ex.ToString());
#endif
}
} catch (NotSupportedException ex) {
if (output != null) {
output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message));
#if DEBUG
output.WriteErrorLine(ex.ToString());
#endif
}
}
return null;
}
internal virtual bool IsUpToDate() {
var outputWindow = OutputWindowRedirector.GetGeneral(ProjectMgr.Site);
#if DEBUG
outputWindow.WriteLine(string.Format("Checking whether {0} needs to be rebuilt:", ProjectMgr.Caption));
#endif
var latestInput = DateTime.MinValue;
var earliestOutput = DateTime.MaxValue;
bool mustRebuild = false;
var allInputs = new HashSet<string>(OutputGroups
.Where(g => IsInputGroup(g.Name))
.SelectMany(x => x.EnumerateOutputs())
.Select(input => input.CanonicalName),
StringComparer.OrdinalIgnoreCase
);
foreach (var group in OutputGroups.Where(g => !IsInputGroup(g.Name))) {
foreach (var output in group.EnumerateOutputs()) {
var path = output.CanonicalName;
#if DEBUG
var dt = TryGetLastWriteTimeUtc(path);
outputWindow.WriteLine(string.Format(
" Out: {0}: {1} [{2}]",
group.Name,
path,
dt.HasValue ? dt.Value.ToString("s") : "err"
));
#endif
DateTime? modifiedTime;
if (!File.Exists(path) ||
!(modifiedTime = TryGetLastWriteTimeUtc(path, outputWindow)).HasValue) {
mustRebuild = true;
break;
}
string inputPath;
if (File.Exists(inputPath = output.GetMetadata("SourceFile"))) {
var inputModifiedTime = TryGetLastWriteTimeUtc(inputPath, outputWindow);
if (inputModifiedTime.HasValue && inputModifiedTime.Value > modifiedTime.Value) {
mustRebuild = true;
break;
} else {
continue;
}
}
// output is an input, ignore it...
if (allInputs.Contains(path)) {
continue;
}
if (modifiedTime.Value < earliestOutput) {
earliestOutput = modifiedTime.Value;
}
}
if (mustRebuild) {
// Early exit if we know we're going to have to rebuild
break;
}
}
if (mustRebuild) {
#if DEBUG
outputWindow.WriteLine(string.Format(
"Rebuilding {0} because mustRebuild is true",
ProjectMgr.Caption
));
#endif
return false;
}
foreach (var group in OutputGroups.Where(g => IsInputGroup(g.Name))) {
foreach (var input in group.EnumerateOutputs()) {
var path = input.CanonicalName;
#if DEBUG
var dt = TryGetLastWriteTimeUtc(path);
outputWindow.WriteLine(string.Format(
" In: {0}: {1} [{2}]",
group.Name,
path,
dt.HasValue ? dt.Value.ToString("s") : "err"
));
#endif
if (!File.Exists(path)) {
continue;
}
var modifiedTime = TryGetLastWriteTimeUtc(path, outputWindow);
if (modifiedTime.HasValue && modifiedTime.Value > latestInput) {
latestInput = modifiedTime.Value;
if (earliestOutput < latestInput) {
break;
}
}
}
if (earliestOutput < latestInput) {
// Early exit if we know we're going to have to rebuild
break;
}
}
if (earliestOutput < latestInput) {
#if DEBUG
outputWindow.WriteLine(string.Format(
"Rebuilding {0} because {1:s} < {2:s}",
ProjectMgr.Caption,
earliestOutput,
latestInput
));
#endif
return false;
} else {
#if DEBUG
outputWindow.WriteLine(string.Format(
"Not rebuilding {0} because {1:s} >= {2:s}",
ProjectMgr.Caption,
earliestOutput,
latestInput
));
#endif
return true;
}
}
#endregion
#region IVsProjectFlavorCfg Members
/// <summary>
/// This is called to let the flavored config let go
/// of any reference it may still be holding to the base config
/// </summary>
/// <returns></returns>
int IVsProjectFlavorCfg.Close() {
// This is used to release the reference the flavored config is holding
// on the base config, but in our scenario these 2 are the same object
// so we have nothing to do here.
return VSConstants.S_OK;
}
/// <summary>
/// Actual implementation of get_CfgType.
/// When not flavored or when the flavor delegate to use
/// we end up creating the requested config if we support it.
/// </summary>
/// <param name="iidCfg">IID representing the type of config object we should create</param>
/// <param name="ppCfg">Config object that the method created</param>
/// <returns>HRESULT</returns>
int IVsProjectFlavorCfg.get_CfgType(ref Guid iidCfg, out IntPtr ppCfg) {
ppCfg = IntPtr.Zero;
// See if this is an interface we support
if (iidCfg == typeof(IVsDebuggableProjectCfg).GUID) {
ppCfg = Marshal.GetComInterfaceForObject(this, typeof(IVsDebuggableProjectCfg));
} else if (iidCfg == typeof(IVsBuildableProjectCfg).GUID) {
IVsBuildableProjectCfg buildableConfig;
this.get_BuildableProjectCfg(out buildableConfig);
//
//In some cases we've intentionally shutdown the build options
// If buildableConfig is null then don't try to get the BuildableProjectCfg interface
//
if (null != buildableConfig) {
ppCfg = Marshal.GetComInterfaceForObject(buildableConfig, typeof(IVsBuildableProjectCfg));
}
}
// If not supported
if (ppCfg == IntPtr.Zero)
return VSConstants.E_NOINTERFACE;
return VSConstants.S_OK;
}
#endregion
}
[ComVisible(true)]
internal class BuildableProjectConfig : IVsBuildableProjectCfg {
#region fields
ProjectConfig config = null;
EventSinkCollection callbacks = new EventSinkCollection();
#endregion
#region ctors
public BuildableProjectConfig(ProjectConfig config) {
this.config = config;
}
#endregion
#region IVsBuildableProjectCfg methods
public virtual int AdviseBuildStatusCallback(IVsBuildStatusCallback callback, out uint cookie) {
cookie = callbacks.Add(callback);
return VSConstants.S_OK;
}
public virtual int get_ProjectCfg(out IVsProjectCfg p) {
p = config;
return VSConstants.S_OK;
}
public virtual int QueryStartBuild(uint options, int[] supported, int[] ready) {
if (supported != null && supported.Length > 0)
supported[0] = 1;
if (ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStartClean(uint options, int[] supported, int[] ready) {
if (supported != null && supported.Length > 0)
supported[0] = 1;
if (ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStartUpToDateCheck(uint options, int[] supported, int[] ready) {
if (supported != null && supported.Length > 0)
supported[0] = 1;
if (ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStatus(out int done) {
done = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int StartBuild(IVsOutputWindowPane pane, uint options) {
config.PrepareBuild(false);
// Current version of MSBuild wish to be called in an STA
uint flags = VSConstants.VS_BUILDABLEPROJECTCFGOPTS_REBUILD;
// If we are not asked for a rebuild, then we build the default target (by passing null)
this.Build(options, pane, ((options & flags) != 0) ? MsBuildTarget.Rebuild : null);
return VSConstants.S_OK;
}
public virtual int StartClean(IVsOutputWindowPane pane, uint options) {
config.PrepareBuild(true);
// Current version of MSBuild wish to be called in an STA
this.Build(options, pane, MsBuildTarget.Clean);
return VSConstants.S_OK;
}
public virtual int StartUpToDateCheck(IVsOutputWindowPane pane, uint options) {
return config.IsUpToDate() ?
VSConstants.S_OK :
VSConstants.E_FAIL;
}
public virtual int Stop(int fsync) {
return VSConstants.S_OK;
}
public virtual int UnadviseBuildStatusCallback(uint cookie) {
callbacks.RemoveAt(cookie);
return VSConstants.S_OK;
}
public virtual int Wait(uint ms, int fTickWhenMessageQNotEmpty) {
return VSConstants.E_NOTIMPL;
}
#endregion
#region helpers
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private bool NotifyBuildBegin() {
int shouldContinue = 1;
foreach (IVsBuildStatusCallback cb in callbacks) {
try {
ErrorHandler.ThrowOnFailure(cb.BuildBegin(ref shouldContinue));
if (shouldContinue == 0) {
return false;
}
} catch (Exception e) {
// If those who ask for status have bugs in their code it should not prevent the build/notification from happening
Debug.Fail(SR.GetString(SR.BuildEventError, e.Message));
}
}
return true;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void NotifyBuildEnd(MSBuildResult result, string buildTarget) {
int success = ((result == MSBuildResult.Successful) ? 1 : 0);
foreach (IVsBuildStatusCallback cb in callbacks) {
try {
ErrorHandler.ThrowOnFailure(cb.BuildEnd(success));
} catch (Exception e) {
// If those who ask for status have bugs in their code it should not prevent the build/notification from happening
Debug.Fail(SR.GetString(SR.BuildEventError, e.Message));
} finally {
// We want to refresh the references if we are building with the Build or Rebuild target or if the project was opened for browsing only.
bool shouldRepaintReferences = (buildTarget == null || buildTarget == MsBuildTarget.Build || buildTarget == MsBuildTarget.Rebuild);
// Now repaint references if that is needed.
// We hardly rely here on the fact the ResolveAssemblyReferences target has been run as part of the build.
// One scenario to think at is when an assembly reference is renamed on disk thus becomming unresolvable,
// but msbuild can actually resolve it.
// Another one if the project was opened only for browsing and now the user chooses to build or rebuild.
if (shouldRepaintReferences && (result == MSBuildResult.Successful)) {
this.RefreshReferences();
}
}
}
}
private void Build(uint options, IVsOutputWindowPane output, string target) {
if (!this.NotifyBuildBegin()) {
return;
}
try {
config.ProjectMgr.BuildAsync(options, this.config.ConfigName, output, target, (result, buildTarget) => this.NotifyBuildEnd(result, buildTarget));
} catch (Exception e) {
if (e.IsCriticalException()) {
throw;
}
Trace.WriteLine("Exception : " + e.Message);
ErrorHandler.ThrowOnFailure(output.OutputStringThreadSafe("Unhandled Exception:" + e.Message + "\n"));
this.NotifyBuildEnd(MSBuildResult.Failed, target);
throw;
} finally {
ErrorHandler.ThrowOnFailure(output.FlushToTaskList());
}
}
/// <summary>
/// Refreshes references and redraws them correctly.
/// </summary>
private void RefreshReferences() {
// Refresh the reference container node for assemblies that could be resolved.
IReferenceContainer referenceContainer = this.config.ProjectMgr.GetReferenceContainer();
if (referenceContainer != null) {
foreach (ReferenceNode referenceNode in referenceContainer.EnumReferences()) {
referenceNode.RefreshReference();
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using Microsoft.Extensions.Primitives;
namespace Microsoft.Net.Http.Headers
{
internal static class CookieHeaderParserShared
{
public static bool TryParseValues(StringValues values, IDictionary<string, string> store, bool enableCookieNameEncoding, bool supportsMultipleValues)
{
// If a parser returns an empty list, it means there was no value, but that's valid (e.g. "Accept: "). The caller
// can ignore the value.
if (values.Count == 0)
{
return false;
}
var hasFoundValue = false;
for (var i = 0; i < values.Count; i++)
{
var value = values[i];
var index = 0;
while (!string.IsNullOrEmpty(value) && index < value.Length)
{
if (TryParseValue(value, ref index, supportsMultipleValues, out var parsedName, out var parsedValue))
{
// The entry may not contain an actual value, like " , "
var name = enableCookieNameEncoding ? Uri.UnescapeDataString(parsedName.Value.Value!) : parsedName.Value.Value!;
store[name] = Uri.UnescapeDataString(parsedValue.Value.Value!);
hasFoundValue = true;
}
else
{
// Skip the invalid values and keep trying.
index++;
}
}
}
return hasFoundValue;
}
public static bool TryParseValue(StringSegment value, ref int index, bool supportsMultipleValues, [NotNullWhen(true)] out StringSegment? parsedName, [NotNullWhen(true)] out StringSegment? parsedValue)
{
parsedName = null;
parsedValue = null;
// If multiple values are supported (i.e. list of values), then accept an empty string: The header may
// be added multiple times to the request/response message. E.g.
// Accept: text/xml; q=1
// Accept:
// Accept: text/plain; q=0.2
if (StringSegment.IsNullOrEmpty(value) || (index == value.Length))
{
return supportsMultipleValues;
}
var current = GetNextNonEmptyOrWhitespaceIndex(value, index, supportsMultipleValues, out var separatorFound);
if (separatorFound && !supportsMultipleValues)
{
return false; // leading separators not allowed if we don't support multiple values.
}
if (current == value.Length)
{
if (supportsMultipleValues)
{
index = current;
}
return supportsMultipleValues;
}
if (!TryGetCookieLength(value, ref current, out parsedName, out parsedValue))
{
return false;
}
current = GetNextNonEmptyOrWhitespaceIndex(value, current, supportsMultipleValues, out separatorFound);
// If we support multiple values and we've not reached the end of the string, then we must have a separator.
if ((separatorFound && !supportsMultipleValues) || (!separatorFound && (current < value.Length)))
{
return false;
}
index = current;
return true;
}
private static int GetNextNonEmptyOrWhitespaceIndex(StringSegment input, int startIndex, bool skipEmptyValues, out bool separatorFound)
{
Contract.Requires(startIndex <= input.Length); // it's OK if index == value.Length.
separatorFound = false;
var current = startIndex + HttpRuleParser.GetWhitespaceLength(input, startIndex);
if ((current == input.Length) || (input[current] != ',' && input[current] != ';'))
{
return current;
}
// If we have a separator, skip the separator and all following whitespaces. If we support
// empty values, continue until the current character is neither a separator nor a whitespace.
separatorFound = true;
current++; // skip delimiter.
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
if (skipEmptyValues)
{
// Most headers only split on ',', but cookies primarily split on ';'
while ((current < input.Length) && ((input[current] == ',') || (input[current] == ';')))
{
current++; // skip delimiter.
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
}
}
return current;
}
// name=value; name="value"
internal static bool TryGetCookieLength(StringSegment input, ref int offset, [NotNullWhen(true)] out StringSegment? parsedName, [NotNullWhen(true)] out StringSegment? parsedValue)
{
Contract.Requires(offset >= 0);
parsedName = null;
parsedValue = null;
if (StringSegment.IsNullOrEmpty(input) || (offset >= input.Length))
{
return false;
}
// The caller should have already consumed any leading whitespace, commas, etc..
// Name=value;
// Name
var itemLength = HttpRuleParser.GetTokenLength(input, offset);
if (itemLength == 0)
{
return false;
}
parsedName = input.Subsegment(offset, itemLength);
offset += itemLength;
// = (no spaces)
if (!ReadEqualsSign(input, ref offset))
{
return false;
}
// value or "quoted value"
// The value may be empty
parsedValue = GetCookieValue(input, ref offset);
return true;
}
// cookie-value = *cookie-octet / ( DQUOTE* cookie-octet DQUOTE )
// cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
// ; US-ASCII characters excluding CTLs, whitespace DQUOTE, comma, semicolon, and backslash
internal static StringSegment GetCookieValue(StringSegment input, ref int offset)
{
Contract.Requires(offset >= 0);
Contract.Ensures((Contract.Result<int>() >= 0) && (Contract.Result<int>() <= (input.Length - offset)));
var startIndex = offset;
if (offset >= input.Length)
{
return StringSegment.Empty;
}
var inQuotes = false;
if (input[offset] == '"')
{
inQuotes = true;
offset++;
}
while (offset < input.Length)
{
var c = input[offset];
if (!IsCookieValueChar(c))
{
break;
}
offset++;
}
if (inQuotes)
{
if (offset == input.Length || input[offset] != '"')
{
// Missing final quote
return StringSegment.Empty;
}
offset++;
}
var length = offset - startIndex;
if (offset > startIndex)
{
return input.Subsegment(startIndex, length);
}
return StringSegment.Empty;
}
private static bool ReadEqualsSign(StringSegment input, ref int offset)
{
// = (no spaces)
if (offset >= input.Length || input[offset] != '=')
{
return false;
}
offset++;
return true;
}
// cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
// ; US-ASCII characters excluding CTLs, whitespace DQUOTE, comma, semicolon, and backslash
private static bool IsCookieValueChar(char c)
{
if (c < 0x21 || c > 0x7E)
{
return false;
}
return !(c == '"' || c == ',' || c == ';' || c == '\\');
}
}
}
| |
//
// SignatureDescriptionTest.cs - NUnit Test Cases for SignatureDescription
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2002 Motus Technologies Inc. (http://www.motus.com)
// (C) 2004 Novell http://www.novell.com
//
using NUnit.Framework;
using System;
using System.Security;
using System.Security.Cryptography;
namespace MonoTests.System.Security.Cryptography {
[TestFixture]
public class SignatureDescriptionTest : Assertion {
protected SignatureDescription sig;
protected static DSA dsa;
protected static RSA rsa;
[SetUp]
public void SetUp ()
{
sig = new SignatureDescription();
// key generation is VERY long so one time is enough
if (dsa == null)
dsa = DSA.Create ();
if (rsa == null)
rsa = RSA.Create ();
}
public void AssertEquals (string msg, byte[] array1, byte[] array2)
{
AllTests.AssertEquals (msg, array1, array2);
}
[Test]
public void Constructor_Default ()
{
// empty constructor
SignatureDescription sig = new SignatureDescription ();
AssertNotNull ("SignatureDescription()", sig);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Constructor_Null ()
{
// null constructor
SignatureDescription sig = new SignatureDescription (null);
// LAMESPEC: Documented as CryptographicException
}
[Test]
public void Constructor_SecurityElement_Empty ()
{
// (empty) SecurityElement constructor
SecurityElement se = new SecurityElement ("xml");
SignatureDescription sig = new SignatureDescription (se);
AssertNotNull ("SignatureDescription(SecurityElement)", sig);
}
[Test]
public void Constructor_SecurityElement_DSA ()
{
SecurityElement se = new SecurityElement ("DSASignature");
se.AddChild (new SecurityElement ("Key", "System.Security.Cryptography.DSACryptoServiceProvider"));
se.AddChild (new SecurityElement ("Digest", "System.Security.Cryptography.SHA1CryptoServiceProvider"));
se.AddChild (new SecurityElement ("Formatter", "System.Security.Cryptography.DSASignatureFormatter"));
se.AddChild (new SecurityElement ("Deformatter", "System.Security.Cryptography.DSASignatureDeformatter"));
SignatureDescription sig = new SignatureDescription (se);
AssertNotNull ("SignatureDescription(SecurityElement)", sig);
AssertEquals ("Key", "System.Security.Cryptography.DSACryptoServiceProvider", sig.KeyAlgorithm);
AssertEquals ("Digest", "System.Security.Cryptography.SHA1CryptoServiceProvider", sig.DigestAlgorithm);
AssertEquals ("Formatter", "System.Security.Cryptography.DSASignatureFormatter", sig.FormatterAlgorithm);
AssertEquals ("Deformatter", "System.Security.Cryptography.DSASignatureDeformatter", sig.DeformatterAlgorithm);
}
[Test]
public void Constructor_SecurityElement_RSA ()
{
SecurityElement se = new SecurityElement ("RSASignature");
se.AddChild (new SecurityElement ("Key", "System.Security.Cryptography.RSACryptoServiceProvider"));
se.AddChild (new SecurityElement ("Digest", "System.Security.Cryptography.SHA1CryptoServiceProvider"));
se.AddChild (new SecurityElement ("Formatter", "System.Security.Cryptography.RSAPKCS1SignatureFormatter"));
se.AddChild (new SecurityElement ("Deformatter", "System.Security.Cryptography.RSAPKCS1SignatureDeformatter"));
SignatureDescription sig = new SignatureDescription (se);
AssertNotNull ("SignatureDescription(SecurityElement)", sig);
AssertEquals ("Key", "System.Security.Cryptography.RSACryptoServiceProvider", sig.KeyAlgorithm);
AssertEquals ("Digest", "System.Security.Cryptography.SHA1CryptoServiceProvider", sig.DigestAlgorithm);
AssertEquals ("Formatter", "System.Security.Cryptography.RSAPKCS1SignatureFormatter", sig.FormatterAlgorithm);
AssertEquals ("Deformatter", "System.Security.Cryptography.RSAPKCS1SignatureDeformatter", sig.DeformatterAlgorithm);
}
[Test]
public void Properties ()
{
string invalid = "invalid";
AssertNull ("DeformatterAlgorithm 1", sig.DeformatterAlgorithm);
sig.DeformatterAlgorithm = invalid;
AssertNotNull ("DeformatterAlgorithm 2", sig.DeformatterAlgorithm);
AssertEquals ("DeformatterAlgorithm 3", invalid, sig.DeformatterAlgorithm);
sig.DeformatterAlgorithm = null;
AssertNull ("DeformatterAlgorithm 4", sig.DeformatterAlgorithm);
AssertNull ("DigestAlgorithm 1", sig.DigestAlgorithm);
sig.DigestAlgorithm = invalid;
AssertNotNull ("DigestAlgorithm 2", sig.DigestAlgorithm);
AssertEquals ("DigestAlgorithm 3", invalid, sig.DigestAlgorithm);
sig.DigestAlgorithm = null;
AssertNull ("DigestAlgorithm 4", sig.DigestAlgorithm);
AssertNull ("FormatterAlgorithm 1", sig.FormatterAlgorithm);
sig.FormatterAlgorithm = invalid;
AssertNotNull ("FormatterAlgorithm 2", sig.FormatterAlgorithm);
AssertEquals ("FormatterAlgorithm 3", invalid, sig.FormatterAlgorithm);
sig.FormatterAlgorithm = null;
AssertNull ("FormatterAlgorithm 4", sig.FormatterAlgorithm);
AssertNull ("KeyAlgorithm 1", sig.KeyAlgorithm);
sig.KeyAlgorithm = invalid;
AssertNotNull ("KeyAlgorithm 2", sig.KeyAlgorithm);
AssertEquals ("KeyAlgorithm 3", invalid, sig.KeyAlgorithm);
sig.KeyAlgorithm = null;
AssertNull ("KeyAlgorithm 4", sig.KeyAlgorithm);
}
[Test]
public void Deformatter ()
{
AsymmetricSignatureDeformatter def = null;
// Deformatter with all properties null
try {
def = sig.CreateDeformatter (dsa);
Fail ("Expected ArgumentNullException but got none");
}
catch (ArgumentNullException) {
// this is what we expect
}
catch (Exception e) {
Fail ("Expected ArgumentNullException but got: " + e.ToString ());
}
// Deformatter with invalid DeformatterAlgorithm property
sig.DeformatterAlgorithm = "DSA";
try {
def = sig.CreateDeformatter (dsa);
Fail ("Expected InvalidCastException but got none");
}
catch (InvalidCastException) {
// this is what we expect
}
catch (Exception e) {
Fail ("Expected InvalidCastException but got: " + e.ToString ());
}
// Deformatter with valid DeformatterAlgorithm property
sig.DeformatterAlgorithm = "DSASignatureDeformatter";
try {
def = sig.CreateDeformatter (dsa);
Fail ("Expected NullReferenceException but got none");
}
catch (NullReferenceException) {
// this is what we expect
}
catch (Exception e) {
Fail ("Expected NullReferenceException but got: " + e.ToString ());
}
// Deformatter with valid DeformatterAlgorithm property
sig.KeyAlgorithm = "DSA";
sig.DigestAlgorithm = "SHA1";
sig.DeformatterAlgorithm = "DSASignatureDeformatter";
try {
def = sig.CreateDeformatter (dsa);
Fail ("Expected NullReferenceException but got none");
}
catch (NullReferenceException) {
// this is what we expect
}
catch (Exception e) {
Fail ("Expected NullReferenceException but got: " + e.ToString ());
}
}
[Test]
public void Digest ()
{
bool rightClass = false;
HashAlgorithm hash = null;
// null hash
try {
hash = sig.CreateDigest ();
Fail ("Expected ArgumentNullException but got none");
}
catch (ArgumentNullException) {
// this is what we expect
}
catch (Exception e) {
Fail ("Expected ArgumentNullException but got: " + e.ToString ());
}
sig.DigestAlgorithm = "SHA1";
hash = sig.CreateDigest ();
AssertNotNull ("CreateDigest(SHA1)", hash);
rightClass = (hash.ToString ().IndexOf (sig.DigestAlgorithm) > 0);
Assert ("CreateDigest(SHA1)", rightClass);
sig.DigestAlgorithm = "MD5";
hash = sig.CreateDigest ();
AssertNotNull ("CreateDigest(MD5)", hash);
rightClass = (hash.ToString ().IndexOf (sig.DigestAlgorithm) > 0);
Assert ("CreateDigest(MD5)", rightClass);
sig.DigestAlgorithm = "SHA256";
hash = sig.CreateDigest ();
AssertNotNull ("CreateDigest(SHA256)", hash);
rightClass = (hash.ToString ().IndexOf (sig.DigestAlgorithm) > 0);
Assert ("CreateDigest(SHA256)", rightClass);
sig.DigestAlgorithm = "SHA384";
hash = sig.CreateDigest ();
AssertNotNull ("CreateDigest(SHA384)", hash);
rightClass = (hash.ToString ().IndexOf (sig.DigestAlgorithm) > 0);
Assert ("CreateDigest(SHA384)", rightClass);
sig.DigestAlgorithm = "SHA512";
hash = sig.CreateDigest ();
AssertNotNull ("CreateDigest(SHA512)", hash);
rightClass = (hash.ToString ().IndexOf (sig.DigestAlgorithm) > 0);
Assert ("CreateDigest(SHA512)", rightClass);
sig.DigestAlgorithm = "bad";
hash = sig.CreateDigest ();
AssertNull ("CreateDigest(bad)", hash);
}
[Test]
public void Formatter ()
{
AsymmetricSignatureFormatter fmt = null;
// Formatter with all properties null
try {
fmt = sig.CreateFormatter (dsa);
Fail ("Expected ArgumentNullException but got none");
}
catch (ArgumentNullException) {
// this is what we expect
}
catch (Exception e) {
Fail ("Expected ArgumentNullException but got: " + e.ToString ());
}
// Formatter with invalid FormatterAlgorithm property
sig.FormatterAlgorithm = "DSA";
try {
fmt = sig.CreateFormatter (dsa);
Fail ("Expected InvalidCastException but got none");
}
catch (InvalidCastException) {
// this is what we expect
}
catch (Exception e) {
Fail ("Expected InvalidCastException but got: " + e.ToString ());
}
// Formatter with valid FormatterAlgorithm property
sig.FormatterAlgorithm = "DSASignatureFormatter";
try {
fmt = sig.CreateFormatter (dsa);
Fail ("Expected NullReferenceException but got none");
}
catch (NullReferenceException) {
// this is what we expect
}
catch (Exception e) {
Fail ("Expected NullReferenceException but got: " + e.ToString ());
}
// Deformatter with valid DeformatterAlgorithm property
sig.KeyAlgorithm = "DSA";
sig.DigestAlgorithm = "SHA1";
sig.FormatterAlgorithm = "DSASignatureFormatter";
try {
fmt = sig.CreateFormatter (dsa);
Fail ("Expected NullReferenceException but got none");
}
catch (NullReferenceException) {
// this is what we expect
}
catch (Exception e) {
Fail ("Expected NullReferenceException but got: " + e.ToString ());
}
}
[Test]
public void DSASignatureDescription ()
{
// internal class - we cannot create one without CryptoConfig
SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName ("http://www.w3.org/2000/09/xmldsig#dsa-sha1");
AssertEquals ("DSA.DigestAlgorithm", "System.Security.Cryptography.SHA1CryptoServiceProvider", sd.DigestAlgorithm);
AssertEquals ("DSA.DeformatterAlgorithm", "System.Security.Cryptography.DSASignatureDeformatter", sd.DeformatterAlgorithm);
AssertEquals ("DSA.FormatterAlgorithm", "System.Security.Cryptography.DSASignatureFormatter", sd.FormatterAlgorithm);
AssertEquals ("DSA.KeyAlgorithm", "System.Security.Cryptography.DSACryptoServiceProvider", sd.KeyAlgorithm);
HashAlgorithm hash = sd.CreateDigest();
AssertEquals ("DSA.CreateDigest", "System.Security.Cryptography.SHA1CryptoServiceProvider", hash.ToString ());
AssertEquals ("DSA.Create", dsa.ToString (), sd.KeyAlgorithm);
AsymmetricSignatureDeformatter asd = sd.CreateDeformatter (dsa);
AssertEquals ("DSA.CreateDeformatter", "System.Security.Cryptography.DSASignatureDeformatter", asd.ToString ());
AsymmetricSignatureFormatter asf = sd.CreateFormatter (dsa);
AssertEquals ("DSA.CreateFormatter", "System.Security.Cryptography.DSASignatureFormatter", asf.ToString ());
}
[Test]
public void RSASignatureDescription ()
{
// internal class - we cannot create one without CryptoConfig
SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName ("http://www.w3.org/2000/09/xmldsig#rsa-sha1");
AssertEquals ("RSA.DigestAlgorithm", "System.Security.Cryptography.SHA1CryptoServiceProvider", sd.DigestAlgorithm);
AssertEquals ("RSA.DeformatterAlgorithm", "System.Security.Cryptography.RSAPKCS1SignatureDeformatter", sd.DeformatterAlgorithm);
AssertEquals ("RSA.FormatterAlgorithm", "System.Security.Cryptography.RSAPKCS1SignatureFormatter", sd.FormatterAlgorithm);
AssertEquals ("RSA.KeyAlgorithm", "System.Security.Cryptography.RSACryptoServiceProvider", sd.KeyAlgorithm);
HashAlgorithm hash = sd.CreateDigest();
AssertEquals ("RSA.CreateDigest", "System.Security.Cryptography.SHA1CryptoServiceProvider", hash.ToString ());
AssertEquals ("RSA.Create", rsa.ToString (), sd.KeyAlgorithm);
AsymmetricSignatureDeformatter asd = sd.CreateDeformatter (rsa);
AssertEquals ("RSA.CreateDeformatter", "System.Security.Cryptography.RSAPKCS1SignatureDeformatter", asd.ToString ());
AsymmetricSignatureFormatter asf = sd.CreateFormatter (rsa);
AssertEquals ("RSA.CreateFormatter", "System.Security.Cryptography.RSAPKCS1SignatureFormatter", asf.ToString ());
}
}
}
| |
// Copyright 2019 Esri
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ArcGIS.Desktop.Framework.Contracts;
using System.ComponentModel;
namespace ScribbleControl_ArcGISPro
{
/// <summary>
/// Interaction logic for Scribble_ControlView.xaml
/// </summary>
public partial class Scribble_ControlView : UserControl , INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
private IList<double> _sizeOptions = new List<double>(){
5, 10, 20, 30, 40, 50
};
public IList<double> ScribbleControlSizeOptions
{
get
{
return _sizeOptions;
}
}
private Brush _shapeColor = Brushes.Tomato;
public Brush ShapeColor
{
get
{
return _shapeColor;
}
set
{
_shapeColor = value;
OnPropertyChanged("ShapeColor");
}
}
public Scribble_ControlView()
{
InitializeComponent();
}
private void ClrPcker_SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color?> e)
{
if (this.cvs != null)
{
this.cvs.DefaultDrawingAttributes.Color = (System.Windows.Media.Color)this.ClrPcker_ScribbleControl.SelectedColor;
ShapeColor = new SolidColorBrush(this.cvs.DefaultDrawingAttributes.Color);
}
}
private void Size_Combo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (this.cvs != null)
{
this.cvs.DefaultDrawingAttributes.Width = System.Convert.ToDouble(this.Size_Combo.SelectedItem.ToString());
this.cvs.DefaultDrawingAttributes.Height = System.Convert.ToDouble(this.Size_Combo.SelectedItem.ToString());
}
}
private void RadioButtonClicked(object sender, RoutedEventArgs e)
{
if (this.cvs != null)
{
if (inkRadioBtn.IsChecked == true)
{
this.cvs.EditingMode = InkCanvasEditingMode.Ink;
}
else if (eraseRadioBtn.IsChecked == true)
{
this.cvs.EditingMode = InkCanvasEditingMode.EraseByStroke;
}
else if (selectRadioBtn.IsChecked == true)
{
this.cvs.EditingMode = InkCanvasEditingMode.Select;
}
}
}
private void cvs_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
Shape shapeToAdd = null;
Brush b = new SolidColorBrush(this.cvs.DefaultDrawingAttributes.Color);
if (this.cvs != null)
{
if (rectShape.IsChecked == true)
{
shapeToAdd = new Rectangle() { Fill = b, Height = 100, Width = 100, RadiusX = 0, RadiusY = 0 };
}
else if(circleShape.IsChecked == true)
{
shapeToAdd = new Ellipse() { Fill = b, Height = 100, Width = 100 } ;
}
else if (lineShape.IsChecked == true)
{
shapeToAdd = new Line() { Height = 24, Width = 210,
StrokeThickness = 20, Stroke = b,
X1 = 5, X2 = 200, Y1 = 5, Y2 = 5,
StrokeStartLineCap = PenLineCap.Round, StrokeEndLineCap = PenLineCap.Round };
}
}
if (rectShape.IsChecked == true || circleShape.IsChecked == true)
{
InkCanvas.SetLeft(shapeToAdd, e.GetPosition(this.cvs).X - 50);
InkCanvas.SetTop(shapeToAdd, e.GetPosition(this.cvs).Y - 50);
}
else
{
InkCanvas.SetLeft(shapeToAdd, e.GetPosition(this.cvs).X);
InkCanvas.SetTop(shapeToAdd, e.GetPosition(this.cvs).Y - 12);
}
this.cvs.Children.Add(shapeToAdd);
}
private void Clear_Canvas_Click(object sender, RoutedEventArgs e)
{
this.cvs.Strokes.Clear();
int numElements = this.cvs.Children.Count;
List<UIElement> uiElements = new List<UIElement>();
for (int i = 0; i < numElements; i++)
{
uiElements.Add(this.cvs.Children[i]);
}
for (int i = 0; i < numElements; i++)
{
this.cvs.Children.Remove(uiElements[i]);
}
}
private void Select_All_Click(object sender, RoutedEventArgs e)
{
int numElements = this.cvs.Children.Count;
List<UIElement> uiElements = new List<UIElement>();
for (int i = 0; i < numElements; i++)
{
uiElements.Add(this.cvs.Children[i]);
}
this.cvs.Select(this.cvs.Strokes, uiElements);
selectRadioBtn.IsChecked = true;
}
private void Copy_Selected_Click(object sender, RoutedEventArgs e)
{
this.cvs.CopySelection();
}
private void Cut_Selected_Click(object sender, RoutedEventArgs e)
{
this.cvs.CutSelection();
}
private void Paste_toCanvas_Click(object sender, RoutedEventArgs e)
{
selectRadioBtn.IsChecked = true;
this.cvs.Paste();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A matrix of type T with 2 columns and 2 rows.
/// </summary>
[Serializable]
[DataContract(Namespace = "mat")]
[StructLayout(LayoutKind.Sequential)]
public struct gmat2<T> : IReadOnlyList<T>, IEquatable<gmat2<T>>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
[DataMember]
public T m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
[DataMember]
public T m01;
/// <summary>
/// Column 1, Rows 0
/// </summary>
[DataMember]
public T m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
[DataMember]
public T m11;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public gmat2(T m00, T m01, T m10, T m11)
{
this.m00 = m00;
this.m01 = m01;
this.m10 = m10;
this.m11 = m11;
}
/// <summary>
/// Constructs this matrix from a gmat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gmat2<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a gmat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gmat3x2<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a gmat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gmat4x2<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a gmat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gmat2x3<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a gmat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gmat3<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a gmat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gmat4x3<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a gmat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gmat2x4<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a gmat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gmat3x4<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a gmat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gmat4<T> m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public gmat2(gvec2<T> c0, gvec2<T> c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m10 = c1.x;
this.m11 = c1.y;
}
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public T[,] Values => new[,] { { m00, m01 }, { m10, m11 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public T[] Values1D => new[] { m00, m01, m10, m11 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public gvec2<T> Column0
{
get
{
return new gvec2<T>(m00, m01);
}
set
{
m00 = value.x;
m01 = value.y;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public gvec2<T> Column1
{
get
{
return new gvec2<T>(m10, m11);
}
set
{
m10 = value.x;
m11 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public gvec2<T> Row0
{
get
{
return new gvec2<T>(m00, m10);
}
set
{
m00 = value.x;
m10 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public gvec2<T> Row1
{
get
{
return new gvec2<T>(m01, m11);
}
set
{
m01 = value.x;
m11 = value.y;
}
}
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static gmat2<T> Zero { get; } = new gmat2<T>(default(T), default(T), default(T), default(T));
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<T> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m10;
yield return m11;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (2 x 2 = 4).
/// </summary>
public int Count => 4;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public T this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m10;
case 3: return m11;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m10 = value; break;
case 3: this.m11 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public T this[int col, int row]
{
get
{
return this[col * 2 + row];
}
set
{
this[col * 2 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(gmat2<T> rhs) => ((EqualityComparer<T>.Default.Equals(m00, rhs.m00) && EqualityComparer<T>.Default.Equals(m01, rhs.m01)) && (EqualityComparer<T>.Default.Equals(m10, rhs.m10) && EqualityComparer<T>.Default.Equals(m11, rhs.m11)));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is gmat2<T> && Equals((gmat2<T>) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(gmat2<T> lhs, gmat2<T> rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(gmat2<T> lhs, gmat2<T> rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((EqualityComparer<T>.Default.GetHashCode(m00)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m01)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m10)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m11);
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public gmat2<T> Transposed => new gmat2<T>(m00, m10, m01, m11);
}
}
| |
/*
* 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 ParquetColumnTests.Column.Values.Delta
{
using System;
using ParquetSharp.Bytes;
using ParquetSharp.Column.Values;
using ParquetSharp.Column.Values.Delta;
using ParquetSharp.External;
using ParquetSharp.IO;
using Xunit;
public class DeltaBinaryPackingValuesWriterTest
{
DeltaBinaryPackingValuesReader reader;
private int blockSize;
private int miniBlockNum;
private ValuesWriter writer;
private Random random;
public DeltaBinaryPackingValuesWriterTest()
{
blockSize = 128;
miniBlockNum = 4;
writer = new DeltaBinaryPackingValuesWriter(blockSize, miniBlockNum, 100, 200, new DirectByteBufferAllocator());
random = new Random();
}
[Fact]
public void miniBlockSizeShouldBeMultipleOf8()
{
Assert.Throws<ArgumentException>(() =>
new DeltaBinaryPackingValuesWriter(1281, 4, 100, 100, new DirectByteBufferAllocator()));
}
/* When data size is multiple of Block*/
[Fact]
public void shouldWriteWhenDataIsAlignedWithBlock()
{
int[] data = new int[5 * blockSize];
for (int i = 0; i < blockSize * 5; i++)
{
data[i] = random.Next();
}
shouldWriteAndRead(data);
}
[Fact]
public void shouldWriteAndReadWhenBlockIsNotFullyWritten()
{
int[] data = new int[blockSize - 3];
for (int i = 0; i < data.Length; i++)
{
data[i] = random.Next();
}
shouldWriteAndRead(data);
}
[Fact]
public void shouldWriteAndReadWhenAMiniBlockIsNotFullyWritten()
{
int miniBlockSize = blockSize / miniBlockNum;
int[] data = new int[miniBlockSize - 3];
for (int i = 0; i < data.Length; i++)
{
data[i] = random.Next();
}
shouldWriteAndRead(data);
}
[Fact]
public void shouldWriteNegativeDeltas()
{
int[] data = new int[blockSize];
for (int i = 0; i < data.Length; i++)
{
data[i] = 10 - (i * 32 - random.Next(6));
}
shouldWriteAndRead(data);
}
[Fact]
public void shouldWriteAndReadWhenDeltasAreSame()
{
int[] data = new int[2 * blockSize];
for (int i = 0; i < blockSize; i++)
{
data[i] = i * 32;
}
shouldWriteAndRead(data);
}
[Fact]
public void shouldWriteAndReadWhenValuesAreSame()
{
int[] data = new int[2 * blockSize];
for (int i = 0; i < blockSize; i++)
{
data[i] = 3;
}
shouldWriteAndRead(data);
}
[Fact]
public void shouldWriteWhenDeltaIs0ForEachBlock()
{
int[] data = new int[5 * blockSize + 1];
for (int i = 0; i < data.Length; i++)
{
data[i] = (i - 1) / blockSize;
}
shouldWriteAndRead(data);
}
[Fact]
public void shouldReadWriteWhenDataIsNotAlignedWithBlock()
{
int[] data = new int[5 * blockSize + 3];
for (int i = 0; i < data.Length; i++)
{
data[i] = random.Next(20) - 10;
}
shouldWriteAndRead(data);
}
[Fact]
public void shouldReadMaxMinValue()
{
int[] data = new int[10];
for (int i = 0; i < data.Length; i++)
{
if (i % 2 == 0)
{
data[i] = int.MinValue;
}
else {
data[i] = int.MaxValue;
}
}
shouldWriteAndRead(data);
}
[Fact]
public void shouldReturnCorrectOffsetAfterInitialization()
{
int[] data = new int[2 * blockSize + 3];
for (int i = 0; i < data.Length; i++)
{
data[i] = i * 32;
}
writeData(data);
reader = new DeltaBinaryPackingValuesReader();
BytesInput bytes = writer.getBytes();
byte[] valueContent = bytes.toByteArray();
byte[] pageContent = new byte[valueContent.Length * 10];
int contentOffsetInPage = 33;
Array.Copy(valueContent, 0, pageContent, contentOffsetInPage, valueContent.Length);
//offset should be correct
reader.initFromPage(100, ByteBuffer.wrap(pageContent), contentOffsetInPage);
int offset = reader.getNextOffset();
Assert.Equal(valueContent.Length + contentOffsetInPage, offset);
//should be able to read data correclty
foreach (int i in data)
{
Assert.Equal(i, reader.readInteger());
}
}
[Fact]
public void shouldThrowExceptionWhenReadMoreThanWritten()
{
int[] data = new int[5 * blockSize + 1];
for (int i = 0; i < data.Length; i++)
{
data[i] = i * 32;
}
shouldWriteAndRead(data);
try
{
reader.readInteger();
}
catch (ParquetDecodingException e)
{
Assert.Equal("no more value to read, total value count is " + data.Length, e.Message);
}
}
[Fact]
public void shouldSkip()
{
int[] data = new int[5 * blockSize + 1];
for (int i = 0; i < data.Length; i++)
{
data[i] = i * 32;
}
writeData(data);
reader = new DeltaBinaryPackingValuesReader();
reader.initFromPage(100, writer.getBytes().toByteBuffer(), 0);
for (int i = 0; i < data.Length; i++)
{
if (i % 3 == 0)
{
reader.skip();
}
else {
Assert.Equal(i * 32, reader.readInteger());
}
}
}
[Fact]
public void shouldReset()
{
shouldReadWriteWhenDataIsNotAlignedWithBlock();
int[] data = new int[5 * blockSize];
for (int i = 0; i < blockSize * 5; i++)
{
data[i] = i * 2;
}
writer.reset();
shouldWriteAndRead(data);
}
[Fact]
public void randomDataTest()
{
int maxSize = 1000;
int[] data = new int[maxSize];
for (int round = 0; round < 100000; round++)
{
int size = random.Next(maxSize);
for (int i = 0; i < size; i++)
{
data[i] = random.Next();
}
shouldReadAndWrite(data, size);
writer.reset();
}
}
private void shouldWriteAndRead(int[] data)
{
shouldReadAndWrite(data, data.Length);
}
private void shouldReadAndWrite(int[] data, int length)
{
writeData(data, length);
reader = new DeltaBinaryPackingValuesReader();
byte[] page = writer.getBytes().toByteArray();
int miniBlockSize = blockSize / miniBlockNum;
double miniBlockFlushed = Math.Ceiling(((double)length - 1) / miniBlockSize);
double blockFlushed = Math.Ceiling(((double)length - 1) / blockSize);
double estimatedSize = 4 * 5 //blockHeader
+ 4 * miniBlockFlushed * miniBlockSize //data(aligned to miniBlock)
+ blockFlushed * miniBlockNum //bitWidth of mini blocks
+ (5.0 * blockFlushed);//min delta for each block
Assert.True(estimatedSize >= page.Length);
reader.initFromPage(100, ByteBuffer.wrap(page), 0);
for (int i = 0; i < length; i++)
{
Assert.Equal(data[i], reader.readInteger());
}
}
private void writeData(int[] data)
{
writeData(data, data.Length);
}
private void writeData(int[] data, int length)
{
for (int i = 0; i < length; i++)
{
writer.writeInteger(data[i]);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.SignatureHelp;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class InvocationExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
public InvocationExpressionSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture)
{
}
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new InvocationExpressionSignatureHelpProvider();
}
#region "Regular tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationAfterCloseParen()
{
var markup = @"
class C
{
int Foo(int x)
{
[|Foo(Foo(x)$$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int C.Foo(int x)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationInsideLambda()
{
var markup = @"
using System;
class C
{
void Foo(Action<int> f)
{
[|Foo(i => Console.WriteLine(i)$$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(Action<int> f)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationInsideLambda2()
{
var markup = @"
using System;
class C
{
void Foo(Action<int> f)
{
[|Foo(i => Con$$sole.WriteLine(i)|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(Action<int> f)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutParameters()
{
var markup = @"
class C
{
void Foo()
{
[|Foo($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutParametersMethodXmlComments()
{
var markup = @"
class C
{
/// <summary>
/// Summary for foo
/// </summary>
void Foo()
{
[|Foo($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", "Summary for foo", null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn1()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo($$a, b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlCommentsOn1()
{
var markup = @"
class C
{
/// <summary>
/// Summary for Foo
/// </summary>
/// <param name=" + "\"a\">Param a</param>" + @"
/// <param name=" + "\"b\">Param b</param>" + @"
void Foo(int a, int b)
{
[|Foo($$a, b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", "Summary for Foo", "Param a", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn2()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(a, $$b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlComentsOn2()
{
var markup = @"
class C
{
/// <summary>
/// Summary for Foo
/// </summary>
/// <param name=" + "\"a\">Param a</param>" + @"
/// <param name=" + "\"b\">Param b</param>" + @"
void Foo(int a, int b)
{
[|Foo(a, $$b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", "Summary for Foo", "Param b", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutClosingParen()
{
var markup = @"
class C
{
void Foo()
{
[|Foo($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutClosingParenWithParameters()
{
var markup =
@"class C
{
void Foo(int a, int b)
{
[|Foo($$a, b
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutClosingParenWithParametersOn2()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(a, $$b
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnLambda()
{
var markup = @"
using System;
class C
{
void Foo()
{
Action<int> f = (i) => Console.WriteLine(i);
[|f($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Action<int>(int obj)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnMemberAccessExpression()
{
var markup = @"
class C
{
static void Bar(int a)
{
}
void Foo()
{
[|C.Bar($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Bar(int a)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestExtensionMethod1()
{
var markup = @"
using System;
class C
{
void Method()
{
string s = ""Text"";
[|s.ExtensionMethod($$
|]}
}
public static class MyExtension
{
public static int ExtensionMethod(this string s, int x)
{
return s.Length;
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.Extension}) int string.ExtensionMethod(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
// TODO: Once we do the work to allow extension methods in nested types, we should change this.
await TestAsync(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestOptionalParameters()
{
var markup = @"
class Class1
{
void Test()
{
Foo($$
}
void Foo(int a = 42)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Class1.Foo([int a = 42])", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestNoInvocationOnEventNotInCurrentClass()
{
var markup = @"
using System;
class C
{
void Foo()
{
D d;
[|d.evt($$
|]}
}
public class D
{
public event Action evt;
}";
await TestAsync(markup);
}
[WorkItem(539712, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539712")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnNamedType()
{
var markup = @"
class Program
{
void Main()
{
C.Foo($$
}
}
class C
{
public static double Foo(double x)
{
return x;
}
public double Foo(double x, double y)
{
return x + y;
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("double C.Foo(double x)", string.Empty, string.Empty, currentParameterIndex: 0)
};
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(539712, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539712")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnInstance()
{
var markup = @"
class Program
{
void Main()
{
new C().Foo($$
}
}
class C
{
public static double Foo(double x)
{
return x;
}
public double Foo(double x, double y)
{
return x + y;
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("double C.Foo(double x, double y)", string.Empty, string.Empty, currentParameterIndex: 0)
};
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(545118, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545118")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestStatic1()
{
var markup = @"
class C
{
static void Foo()
{
Bar($$
}
static void Bar()
{
}
void Bar(int i)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void C.Bar()", currentParameterIndex: 0)
};
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(545118, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545118")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestStatic2()
{
var markup = @"
class C
{
void Foo()
{
Bar($$
}
static void Bar()
{
}
void Bar(int i)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void C.Bar()", currentParameterIndex: 0),
new SignatureHelpTestItem("void C.Bar(int i)", currentParameterIndex: 0)
};
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(543117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543117")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnAnonymousType()
{
var markup = @"
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
var foo = new { Name = string.Empty, Age = 30 };
Foo(foo).Add($$);
}
static List<T> Foo<T>(T t)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
$@"void List<'a>.Add('a item)
{FeaturesResources.AnonymousTypes}
'a {FeaturesResources.Is} new {{ string Name, int Age }}",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: $@"
{FeaturesResources.AnonymousTypes}
'a {FeaturesResources.Is} new {{ string Name, int Age }}")
};
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnBaseExpression_ProtectedAccessibility()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnBaseExpression_AbstractBase()
{
var markup = @"
using System;
public abstract class Base
{
protected abstract void Foo(int x);
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnThisExpression_ProtectedAccessibility()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnThisExpression_ProtectedAccessibility_Overridden()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Derived.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase()
{
var markup = @"
using System;
public abstract class Base
{
protected abstract void Foo(int x);
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase_Overridden()
{
var markup = @"
using System;
public abstract class Base
{
protected abstract void Foo(int x);
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Derived.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnBaseExpression_ProtectedInternalAccessibility()
{
var markup = @"
using System;
public class Base
{
protected internal void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnBaseMember_ProtectedAccessibility_ThroughType()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
new Base().Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
await TestAsync(markup, null);
}
[WorkItem(968188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968188")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnBaseExpression_PrivateAccessibility()
{
var markup = @"
using System;
public class Base
{
private void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
await TestAsync(markup, null);
}
#endregion
#region "Current Parameter Name"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestCurrentParameterName()
{
var markup = @"
class C
{
void Foo(int someParameter, bool something)
{
Foo(something: false, someParameter: $$)
}
}";
await VerifyCurrentParameterNameAsync(markup, "someParameter");
}
#endregion
#region "Trigger tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerParens()
{
var markup = @"
class C
{
void Foo()
{
[|Foo($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerComma()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(23,$$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestNoInvocationOnSpace()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(23, $$|]);
}
}";
await TestAsync(markup, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestTriggerCharacterInComment01()
{
var markup = @"
class C
{
void Foo(int a)
{
Foo(/*,$$*/);
}
}";
await TestAsync(markup, Enumerable.Empty<SignatureHelpTestItem>(), usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestTriggerCharacterInComment02()
{
var markup = @"
class C
{
void Foo(int a)
{
Foo(//,$$
);
}
}";
await TestAsync(markup, Enumerable.Empty<SignatureHelpTestItem>(), usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestTriggerCharacterInString01()
{
var markup = @"
class C
{
void Foo(int a)
{
Foo("",$$"");
}
}";
await TestAsync(markup, Enumerable.Empty<SignatureHelpTestItem>(), usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacters()
{
char[] expectedCharacters = { ',', '(' };
char[] unexpectedCharacters = { ' ', '[', '<' };
VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters);
}
#endregion
#region "EditorBrowsable tests"
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Method_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
Foo.Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Method_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
Foo.Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Method_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Foo().Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public void Bar()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Method_Overloads_OneBrowsableAlways_OneBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Foo().Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar(int x)
{
}
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Method_Overloads_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Foo().Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar(int x)
{
}
}";
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task OverriddenSymbolsFilteredFromSigHelp()
{
var markup = @"
class Program
{
void M()
{
new D().Foo($$
}
}";
var referencedCode = @"
public class B
{
public virtual void Foo(int original)
{
}
}
public class D : B
{
public override void Foo(int derived)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void D.Foo(int derived)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverClass()
{
var markup = @"
class Program
{
void M()
{
new C().Foo($$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public class C
{
public void Foo()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverBaseClass()
{
var markup = @"
class Program
{
void M()
{
new D().Foo($$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public class B
{
public void Foo()
{
}
}
public class D : B
{
public void Foo(int x)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void B.Foo()", string.Empty, null, currentParameterIndex: 0),
new SignatureHelpTestItem("void D.Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0),
};
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_BrowsableStateNeverMethodsInBaseClass()
{
var markup = @"
class Program : B
{
void M()
{
Foo($$
}
}";
var referencedCode = @"
public class B
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void B.Foo()", string.Empty, null, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
public void Foo(T t) { }
public void Foo(int i) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed1()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
public void Foo(int i) { }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed2()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
public void Foo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(int i) { }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(int i) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new C<int, int>().Foo($$
}
}";
var referencedCode = @"
public class C<T, U>
{
public void Foo(T t) { }
public void Foo(U u) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new C<int, int>().Foo($$
}
}";
var referencedCode = @"
public class C<T, U>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
public void Foo(U u) { }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new C<int, int>().Foo($$
}
}";
var referencedCode = @"
public class C<T, U>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(U u) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
#endregion
#region "Awaitable tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task AwaitableMethod()
{
var markup = @"
using System.Threading.Tasks;
class C
{
async Task Foo()
{
[|Foo($$|]);
}
}";
var description = $@"
{WorkspacesResources.Usage}
await Foo();";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.Awaitable}) Task C.Foo()", methodDocumentation: description, currentParameterIndex: 0));
await TestSignatureHelpWithMscorlib45Async(markup, expectedOrderedItems, "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task AwaitableMethod2()
{
var markup = @"
using System.Threading.Tasks;
class C
{
async Task<Task<int>> Foo()
{
[|Foo($$|]);
}
}";
var description = $@"
{WorkspacesResources.Usage}
Task<int> x = await Foo();";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.Awaitable}) Task<Task<int>> C.Foo()", methodDocumentation: description, currentParameterIndex: 0));
await TestSignatureHelpWithMscorlib45Async(markup, expectedOrderedItems, "C#");
}
#endregion
[WorkItem(13849, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestSpecificity1()
{
var markup = @"
class Class1
{
static void Main()
{
var obj = new C<int>();
[|obj.M($$|])
}
}
class C<T>
{
/// <param name=""t"">Generic t</param>
public void M(T t) { }
/// <param name=""t"">Real t</param>
public void M(int t) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void C<int>.M(int t)", string.Empty, "Real t", currentParameterIndex: 0)
};
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(530017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530017")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task LongSignature()
{
var markup = @"
class C
{
void Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j, string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u, string v, string w, string x, string y, string z)
{
[|Foo($$|])
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
signature: "void C.Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j, string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u, string v, string w, string x, string y, string z)",
prettyPrintedSignature: @"void C.Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j,
string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u,
string v, string w, string x, string y, string z)",
currentParameterIndex: 0)
};
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task GenericExtensionMethod()
{
var markup = @"
interface IFoo
{
void Bar<T>();
}
static class FooExtensions
{
public static void Bar<T1, T2>(this IFoo foo) { }
}
class Program
{
static void Main()
{
IFoo f = null;
[|f.Bar($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void IFoo.Bar<T>()", currentParameterIndex: 0),
new SignatureHelpTestItem($"({CSharpFeaturesResources.Extension}) void IFoo.Bar<T1, T2>()", currentParameterIndex: 0),
};
// Extension methods are supported in Interactive/Script (yet).
await TestAsync(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithCrefXmlComments()
{
var markup = @"
class C
{
/// <summary>
/// Summary for foo. See method <see cref=""Bar"" />
/// </summary>
void Foo()
{
[|Foo($$|]);
}
void Bar() { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", "Summary for foo. See method C.Bar()", null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
void bar()
{
}
#endif
void foo()
{
bar($$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"void C.bar()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
void bar()
{
}
#endif
#if BAR
void foo()
{
bar($$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"void C.bar()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[WorkItem(768697, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768697")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InstanceAndStaticMethodsShown1()
{
var markup = @"
class C
{
Foo Foo;
void M()
{
Foo.Bar($$
}
}
class Foo
{
public void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0),
new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0)
};
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(768697, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768697")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InstanceAndStaticMethodsShown2()
{
var markup = @"
class C
{
Foo Foo;
void M()
{
Foo.Bar($$"");
}
}
class Foo
{
public void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0),
new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0)
};
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(768697, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768697")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InstanceAndStaticMethodsShown3()
{
var markup = @"
class C
{
Foo Foo;
void M()
{
Foo.Bar($$
}
}
class Foo
{
public static void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0),
new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0)
};
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(768697, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768697")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InstanceAndStaticMethodsShown4()
{
var markup = @"
class C
{
void M()
{
Foo x;
x.Bar($$
}
}
class Foo
{
public static void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(768697, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768697")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InstanceAndStaticMethodsShown5()
{
var markup = @"
class C
{
void M()
{
Foo x;
x.Bar($$
}
}
class x { }
class Foo
{
public static void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvokedWithNoToken()
{
var markup = @"
// foo($$";
await TestAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
#if TWO
void Do(string x){}
#endif
void Shared()
{
this.Do($$
}
}]]></Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"void C.Do(int x)", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[WorkItem(699, "https://github.com/dotnet/roslyn/issues/699")]
[WorkItem(1068424, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068424")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestGenericParameters1()
{
var markup = @"
class C
{
void M()
{
Foo(""""$$);
}
void Foo<T>(T a) { }
void Foo<T, U>(T a, U b) { }
}
";
var expectedOrderedItems = new List<SignatureHelpTestItem>()
{
new SignatureHelpTestItem("void C.Foo<string>(string a)", string.Empty, string.Empty, currentParameterIndex: 0),
new SignatureHelpTestItem("void C.Foo<T, U>(T a, U b)", string.Empty)
};
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(699, "https://github.com/dotnet/roslyn/issues/699")]
[WorkItem(1068424, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068424")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestGenericParameters2()
{
var markup = @"
class C
{
void M()
{
Foo("""", $$);
}
void Foo<T>(T a) { }
void Foo<T, U>(T a, U b) { }
}
";
var expectedOrderedItems = new List<SignatureHelpTestItem>()
{
new SignatureHelpTestItem("void C.Foo<T>(T a)", string.Empty),
new SignatureHelpTestItem("void C.Foo<T, U>(T a, U b)", string.Empty, string.Empty, currentParameterIndex: 1)
};
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(4144, "https://github.com/dotnet/roslyn/issues/4144")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestSigHelpIsVisibleOnInaccessibleItem()
{
var markup = @"
using System.Collections.Generic;
class A
{
List<int> args;
}
class B : A
{
void M()
{
args.Add($$
}
}
";
await TestAsync(markup, new[] { new SignatureHelpTestItem("void List<int>.Add(int item)") });
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.