context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using Skybrud.Essentials.Strings;
using Skybrud.Social.Interfaces.Http;
namespace Skybrud.Social.Http {
/// <summary>
/// Class representing a basic HTTP query string.
/// </summary>
public class SocialHttpQueryString : IHttpQueryString {
#region Private fields
private readonly Dictionary<string, string> _values;
#endregion
#region Properties
/// <summary>
/// Gets the number of key/value pairs contained in the internal dictionary instance.
/// </summary>
public int Count => _values.Count;
/// <summary>
/// Gets whether the internal dictionary is empty.
/// </summary>
public bool IsEmpty => _values.Count == 0;
/// <summary>
/// Gets an array of the keys of all items in the query string.
/// </summary>
public string[] Keys => _values.Keys.ToArray();
/// <summary>
/// Gets an array of all items in the query string.
/// </summary>
public KeyValuePair<string, string>[] Items => _values.ToArray();
/// <summary>
/// Gets the value of the item with the specified <paramref name="key"/>.
/// </summary>
/// <param name="key">The key of the item to match.</param>
/// <returns>The <see cref="string"/> value of the item, or <c>null</c> if not found.</returns>
public string this[string key] {
get => GetString(key);
set => _values[key] = value;
}
/// <summary>
/// Gets whether this implementation of <see cref="IHttpQueryString"/> supports duplicate keys.
/// </summary>
public bool SupportsDuplicateKeys => false;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance without any entries.
/// </summary>
public SocialHttpQueryString() {
_values = new Dictionary<string, string>();
}
/// <summary>
/// Initializes a new instance based on the specified <paramref name="dictionary"/>.
/// </summary>
/// <param name="dictionary">The dictionary the query string should be based.</param>
public SocialHttpQueryString(Dictionary<string, string> dictionary) {
_values = dictionary ?? throw new ArgumentNullException(nameof(dictionary));
}
#if NET_FRAMEWORK
/// <summary>
/// Initializes a new instance based on the specified <paramref name="collection"/>.
/// </summary>
/// <param name="collection">The collection the query string should be based.</param>
public SocialHttpQueryString(NameValueCollection collection) {
if (collection == null) throw new ArgumentNullException(nameof(collection));
_values = new Dictionary<string, string>();
foreach (string key in collection.AllKeys) {
_values.Add(key, collection[key]);
}
}
#endif
#endregion
#region Methods
/// <summary>
/// Adds an entry with the specified <paramref name="key"/> and <paramref name="value"/>.
/// </summary>
/// <param name="key">The key of the entry.</param>
/// <param name="value">The value of the entry.</param>
public void Add(string key, object value) {
if (String.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key));
_values.Add(key, String.Format(CultureInfo.InvariantCulture, "{0}", value));
}
/// <summary>
/// Sets the <paramref name="value"/> of an entry with the specified <paramref name="key"/>.
/// </summary>
/// <param name="key">The key of the entry.</param>
/// <param name="value">The value of the entry.</param>
public void Set(string key, object value) {
if (String.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key));
_values[key] = String.Format(CultureInfo.InvariantCulture, "{0}", value);
}
/// <summary>
/// Gets a string representation of the query string.
/// </summary>
/// <returns>The query string as an URL encoded string.</returns>
public override string ToString() {
return String.Join("&", from pair in _values select StringUtils.UrlEncode(pair.Key) + "=" + StringHelper.UrlEncode(pair.Value));
}
/// <summary>
/// Return whether the query string contains an entry with the specified <paramref name="key"/>.
/// </summary>
/// <param name="key">The key of the entry.</param>
/// <returns><c>true</c> if the query string contains the specified <paramref name="key"/>, otherwise
/// <c>false</c>.</returns>
public bool ContainsKey(string key) {
if (String.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key));
return _values.ContainsKey(key);
}
/// <summary>
/// Gets the <see cref="System.String"/> value of the entry with the specified <paramref name="key"/>.
/// </summary>
/// <param name="key">The key of the entry.</param>
/// <returns>The <see cref="System.String"/> value of the entry, or <c>null</c> if not found.</returns>
public string GetString(string key) {
if (String.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key));
return _values.TryGetValue(key, out string value) ? value : null;
}
/// <summary>
/// Gets the <see cref="System.Int32"/> value of the entry with the specified <paramref name="key"/>.
/// </summary>
/// <param name="key">The key of the entry.</param>
/// <returns>The <see cref="System.Int32"/> value of the entry, or <c>0</c> if not found.</returns>
public int GetInt32(string key) {
return GetValue<int>(key);
}
/// <summary>
/// Gets the <see cref="System.Int64"/> value of the entry with the specified <paramref name="key"/>.
/// </summary>
/// <param name="key">The key of the entry.</param>
/// <returns>The <see cref="System.Int64"/> value of the entry, or <c>0</c> if not found.</returns>
public long GetInt64(string key) {
return GetValue<long>(key);
}
/// <summary>
/// Gets the <see cref="System.Boolean"/> value of the entry with the specified <paramref name="key"/>.
/// </summary>
/// <param name="key">The key of the entry.</param>
/// <returns>The <see cref="System.Boolean"/> value of the entry, or <c>0</c> if not found.</returns>
public bool GetBoolean(string key) {
return GetValue<bool>(key);
}
/// <summary>
/// Gets the <see cref="System.Double"/> value of the entry with the specified <paramref name="key"/>.
/// </summary>
/// <param name="key">The key of the entry.</param>
/// <returns>The <see cref="System.Double"/> value of the entry, or <c>0</c> if not found.</returns>
public double GetDouble(string key) {
return GetValue<double>(key);
}
/// <summary>
/// Gets the <see cref="System.Single"/> value of the entry with the specified <paramref name="key"/>.
/// </summary>
/// <param name="key">The key of the entry.</param>
/// <returns>The <see cref="System.Single"/> value of the entry, or <c>0</c> if not found.</returns>
public float GetFloat(string key) {
return GetValue<float>(key);
}
/// <summary>
/// Gets the <typeparamref name="T"/> value of the entry with the specified <paramref name="key"/>.
/// </summary>
/// <param name="key">The key of the entry.</param>
/// <returns>The <typeparamref name="T"/> value of the entry, or the default value of <typeparamref name="T"/> if not found.</returns>
private T GetValue<T>(string key) {
if (String.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key));
string value;
if (!_values.TryGetValue(key, out value)) return default(T);
return String.IsNullOrWhiteSpace(value) ? default(T) : (T) Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>An enumerator that can be used to iterate through the collection.</returns>
public IEnumerator<KeyValuePair<string, string>> GetEnumerator() {
return _values.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>An enumerator that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
#endregion
#region Static methods
/// <summary>
/// Parses the specified query string into an instance of <see cref="SocialHttpQueryString"/>.
/// </summary>
/// <param name="str">The query string to parse.</param>
/// <returns>An instance of <see cref="SocialHttpQueryString"/>.</returns>
public static SocialHttpQueryString ParseQueryString(string str) {
return ParseQueryString(str, false);
}
/// <summary>
/// Parses the specified query string into an instance of <see cref="SocialHttpQueryString"/>.
/// </summary>
/// <param name="str">The query string to parse.</param>
/// <param name="urlencoded">Whether the query string is URL encoded</param>
/// <returns>An instance of <see cref="SocialHttpQueryString"/> representing the parsed query string.</returns>
/// <see>
/// <cref>https://referencesource.microsoft.com/#System.Web/HttpValueCollection.cs,222f9a1bfd1f9a98,references</cref>
/// </see>
public static SocialHttpQueryString ParseQueryString(string str, bool urlencoded) {
// Return an empty instance if "str" is NULL or empty
if (String.IsNullOrWhiteSpace(str)) return new SocialHttpQueryString();
Dictionary<string, string> values = new Dictionary<string, string>();
int length = str.Length;
int i = 0;
while (i < length) {
int si = i;
int ti = -1;
while (i < length) {
char ch = str[i];
if (ch == '=') {
if (ti < 0)
ti = i;
} else if (ch == '&') {
break;
}
i++;
}
// extract the name / value pair
String name = null;
String value;
if (ti >= 0) {
name = str.Substring(si, ti - si);
value = str.Substring(ti + 1, i - ti - 1);
} else {
value = str.Substring(si, i - si);
}
// TODO: Should we throw an exception if the key already exists? (I think Add might do it for us)
// add name / value pair to the collection
if (urlencoded) {
values.Add(StringUtils.UrlDecode(name), StringUtils.UrlDecode(value));
} else {
values.Add(name ?? "", value);
}
// trailing '&'
if (i == length - 1 && str[i] == '&') {
values.Add("", String.Empty);
}
i++;
}
return new SocialHttpQueryString(values);
}
#endregion
#region Operator overloading
#if NET_FRAMEWORK
/// <summary>
/// Initializes a new query string based on the specified <paramref name="collection"/>.
/// </summary>
/// <param name="collection">The instance of <see cref="NameValueCollection"/> the query string should be based on.</param>
/// <returns>An instance of <see cref="SocialHttpQueryString"/> based on the specified <paramref name="collection"/>.</returns>
public static implicit operator SocialHttpQueryString(NameValueCollection collection) {
return collection == null ? null : new SocialHttpQueryString(collection);
}
#endif
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Graphics.Drawables;
using Android.Graphics;
namespace QuickAction3Dnet
{
public class ActionItemClickEventArgs : EventArgs
{
public ActionItem ActionItem { get; set; }
}
public class QuickAction : PopupWindows
{
private ImageView arrowUp;
private ImageView arrowDown;
private LayoutInflater inflater;
private ViewGroup track;
private ScrollView scroller;
private List<ActionItem> actionItems = new List<ActionItem>();
private bool didAction;
private int childPos;
private int insertPos;
private int rootWidth=0;
public enum Orientation { Horizontal= 0, Vertical };
private Orientation orientation;
public enum AnimationStyle { GrowFromLeft= 1, GrowFromRight, GrowFromCenter, Reflect, Auto };
private AnimationStyle animationStyle;
/// <summary>
/// Constructor for default vertical layout
/// </summary>
/// <param name="context">Context.</param>
public QuickAction(Context context)
: this(context, Orientation.Vertical)
{
}
/// <summary>
/// Constructor allowing orientation override
/// </summary>
/// <param name="context">Context.</param>
/// <param name="orientation"> Layout orientation, can be vartical or horizontal.</param>
public QuickAction(Context context, Orientation orientation)
: base(context)
{
this.orientation = orientation;
inflater = context.GetSystemService(Context.LayoutInflaterService).JavaCast<LayoutInflater>();
if (orientation == Orientation.Horizontal) {
SetRootViewId(Resource.Layout.popup_horizontal);
} else {
SetRootViewId(Resource.Layout.popup_vertical);
}
animationStyle = AnimationStyle.Auto;
childPos = 0;
}
protected override void onDismissEvent(object sender, EventArgs e)
{
if (!didAction)
base.onDismissEvent(sender, e);
}
public ActionItem GetActionItem(int index)
{
return actionItems[index];
}
public void SetRootViewId(int id)
{
rootView = inflater.Inflate(id, null);
track = rootView.FindViewById<ViewGroup>(Resource.Id.tracks);
arrowDown = rootView.FindViewById<ImageView>(Resource.Id.arrow_down);
arrowUp = rootView.FindViewById<ImageView>(Resource.Id.arrow_up);
scroller = rootView.FindViewById<ScrollView>(Resource.Id.scroller);
rootView.LayoutParameters= new Android.Views.ViewGroup.LayoutParams(WindowManagerLayoutParams.WrapContent, WindowManagerLayoutParams.WrapContent);
ContentView= rootView;
}
/// <summary>
/// Sets the animation style.
/// </summary>
/// <param name="animationStyle">The default is set to AnimationStyle.Auto.</param>
public void SetAnimStyle(AnimationStyle animationStyle)
{
this.animationStyle = animationStyle;
}
public event EventHandler<ActionItemClickEventArgs> ItemClickEvent;
public void AddActionItem(ActionItem action)
{
actionItems.Add(action);
string title = action.Title;
Drawable icon = action.Icon;
View container;
if (orientation == Orientation.Horizontal) {
container = inflater.Inflate(Resource.Layout.action_item_horizontal, null);
} else {
container = inflater.Inflate(Resource.Layout.action_item_vertical, null);
}
ImageView img = container.FindViewById<ImageView>(Resource.Id.iv_icon);
TextView text = container.FindViewById<TextView>(Resource.Id.tv_title);
if (icon != null) {
img.SetImageDrawable(icon);
} else {
img.Visibility = ViewStates.Gone;
}
if (title != null) {
text.Text = title;
} else {
text.Visibility = ViewStates.Gone;
}
int pos = childPos;
container.Click += (sender, e) => {
EventHandler<ActionItemClickEventArgs> handler = ItemClickEvent;
if (handler != null)
{
ActionItemClickEventArgs eventArgs= new ActionItemClickEventArgs();
eventArgs.ActionItem = GetActionItem(pos);
handler(this, eventArgs);
}
if (!this.GetActionItem(pos).Sticky) {
didAction = true;
Dismiss();
}
};
container.Focusable = true;
container.Clickable = true;
if (orientation == Orientation.Horizontal && childPos != 0) {
View separator = inflater.Inflate(Resource.Layout.horiz_separator, null);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
WindowManagerLayoutParams.WrapContent, WindowManagerLayoutParams.FillParent);
separator.LayoutParameters = layoutParams;
separator.SetPadding(5, 0, 5, 0);
track.AddView(separator, insertPos);
insertPos++;
}
track.AddView(container, insertPos);
childPos++;
insertPos++;
}
public void Show (View anchor)
{
preShow();
int xPos, yPos, arrowPos;
didAction = false;
int[] location = new int[2];
anchor.GetLocationOnScreen(location);
Rect anchorRect = new Rect(location[0], location[1], location[0] + anchor.Width, location[1] + anchor.Height);
rootView.Measure(WindowManagerLayoutParams.WrapContent, WindowManagerLayoutParams.WrapContent);
int rootHeight = rootView.MeasuredHeight;
if (rootWidth == 0) {
rootWidth = rootView.MeasuredWidth;
}
int screenWidth = windowManager.DefaultDisplay.Width;
int screenHeight = windowManager.DefaultDisplay.Height;
//automatically get X coord of popup (top left)
if ((anchorRect.Left + rootWidth) > screenWidth) {
xPos = anchorRect.Left - (rootWidth-anchor.Width);
xPos = (xPos < 0) ? 0 : xPos;
arrowPos = anchorRect.CenterX()-xPos;
} else {
if (anchor.Width > rootWidth) {
xPos = anchorRect.CenterX() - (rootWidth/2);
} else {
xPos = anchorRect.Left;
}
arrowPos = anchorRect.CenterX()-xPos;
}
int dyTop = anchorRect.Top;
int dyBottom = screenHeight - anchorRect.Bottom;
bool onTop = (dyTop > dyBottom) ? true : false;
if (onTop) {
if (rootHeight > dyTop) {
yPos = 15;
ViewGroup.LayoutParams l = scroller.LayoutParameters;
l.Height = dyTop - anchor.Height;
} else {
yPos = anchorRect.Top - rootHeight;
}
} else {
yPos = anchorRect.Bottom;
if (rootHeight > dyBottom) {
ViewGroup.LayoutParams l = scroller.LayoutParameters;
l.Height = dyBottom;
}
}
ShowArrow(((onTop) ? Resource.Id.arrow_down : Resource.Id.arrow_up), arrowPos);
SetAnimationStyle(screenWidth, anchorRect.CenterX(), onTop);
window.ShowAtLocation(anchor, GravityFlags.NoGravity, xPos, yPos);
}
/// <summary>
/// Sets the animation style.
/// </summary>
/// <param name="screenWidth">Screen width.</param>
/// <param name="requestedX">distance from left edge</param>
/// <param name="onTop">flag to indicate where the popup should be displayed. Set TRUE if displayed on top of anchor view and vice versa</param>
private void SetAnimationStyle(int screenWidth, int requestedX, bool onTop) {
int arrowPos = requestedX - arrowUp.MeasuredWidth/2;
switch (animationStyle) {
case AnimationStyle.GrowFromLeft:
window.AnimationStyle = (onTop) ? Resource.Style.Animations_PopUpMenu_Left : Resource.Style.Animations_PopDownMenu_Left;
break;
case AnimationStyle.GrowFromRight:
window.AnimationStyle = (onTop) ? Resource.Style.Animations_PopUpMenu_Right : Resource.Style.Animations_PopDownMenu_Right;
break;
case AnimationStyle.GrowFromCenter:
window.AnimationStyle = (onTop) ? Resource.Style.Animations_PopUpMenu_Center : Resource.Style.Animations_PopDownMenu_Center;
break;
case AnimationStyle.Reflect:
window.AnimationStyle = (onTop) ? Resource.Style.Animations_PopUpMenu_Reflect : Resource.Style.Animations_PopDownMenu_Reflect;
break;
case AnimationStyle.Auto:
if (arrowPos <= screenWidth/4) {
window.AnimationStyle = (onTop) ? Resource.Style.Animations_PopUpMenu_Left : Resource.Style.Animations_PopDownMenu_Left;
} else if (arrowPos > screenWidth/4 && arrowPos < 3 * (screenWidth/4)) {
window.AnimationStyle = (onTop) ? Resource.Style.Animations_PopUpMenu_Center : Resource.Style.Animations_PopDownMenu_Center;
} else {
window.AnimationStyle = (onTop) ? Resource.Style.Animations_PopUpMenu_Right : Resource.Style.Animations_PopDownMenu_Right;
}
break;
}
}
private void ShowArrow(int whichArrow, int requestedX)
{
View showArrow = (whichArrow == Resource.Id.arrow_up) ? arrowUp : arrowDown;
View hideArrow = (whichArrow == Resource.Id.arrow_up) ? arrowDown : arrowUp;
int arrowWidth = arrowUp.MeasuredWidth;
showArrow.Visibility = ViewStates.Visible;
ViewGroup.MarginLayoutParams param = (ViewGroup.MarginLayoutParams)showArrow.LayoutParameters;
param.LeftMargin = requestedX - arrowWidth / 2;
hideArrow.Visibility = ViewStates.Invisible;
}
}
}
| |
namespace FakeItEasy.Expressions
{
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using FakeItEasy.Configuration;
using FakeItEasy.Core;
using FakeItEasy.Expressions.ArgumentConstraints;
internal class ExpressionArgumentConstraintFactory
{
private readonly IArgumentConstraintTrapper argumentConstraintTrapper;
public ExpressionArgumentConstraintFactory(IArgumentConstraintTrapper argumentConstraintTrapper)
{
this.argumentConstraintTrapper = argumentConstraintTrapper;
}
public virtual IArgumentConstraint GetArgumentConstraint(ParsedArgumentExpression argument)
{
var parameterType = argument.ArgumentInformation.ParameterType;
if (IsParamArrayExpression(argument))
{
return this.CreateParamArrayConstraint((NewArrayExpression)argument.Expression, parameterType);
}
var isOutOrRefArgument = argument.ArgumentInformation.IsOutOrRef();
var constraint = this.GetArgumentConstraintFromExpression(argument.Expression, parameterType, out var argumentValue);
if (isOutOrRefArgument)
{
if (IsOutArgument(argument))
{
constraint = new OutArgumentConstraint(argumentValue);
}
else
{
constraint = new RefArgumentConstraint(constraint, argumentValue);
}
}
return constraint;
}
private static bool IsParamArrayExpression(ParsedArgumentExpression argument)
{
return argument.Expression is NewArrayExpression && IsTaggedWithParamArrayAttribute(argument);
}
private static bool IsTaggedWithParamArrayAttribute(ParsedArgumentExpression argument)
{
return argument.ArgumentInformation.IsDefined(typeof(ParamArrayAttribute), true);
}
private static bool IsOutArgument(ParsedArgumentExpression argument)
{
return argument.ArgumentInformation.IsOut;
}
private static IArgumentConstraint CreateEqualityConstraint(object? expressionValue)
{
return new EqualityArgumentConstraint(expressionValue);
}
private static void CheckArgumentExpressionIsValid(Expression expression)
{
expression = GetExpressionWithoutConversion(expression);
if (expression is MemberExpression memberExpression && IsMemberOfA(memberExpression.Member))
{
// It's A._, or A.Ignore, so it's safe.
return;
}
var visitor = new ArgumentConstraintExpressionVisitor();
if (expression is MethodCallExpression methodCallExpression)
{
// A method call. It might be A<T>.That.Matches, or one of the other extension methods, so don't
// check the method node itself. Instead, look at all the arguments (except the first, if it's an
// extension method).
int firstArgumentToCheck = IsArgumentConstraintManagerExtensionMethod(methodCallExpression) ? 1 : 0;
for (var index = firstArgumentToCheck; index < methodCallExpression.Arguments.Count; index++)
{
visitor.Visit(methodCallExpression.Arguments[index]);
}
}
else
{
// An unknown kind of expression - could be a constructor, or almost anything else. Play it safe and
// check it out.
visitor.Visit(expression);
}
}
private static bool IsArgumentConstraintManagerExtensionMethod(MethodCallExpression methodCallExpression)
{
if (methodCallExpression.Arguments.Count == 0)
{
return false;
}
// Checking for an extension method is very expensive, so check the common
// case first - that the method is one of the predefined extension methods.
if (GetGenericTypeDefinition(methodCallExpression.Method.DeclaringType!) ==
typeof(ArgumentConstraintManagerExtensions))
{
return true;
}
return methodCallExpression.Method.IsStatic &&
methodCallExpression.Method.IsDefined(typeof(ExtensionAttribute), false);
}
/// <summary>
/// Removes the conversion node introduced in a Linq expression by implicit conversion.
/// </summary>
/// <param name="expression">The expression from which to remove the conversion.</param>
/// <returns>The original expression, if no conversion is happening, or the expression that would be converted.</returns>
private static Expression GetExpressionWithoutConversion(Expression expression)
{
while (expression is UnaryExpression conversion && conversion.NodeType == ExpressionType.Convert)
{
expression = conversion.Operand;
}
return expression;
}
private static bool IsMemberOfA(MemberInfo member)
{
return GetGenericTypeDefinition(member.DeclaringType!) == typeof(A<>);
}
private static Type GetGenericTypeDefinition(Type type)
{
if (type.IsGenericType && !type.IsGenericTypeDefinition)
{
return type.GetGenericTypeDefinition();
}
return type;
}
private static void CheckConstraintIsCompatibleWithParameterType(ITypedArgumentConstraint constraint, Type parameterType)
{
parameterType = parameterType.IsByRef ? parameterType.GetElementType()! : parameterType;
if (!parameterType.IsAssignableFrom(constraint.Type))
{
throw new FakeConfigurationException(ExceptionMessages.ArgumentConstraintHasWrongType(constraint.Type, parameterType));
}
}
private IArgumentConstraint GetArgumentConstraintFromExpression(Expression expression, Type parameterType, out object? value)
{
CheckArgumentExpressionIsValid(expression);
object? expressionValue = null;
IArgumentConstraint constraint;
try
{
constraint = this.argumentConstraintTrapper.TrapConstraintOrCreate(
() => expressionValue = expression.Evaluate(),
() => CreateEqualityConstraint(expressionValue));
}
catch (TargetInvocationException ex)
{
throw new UserCallbackException(
ExceptionMessages.UserCallbackThrewAnException($"Argument constraint expression <{expression}>"),
ex.InnerException!);
}
if (constraint is ITypedArgumentConstraint typedConstraint)
{
CheckConstraintIsCompatibleWithParameterType(typedConstraint, parameterType);
}
value = expressionValue;
return constraint;
}
private IArgumentConstraint CreateParamArrayConstraint(NewArrayExpression expression, Type parameterType)
{
var result = new List<IArgumentConstraint>();
var itemType = parameterType.GetElementType()!;
foreach (var argumentExpression in expression.Expressions)
{
result.Add(this.GetArgumentConstraintFromExpression(argumentExpression, itemType, out _));
}
return new AggregateArgumentConstraint(result);
}
private class ArgumentConstraintExpressionVisitor : ExpressionVisitor
{
protected override Expression VisitMember(MemberExpression node)
{
if (IsMemberOfA(node.Member))
{
throw new InvalidOperationException(ExceptionMessages.ArgumentConstraintCannotBeNestedInArgument);
}
return base.VisitMember(node);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Diagnostics;
namespace Core.Geometry
{
public class RectangleE : AShapeE, ICloneable, IComparable<RectangleE>
{//RectangleC
#region Private Fields
private double m_X;
private double m_Y;
private double m_Width;
private double m_Height;
#endregion
#region Constructors
public RectangleE(double x, double y, double width, double height) {
m_X = x;
m_Width = width;
m_Y = y;
m_Height = height;
}
public RectangleE(PointE location, SizeE size) {
m_X = location.X;
m_Width = size.Width;
m_Y = location.Y;
m_Height = size.Height;
}
public RectangleE(IntervalE xInt, IntervalE yInt) {
m_X = xInt.Minimum;
m_Width = xInt.Dimension;
m_Y = yInt.Minimum;
m_Height = yInt.Dimension;
}
public RectangleE(RectangleE r) {
m_X = r.X;
m_Width = r.Width;
m_Y = r.Y;
m_Height = r.Height;
}
public RectangleE() {
}
#endregion
#region GetSet
[XmlAttribute()]
public double X {
get {
return m_X;
}
set {
m_X = value;
CallGeometryChanged();
}
}
[XmlAttribute()]
public double Y {
get {
return m_Y;
}
set {
m_Y = value;
CallGeometryChanged();
}
}
[XmlAttribute()]
public double Width {
get {
return m_Width;
}
set {
m_Width = value;
CallGeometryChanged();
}
}
[XmlAttribute()]
public double Height {
get {
return m_Height;
}
set {
m_Height = value;
CallGeometryChanged();
}
}
[XmlIgnore()]
public double Top {
get {
return Y + Height;
}
set {
Y = value - Height;
}
}
[XmlIgnore()]
public double Bottom {
get {
return Y;
}
set {
Y = value;
}
}
[XmlIgnore()]
public double Left {
get {
return X;
}
set {
X = value;
}
}
[XmlIgnore()]
public double Right {
get {
return X + Width;
}
set {
X = value - Width;
}
}
[XmlIgnore()]
public PointE Location {
get {
return new PointE(X, Y);
}
set {
X = value.X;
Y = value.Y;
}
}
[XmlIgnore()]
public SizeE Size {
get {
return new SizeE(Width, Height);
}
set {
Width = value.Width;
Height = value.Height;
}
}
[XmlIgnore()]
public PointE Center {
get {
return new PointE(X + Width / 2, Y + Height / 2);
}
set {
X = value.X - Width / 2;
Y = value.Y - Height / 2;
}
}
[XmlIgnore()]
public PointE TopLeft {
get {
return new PointE(X, Y + Height);
}
set {
X = value.X;
Y = value.Y - Height;
}
}
[XmlIgnore()]
public PointE TopRight {
get {
return new PointE(X + Width, Y + Height);
}
set {
X = value.X - Width;
Y = value.Y - Height;
}
}
[XmlIgnore()]
public PointE BottomLeft {
get {
return Location;
}
set {
Location = value;
}
}
[XmlIgnore()]
public PointE BottomRight {
get {
return new PointE(X + Width, Y);
}
set {
X = value.X - Width;
Y = value.Y;
}
}
[XmlIgnore()]
public override RectangleE BoundingBox {
get {
return CloneRect();
}
}
[XmlIgnore()]
public IntervalE XInterval {
get {
return new IntervalE(X, Right);
}
}
[XmlIgnore()]
public IntervalE YInterval {
get {
return new IntervalE(Y, Top);
}
}
[XmlIgnore()]
public bool IsEmpty {
get {
return (m_Width == 0 || m_Height == 0);
}
}
[XmlIgnore()]
public double Area {
get {
return m_Width * m_Height;
}
}
#endregion
#region Operations
public RectangleE Union(RectangleE r) {
if (r.Height == 0 || r.Width == 0) {
return CloneRect();
}
if (Height == 0 || Width == 0) {
return r.CloneRect();
}
return new RectangleE(XInterval.Union(r.XInterval), YInterval.Union(r.YInterval));
}
public RectangleE Union(PointE pt) {
if (Contains(pt)) {
return CloneRect();
}
IntervalE xInt = XInterval.Union(pt.X);
RectangleE ans = new RectangleE(xInt, YInterval.Union(pt.Y));
return ans;
}
public override bool ContainsPoint(PointE point) {
return Contains(point); //--simple wrapper for IShapeE compatibility
}
public bool Contains(PointE pt) {
return XInterval.Contains(pt.X) && YInterval.Contains(pt.Y);
}
public override bool FullyContains(IShapeE shapeE) {
if (shapeE == null) {
return false;
}
return Contains(shapeE.BoundingBox);
}
public override bool MostlyContains(IShapeE shapeE, double tolerance) {
if (shapeE == null) {
return false;
}
RectangleE intersect = Intersect(shapeE.BoundingBox);
return intersect.Area / Area > tolerance;
}
public bool Contains(RectangleE rect) {
return XInterval.Contains(rect.XInterval) && YInterval.Contains(rect.YInterval);
}
public RectangleE Intersect(RectangleE r) {
IntervalE xIntersect = XInterval.Intersect(r.XInterval);
IntervalE yIntersect = YInterval.Intersect(r.YInterval);
return new RectangleE(xIntersect, yIntersect);
}
public bool IntersectsWith(RectangleE r) {
return XInterval.IntersectsWith(r.XInterval) && YInterval.IntersectsWith(r.YInterval);
}
public bool OverlapsWith(RectangleE r) {
if (IntersectsWith(r)) return true;
if (Contains(r)) return true;
if (r.Contains(this)) return true;
return false;
}
public void Inflate(SizeE size) {
Inflate(size.Width, size.Height);
}
public void Inflate(double amount) {
Inflate(amount, amount);
}
public void Inflate(double amountX, double amountY) {
Inflate(amountX, amountX, amountY, amountY);
}
public void Inflate(double left, double right, double top, double bottom) {
X -= left;
Y -= top;
Size = Size.Inflate(left + right, top + bottom);
}
public RectangleE ScaleCloneBy(double val) {
RectangleE ans = new RectangleE(this);
ans.ScaleSelfBy(val);
return ans;
}
public RectangleE ScaleCloneBy(double val, PointE about) {
RectangleE ans = new RectangleE(this);
ans.ScaleSelfBy(val, about);
return ans;
}
public void ScaleSelfBy(double val) {
m_X = m_X * val;
m_Y = m_Y * val;
m_Width = m_Width * val;
m_Height = m_Height * val;
}
public void ScaleSelfBy(double val, PointE about) {
m_Width = m_Width * val;
m_Height = m_Height * val;
Location = Calc.PointBetween(about, Location, val);
}
public override string ToString() {
return "RectangleE: X:" + X + ", Y:" + Y + ", W:" + Width + ", H:" + Height;
}
#endregion
#region ICloneable Members
public object Clone() {
return CloneRect();
}
public RectangleE CloneRect() {
return new RectangleE(X, Y, Width, Height);
}
public RectangleE ShiftRectangle(PointE point) {
return new RectangleE(Location.ShiftPt(point), Size);
}
public override IShapeE Shift(PointE point) {
return ShiftRectangle(point);
}
#endregion
#region IComparable<RectangleE> Members
public int CompareTo(RectangleE other) {
return Area.CompareTo(other.Area);
}
#endregion
public static explicit operator System.Drawing.Rectangle(RectangleE r) {
return new System.Drawing.Rectangle((int)r.X, (int)r.Y, (int)r.Width, (int)r.Height);
}
public static explicit operator System.Drawing.RectangleF(RectangleE r) {
return new System.Drawing.RectangleF((float)r.X, (float)r.Y, (float)r.Width, (float)r.Height);
}
public static RectangleE FromMinMax(PointE minPt, PointE maxPt) {
return new RectangleE(minPt, (SizeE)(maxPt - minPt));
}
public static RectangleE FromMinMax(double minX, double minY, double maxX, double maxY) {
return new RectangleE(minX, minY, maxX - minX, maxY - minY);
}
}
}
| |
#region Copyright
//
// This framework is based on log4j see http://jakarta.apache.org/log4j
// Copyright (C) The Apache Software Foundation. All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.txt file.
//
#endregion
using System;
using System.Text;
using System.Xml;
using System.IO;
using log4net.spi;
using log4net.helpers;
namespace log4net.Layout
{
/// <summary>
/// Layout that formats the log events as XML elements.
/// </summary>
/// <remarks>
/// <para>
/// The output of the <see cref="XmlLayout" /> consists of a series of
/// log4net:event elements. It does not output a complete well-formed XML
/// file. The output is designed to be included as an <em>external entity</em>
/// in a separate file to form a correct XML file.
/// </para>
/// <para>
/// For example, if <code>abc</code> is the name of the file where
/// the <see cref="XmlLayout" /> output goes, then a well-formed XML file would
/// be:
/// </para>
/// <code>
/// <?xml version="1.0" ?>
///
/// <!DOCTYPE log4net:events SYSTEM "log4net-events.dtd" [<!ENTITY data SYSTEM "abc">]>
///
/// <log4net:events version="1.2" xmlns:log4net="http://log4net.sourceforge.net/">
/// &data;
/// </log4net:events>
/// </code>
/// <para>
/// This approach enforces the independence of the <see cref="XmlLayout" />
/// and the appender where it is embedded.
/// </para>
/// <para>
/// The <code>version</code> attribute helps components to correctly
/// interpret output generated by <see cref="XmlLayout" />. The value of
/// this attribute should be "1.2" for release 1.2 and later.
/// </para>
/// <para>
/// Alternatively the <c>Header</c> and <c>Footer</c> properties can be
/// configured to output the correct XML header, open tag and close tag.
/// </para>
/// </remarks>
public class XmlLayout : XmlLayoutBase
{
#region Public Instance Constructors
/// <summary>
/// Constructs an XmlLayout
/// </summary>
public XmlLayout() : base()
{
}
/// <summary>
/// Constructs an XmlLayout.
/// </summary>
/// <remarks>
/// <para>
/// The <b>LocationInfo</b> option takes a boolean value. By
/// default, it is set to false which means there will be no location
/// information output by this layout. If the the option is set to
/// true, then the file name and line number of the statement
/// at the origin of the log statement will be output.
/// </para>
/// <para>
/// If you are embedding this layout within an SMTPAppender
/// then make sure to set the <b>LocationInfo</b> option of that
/// appender as well.
/// </para>
/// </remarks>
public XmlLayout(bool locationInfo) : base(locationInfo)
{
}
#endregion Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// The prefix to use for all element names
/// </summary>
/// <remarks>
/// <para>
/// The default prefix is <b>log4net</b>. Set this property
/// to change the prefix. If the prefix is set to an empty string
/// then no prefix will be written.
/// </para>
/// </remarks>
public string Prefix
{
get { return m_prefix; }
set { m_prefix = value; }
}
#endregion Public Instance Properties
#region Implementation of IOptionHandler
/// <summary>
/// Builds a cache of the element names
/// </summary>
override public void ActivateOptions()
{
base.ActivateOptions();
// Cache the full element names including the prefix
if (m_prefix != null && m_prefix.Length > 0)
{
m_elmEvent = m_prefix + ":" + ELM_EVENT;
m_elmMessage = m_prefix + ":" + ELM_MESSAGE;
m_elmNdc = m_prefix + ":" + ELM_NDC;
m_elmMdc = m_prefix + ":" + ELM_MDC;
m_elmProperties = m_prefix + ":" + ELM_PROPERTIES;
m_elmData = m_prefix + ":" + ELM_DATA;
m_elmException = m_prefix + ":" + ELM_EXCEPTION;
m_elmLocation = m_prefix + ":" + ELM_LOCATION;
}
}
#endregion Implementation of IOptionHandler
#region Override implementation of XMLLayoutBase
/// <summary>
/// Does the actual writing of the XML.
/// </summary>
/// <param name="writer">The writer to use to output the event to.</param>
/// <param name="loggingEvent">The event to write.</param>
override protected void FormatXml(XmlWriter writer, LoggingEvent loggingEvent)
{
writer.WriteStartElement(m_elmEvent);
writer.WriteAttributeString(ATTR_LOGGER, loggingEvent.LoggerName);
writer.WriteAttributeString(ATTR_TIMESTAMP, XmlConvert.ToString(loggingEvent.TimeStamp));
writer.WriteAttributeString(ATTR_LEVEL, loggingEvent.Level.ToString());
writer.WriteAttributeString(ATTR_THREAD, loggingEvent.ThreadName);
if (loggingEvent.Domain != null && loggingEvent.Domain.Length > 0)
{
writer.WriteAttributeString(ATTR_DOMAIN, loggingEvent.Domain);
}
if (loggingEvent.Identity != null && loggingEvent.Identity.Length > 0)
{
writer.WriteAttributeString(ATTR_IDENTITY, loggingEvent.Identity);
}
if (loggingEvent.UserName != null && loggingEvent.UserName.Length > 0)
{
writer.WriteAttributeString(ATTR_USERNAME, loggingEvent.UserName);
}
// Append the message text
writer.WriteStartElement(m_elmMessage);
Transform.WriteEscapedXmlString(writer, loggingEvent.RenderedMessage);
writer.WriteEndElement();
if (loggingEvent.NestedContext != null && loggingEvent.NestedContext.Length > 0)
{
// Append the NDC text
writer.WriteStartElement(m_elmNdc);
Transform.WriteEscapedXmlString(writer, loggingEvent.NestedContext);
writer.WriteEndElement();
}
if (loggingEvent.MappedContext != null && loggingEvent.MappedContext.Count > 0)
{
// Append the MDC text
writer.WriteStartElement(m_elmMdc);
foreach(System.Collections.DictionaryEntry entry in loggingEvent.MappedContext)
{
writer.WriteStartElement(m_elmData);
writer.WriteAttributeString(ATTR_NAME, entry.Key.ToString());
writer.WriteAttributeString(ATTR_VALUE, entry.Value.ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
}
if (loggingEvent.Properties != null)
{
// Append the properties text
string[] propKeys = loggingEvent.Properties.GetKeys();
if (propKeys.Length > 0)
{
writer.WriteStartElement(m_elmProperties);
foreach(string key in propKeys)
{
writer.WriteStartElement(m_elmData);
writer.WriteAttributeString(ATTR_NAME, key);
writer.WriteAttributeString(ATTR_VALUE, loggingEvent.Properties[key].ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
}
}
string exceptionStr = loggingEvent.GetExceptionStrRep();
if (exceptionStr != null && exceptionStr.Length > 0)
{
// Append the stack trace line
writer.WriteStartElement(m_elmException);
Transform.WriteEscapedXmlString(writer, exceptionStr);
writer.WriteEndElement();
}
if (LocationInfo)
{
LocationInfo locationInfo = loggingEvent.LocationInformation;
writer.WriteStartElement(m_elmLocation);
writer.WriteAttributeString(ATTR_CLASS, locationInfo.ClassName);
writer.WriteAttributeString(ATTR_METHOD, locationInfo.MethodName);
writer.WriteAttributeString(ATTR_FILE, locationInfo.FileName);
writer.WriteAttributeString(ATTR_LINE, locationInfo.LineNumber);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
#endregion Override implementation of XMLLayoutBase
#region Private Instance Fields
/// <summary>
/// The prefix to use for all generated element names
/// </summary>
private string m_prefix = PREFIX;
private string m_elmEvent = ELM_EVENT;
private string m_elmMessage = ELM_MESSAGE;
private string m_elmNdc = ELM_NDC;
private string m_elmMdc = ELM_MDC;
private string m_elmData = ELM_DATA;
private string m_elmProperties = ELM_PROPERTIES;
private string m_elmException = ELM_EXCEPTION;
private string m_elmLocation = ELM_LOCATION;
#endregion Private Instance Fields
#region Private Static Fields
private const string PREFIX = "log4net";
private const string ELM_EVENT = "event";
private const string ELM_MESSAGE = "message";
private const string ELM_NDC = "ndc";
private const string ELM_MDC = "mdc";
private const string ELM_PROPERTIES = "properties";
private const string ELM_DATA = "data";
private const string ELM_EXCEPTION = "exception";
private const string ELM_LOCATION = "locationInfo";
private const string ATTR_LOGGER = "logger";
private const string ATTR_TIMESTAMP = "timestamp";
private const string ATTR_LEVEL = "level";
private const string ATTR_THREAD = "thread";
private const string ATTR_DOMAIN = "domain";
private const string ATTR_IDENTITY = "identity";
private const string ATTR_USERNAME = "username";
private const string ATTR_CLASS = "class";
private const string ATTR_METHOD = "method";
private const string ATTR_FILE = "file";
private const string ATTR_LINE = "line";
private const string ATTR_NAME = "name";
private const string ATTR_VALUE = "value";
#endregion Private Static Fields
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace DocuSign.eSign.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public class FolderItemResponse : IEquatable<FolderItemResponse>
{
/// <summary>
/// The number of results returned in this response.
/// </summary>
/// <value>The number of results returned in this response.</value>
[DataMember(Name="resultSetSize", EmitDefaultValue=false)]
public string ResultSetSize { get; set; }
/// <summary>
/// Starting position of the current result set.
/// </summary>
/// <value>Starting position of the current result set.</value>
[DataMember(Name="startPosition", EmitDefaultValue=false)]
public string StartPosition { get; set; }
/// <summary>
/// The last position in the result set.
/// </summary>
/// <value>The last position in the result set.</value>
[DataMember(Name="endPosition", EmitDefaultValue=false)]
public string EndPosition { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="totalRows", EmitDefaultValue=false)]
public string TotalRows { get; set; }
/// <summary>
/// The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null.
/// </summary>
/// <value>The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null.</value>
[DataMember(Name="nextUri", EmitDefaultValue=false)]
public string NextUri { get; set; }
/// <summary>
/// The postal code for the billing address.
/// </summary>
/// <value>The postal code for the billing address.</value>
[DataMember(Name="previousUri", EmitDefaultValue=false)]
public string PreviousUri { get; set; }
/// <summary>
/// A list of the envelopes in the specified folder or folders.
/// </summary>
/// <value>A list of the envelopes in the specified folder or folders.</value>
[DataMember(Name="folderItems", EmitDefaultValue=false)]
public List<FolderItemV2> FolderItems { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class FolderItemResponse {\n");
sb.Append(" ResultSetSize: ").Append(ResultSetSize).Append("\n");
sb.Append(" StartPosition: ").Append(StartPosition).Append("\n");
sb.Append(" EndPosition: ").Append(EndPosition).Append("\n");
sb.Append(" TotalRows: ").Append(TotalRows).Append("\n");
sb.Append(" NextUri: ").Append(NextUri).Append("\n");
sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n");
sb.Append(" FolderItems: ").Append(FolderItems).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as FolderItemResponse);
}
/// <summary>
/// Returns true if FolderItemResponse instances are equal
/// </summary>
/// <param name="other">Instance of FolderItemResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(FolderItemResponse other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.ResultSetSize == other.ResultSetSize ||
this.ResultSetSize != null &&
this.ResultSetSize.Equals(other.ResultSetSize)
) &&
(
this.StartPosition == other.StartPosition ||
this.StartPosition != null &&
this.StartPosition.Equals(other.StartPosition)
) &&
(
this.EndPosition == other.EndPosition ||
this.EndPosition != null &&
this.EndPosition.Equals(other.EndPosition)
) &&
(
this.TotalRows == other.TotalRows ||
this.TotalRows != null &&
this.TotalRows.Equals(other.TotalRows)
) &&
(
this.NextUri == other.NextUri ||
this.NextUri != null &&
this.NextUri.Equals(other.NextUri)
) &&
(
this.PreviousUri == other.PreviousUri ||
this.PreviousUri != null &&
this.PreviousUri.Equals(other.PreviousUri)
) &&
(
this.FolderItems == other.FolderItems ||
this.FolderItems != null &&
this.FolderItems.SequenceEqual(other.FolderItems)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.ResultSetSize != null)
hash = hash * 57 + this.ResultSetSize.GetHashCode();
if (this.StartPosition != null)
hash = hash * 57 + this.StartPosition.GetHashCode();
if (this.EndPosition != null)
hash = hash * 57 + this.EndPosition.GetHashCode();
if (this.TotalRows != null)
hash = hash * 57 + this.TotalRows.GetHashCode();
if (this.NextUri != null)
hash = hash * 57 + this.NextUri.GetHashCode();
if (this.PreviousUri != null)
hash = hash * 57 + this.PreviousUri.GetHashCode();
if (this.FolderItems != null)
hash = hash * 57 + this.FolderItems.GetHashCode();
return hash;
}
}
}
}
| |
using System;
using Org.BouncyCastle.Crypto.Parameters;
namespace Org.BouncyCastle.Crypto.Engines
{
/**
* The specification for RC5 came from the <code>RC5 Encryption Algorithm</code>
* publication in RSA CryptoBytes, Spring of 1995.
* <em>http://www.rsasecurity.com/rsalabs/cryptobytes</em>.
* <p>
* This implementation is set to work with a 64 bit word size.</p>
*/
public class RC564Engine
: IBlockCipher
{
private static readonly int wordSize = 64;
private static readonly int bytesPerWord = wordSize / 8;
/*
* the number of rounds to perform
*/
private int _noRounds;
/*
* the expanded key array of size 2*(rounds + 1)
*/
private long [] _S;
/*
* our "magic constants" for wordSize 62
*
* Pw = Odd((e-2) * 2^wordsize)
* Qw = Odd((o-2) * 2^wordsize)
*
* where e is the base of natural logarithms (2.718281828...)
* and o is the golden ratio (1.61803398...)
*/
private static readonly long P64 = unchecked( (long) 0xb7e151628aed2a6bL);
private static readonly long Q64 = unchecked( (long) 0x9e3779b97f4a7c15L);
private bool forEncryption;
/**
* Create an instance of the RC5 encryption algorithm
* and set some defaults
*/
public RC564Engine()
{
_noRounds = 12;
// _S = null;
}
public string AlgorithmName
{
get { return "RC5-64"; }
}
public bool IsPartialBlockOkay
{
get { return false; }
}
public int GetBlockSize()
{
return 2 * bytesPerWord;
}
/**
* initialise a RC5-64 cipher.
*
* @param forEncryption whether or not we are for encryption.
* @param parameters the parameters required to set up the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (!(typeof(RC5Parameters).IsInstanceOfType(parameters)))
{
throw new ArgumentException("invalid parameter passed to RC564 init - " + parameters.GetType().ToString());
}
RC5Parameters p = (RC5Parameters)parameters;
this.forEncryption = forEncryption;
_noRounds = p.Rounds;
SetKey(p.GetKey());
}
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
return (forEncryption) ? EncryptBlock(input, inOff, output, outOff)
: DecryptBlock(input, inOff, output, outOff);
}
public void Reset()
{
}
/**
* Re-key the cipher.
*
* @param key the key to be used
*/
private void SetKey(
byte[] key)
{
//
// KEY EXPANSION:
//
// There are 3 phases to the key expansion.
//
// Phase 1:
// Copy the secret key K[0...b-1] into an array L[0..c-1] of
// c = ceil(b/u), where u = wordSize/8 in little-endian order.
// In other words, we fill up L using u consecutive key bytes
// of K. Any unfilled byte positions in L are zeroed. In the
// case that b = c = 0, set c = 1 and L[0] = 0.
//
long[] L = new long[(key.Length + (bytesPerWord - 1)) / bytesPerWord];
for (int i = 0; i != key.Length; i++)
{
L[i / bytesPerWord] += (long)(key[i] & 0xff) << (8 * (i % bytesPerWord));
}
//
// Phase 2:
// Initialize S to a particular fixed pseudo-random bit pattern
// using an arithmetic progression modulo 2^wordsize determined
// by the magic numbers, Pw & Qw.
//
_S = new long[2*(_noRounds + 1)];
_S[0] = P64;
for (int i=1; i < _S.Length; i++)
{
_S[i] = (_S[i-1] + Q64);
}
//
// Phase 3:
// Mix in the user's secret key in 3 passes over the arrays S & L.
// The max of the arrays sizes is used as the loop control
//
int iter;
if (L.Length > _S.Length)
{
iter = 3 * L.Length;
}
else
{
iter = 3 * _S.Length;
}
long A = 0, B = 0;
int ii = 0, jj = 0;
for (int k = 0; k < iter; k++)
{
A = _S[ii] = RotateLeft(_S[ii] + A + B, 3);
B = L[jj] = RotateLeft( L[jj] + A + B, A+B);
ii = (ii+1) % _S.Length;
jj = (jj+1) % L.Length;
}
}
/**
* Encrypt the given block starting at the given offset and place
* the result in the provided buffer starting at the given offset.
*
* @param in in byte buffer containing data to encrypt
* @param inOff offset into src buffer
* @param out out buffer where encrypted data is written
* @param outOff offset into out buffer
*/
private int EncryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
long A = BytesToWord(input, inOff) + _S[0];
long B = BytesToWord(input, inOff + bytesPerWord) + _S[1];
for (int i = 1; i <= _noRounds; i++)
{
A = RotateLeft(A ^ B, B) + _S[2*i];
B = RotateLeft(B ^ A, A) + _S[2*i+1];
}
WordToBytes(A, outBytes, outOff);
WordToBytes(B, outBytes, outOff + bytesPerWord);
return 2 * bytesPerWord;
}
private int DecryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
long A = BytesToWord(input, inOff);
long B = BytesToWord(input, inOff + bytesPerWord);
for (int i = _noRounds; i >= 1; i--)
{
B = RotateRight(B - _S[2*i+1], A) ^ A;
A = RotateRight(A - _S[2*i], B) ^ B;
}
WordToBytes(A - _S[0], outBytes, outOff);
WordToBytes(B - _S[1], outBytes, outOff + bytesPerWord);
return 2 * bytesPerWord;
}
//////////////////////////////////////////////////////////////
//
// PRIVATE Helper Methods
//
//////////////////////////////////////////////////////////////
/**
* Perform a left "spin" of the word. The rotation of the given
* word <em>x</em> is rotated left by <em>y</em> bits.
* Only the <em>lg(wordSize)</em> low-order bits of <em>y</em>
* are used to determine the rotation amount. Here it is
* assumed that the wordsize used is a power of 2.
*
* @param x word to rotate
* @param y number of bits to rotate % wordSize
*/
private long RotateLeft(long x, long y) {
return ((long) ( (ulong) (x << (int) (y & (wordSize-1))) |
((ulong) x >> (int) (wordSize - (y & (wordSize-1)))))
);
}
/**
* Perform a right "spin" of the word. The rotation of the given
* word <em>x</em> is rotated left by <em>y</em> bits.
* Only the <em>lg(wordSize)</em> low-order bits of <em>y</em>
* are used to determine the rotation amount. Here it is
* assumed that the wordsize used is a power of 2.
*
* @param x word to rotate
* @param y number of bits to rotate % wordSize
*/
private long RotateRight(long x, long y) {
return ((long) ( ((ulong) x >> (int) (y & (wordSize-1))) |
(ulong) (x << (int) (wordSize - (y & (wordSize-1)))))
);
}
private long BytesToWord(
byte[] src,
int srcOff)
{
long word = 0;
for (int i = bytesPerWord - 1; i >= 0; i--)
{
word = (word << 8) + (src[i + srcOff] & 0xff);
}
return word;
}
private void WordToBytes(
long word,
byte[] dst,
int dstOff)
{
for (int i = 0; i < bytesPerWord; i++)
{
dst[i + dstOff] = (byte)word;
word = (long) ((ulong) word >> 8);
}
}
}
}
| |
/*
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.Windows.Forms;
using System.Drawing;
using ESRI.ArcGIS.PublisherControls;
namespace Query
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class SpatialQuery : System.Windows.Forms.Form
{
public System.Windows.Forms.Button cmdQuery;
public System.Windows.Forms.Button cmdFullExtent;
public System.Windows.Forms.RadioButton optTool2;
public System.Windows.Forms.RadioButton optTool1;
public System.Windows.Forms.RadioButton optTool0;
public System.Windows.Forms.Button cmdLoad;
public System.Windows.Forms.GroupBox Frame1;
public System.Windows.Forms.Button cmdFeatureSet1;
public System.Windows.Forms.Button cmdFeature3;
public System.Windows.Forms.Button cmdFeature2;
public System.Windows.Forms.Button cmdFeature1;
public System.Windows.Forms.Button cmdFeature0;
public System.Windows.Forms.Button cmdFeatureSet0;
public System.Windows.Forms.Label lblRecords;
public System.Windows.Forms.Label Label2;
public System.Windows.Forms.Label Label3;
public System.Windows.Forms.Label Label5;
public System.Windows.Forms.Label Label6;
private IARFeature m_feature;
private IARFeatureSet m_featureSet;
private bool m_queryFeatures;
private bool m_queryValues;
private int m_record;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private ESRI.ArcGIS.PublisherControls.AxArcReaderControl axArcReaderControl1;
private DataGridView dataGridView1;
private DataGridViewTextBoxColumn Column1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public SpatialQuery()
{
//
// 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()
{
this.cmdQuery = new System.Windows.Forms.Button();
this.cmdFullExtent = new System.Windows.Forms.Button();
this.optTool2 = new System.Windows.Forms.RadioButton();
this.optTool1 = new System.Windows.Forms.RadioButton();
this.optTool0 = new System.Windows.Forms.RadioButton();
this.cmdLoad = new System.Windows.Forms.Button();
this.Frame1 = new System.Windows.Forms.GroupBox();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.cmdFeatureSet1 = new System.Windows.Forms.Button();
this.cmdFeature3 = new System.Windows.Forms.Button();
this.cmdFeature2 = new System.Windows.Forms.Button();
this.cmdFeature1 = new System.Windows.Forms.Button();
this.cmdFeature0 = new System.Windows.Forms.Button();
this.cmdFeatureSet0 = new System.Windows.Forms.Button();
this.lblRecords = new System.Windows.Forms.Label();
this.Label2 = new System.Windows.Forms.Label();
this.Label3 = new System.Windows.Forms.Label();
this.Label5 = new System.Windows.Forms.Label();
this.Label6 = new System.Windows.Forms.Label();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.axArcReaderControl1 = new ESRI.ArcGIS.PublisherControls.AxArcReaderControl();
this.Frame1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axArcReaderControl1)).BeginInit();
this.SuspendLayout();
//
// cmdQuery
//
this.cmdQuery.BackColor = System.Drawing.SystemColors.Control;
this.cmdQuery.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdQuery.Enabled = false;
this.cmdQuery.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmdQuery.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdQuery.Location = new System.Drawing.Point(368, 8);
this.cmdQuery.Name = "cmdQuery";
this.cmdQuery.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdQuery.Size = new System.Drawing.Size(73, 49);
this.cmdQuery.TabIndex = 11;
this.cmdQuery.Text = "Spatial Query";
this.cmdQuery.UseVisualStyleBackColor = false;
this.cmdQuery.Click += new System.EventHandler(this.cmdQuery_Click);
//
// cmdFullExtent
//
this.cmdFullExtent.BackColor = System.Drawing.SystemColors.Control;
this.cmdFullExtent.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdFullExtent.Enabled = false;
this.cmdFullExtent.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmdFullExtent.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdFullExtent.ImageAlign = System.Drawing.ContentAlignment.BottomCenter;
this.cmdFullExtent.Location = new System.Drawing.Point(296, 8);
this.cmdFullExtent.Name = "cmdFullExtent";
this.cmdFullExtent.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdFullExtent.Size = new System.Drawing.Size(73, 49);
this.cmdFullExtent.TabIndex = 10;
this.cmdFullExtent.Text = "FullExtent";
this.cmdFullExtent.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this.cmdFullExtent.UseVisualStyleBackColor = false;
this.cmdFullExtent.Click += new System.EventHandler(this.cmdFullExtent_Click);
//
// optTool2
//
this.optTool2.Appearance = System.Windows.Forms.Appearance.Button;
this.optTool2.BackColor = System.Drawing.SystemColors.Control;
this.optTool2.Cursor = System.Windows.Forms.Cursors.Default;
this.optTool2.Enabled = false;
this.optTool2.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.optTool2.ForeColor = System.Drawing.SystemColors.ControlText;
this.optTool2.ImageAlign = System.Drawing.ContentAlignment.BottomCenter;
this.optTool2.Location = new System.Drawing.Point(224, 8);
this.optTool2.Name = "optTool2";
this.optTool2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.optTool2.Size = new System.Drawing.Size(73, 49);
this.optTool2.TabIndex = 9;
this.optTool2.TabStop = true;
this.optTool2.Text = "Pan";
this.optTool2.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this.optTool2.UseVisualStyleBackColor = false;
this.optTool2.Click += new System.EventHandler(this.CurrentTool_Click);
//
// optTool1
//
this.optTool1.Appearance = System.Windows.Forms.Appearance.Button;
this.optTool1.BackColor = System.Drawing.SystemColors.Control;
this.optTool1.Cursor = System.Windows.Forms.Cursors.Default;
this.optTool1.Enabled = false;
this.optTool1.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.optTool1.ForeColor = System.Drawing.SystemColors.ControlText;
this.optTool1.ImageAlign = System.Drawing.ContentAlignment.BottomCenter;
this.optTool1.Location = new System.Drawing.Point(152, 8);
this.optTool1.Name = "optTool1";
this.optTool1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.optTool1.Size = new System.Drawing.Size(73, 49);
this.optTool1.TabIndex = 8;
this.optTool1.TabStop = true;
this.optTool1.Text = "ZoomOut";
this.optTool1.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this.optTool1.UseVisualStyleBackColor = false;
this.optTool1.Click += new System.EventHandler(this.CurrentTool_Click);
//
// optTool0
//
this.optTool0.Appearance = System.Windows.Forms.Appearance.Button;
this.optTool0.BackColor = System.Drawing.SystemColors.Control;
this.optTool0.Cursor = System.Windows.Forms.Cursors.Default;
this.optTool0.Enabled = false;
this.optTool0.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.optTool0.ForeColor = System.Drawing.SystemColors.ControlText;
this.optTool0.ImageAlign = System.Drawing.ContentAlignment.BottomCenter;
this.optTool0.Location = new System.Drawing.Point(80, 8);
this.optTool0.Name = "optTool0";
this.optTool0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.optTool0.Size = new System.Drawing.Size(73, 49);
this.optTool0.TabIndex = 7;
this.optTool0.TabStop = true;
this.optTool0.Text = "ZoomIn";
this.optTool0.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this.optTool0.UseVisualStyleBackColor = false;
this.optTool0.Click += new System.EventHandler(this.CurrentTool_Click);
//
// cmdLoad
//
this.cmdLoad.BackColor = System.Drawing.SystemColors.Control;
this.cmdLoad.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdLoad.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmdLoad.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdLoad.ImageAlign = System.Drawing.ContentAlignment.BottomCenter;
this.cmdLoad.Location = new System.Drawing.Point(8, 8);
this.cmdLoad.Name = "cmdLoad";
this.cmdLoad.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdLoad.Size = new System.Drawing.Size(73, 49);
this.cmdLoad.TabIndex = 6;
this.cmdLoad.Text = "Open";
this.cmdLoad.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this.cmdLoad.UseVisualStyleBackColor = false;
this.cmdLoad.Click += new System.EventHandler(this.cmdLoad_Click);
//
// Frame1
//
this.Frame1.BackColor = System.Drawing.SystemColors.Control;
this.Frame1.Controls.Add(this.dataGridView1);
this.Frame1.Controls.Add(this.cmdFeatureSet1);
this.Frame1.Controls.Add(this.cmdFeature3);
this.Frame1.Controls.Add(this.cmdFeature2);
this.Frame1.Controls.Add(this.cmdFeature1);
this.Frame1.Controls.Add(this.cmdFeature0);
this.Frame1.Controls.Add(this.cmdFeatureSet0);
this.Frame1.Controls.Add(this.lblRecords);
this.Frame1.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Frame1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Frame1.Location = new System.Drawing.Point(448, 128);
this.Frame1.Name = "Frame1";
this.Frame1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Frame1.Size = new System.Drawing.Size(241, 369);
this.Frame1.TabIndex = 19;
this.Frame1.TabStop = false;
//
// dataGridView1
//
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AllowUserToDeleteRows = false;
this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
this.dataGridView1.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells;
this.dataGridView1.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.ColumnHeadersVisible = false;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Column1});
this.dataGridView1.EditMode = System.Windows.Forms.DataGridViewEditMode.EditProgrammatically;
this.dataGridView1.Location = new System.Drawing.Point(3, 62);
this.dataGridView1.MultiSelect = false;
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.ReadOnly = true;
this.dataGridView1.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect;
this.dataGridView1.ShowEditingIcon = false;
this.dataGridView1.Size = new System.Drawing.Size(233, 260);
this.dataGridView1.TabIndex = 25;
//
// Column1
//
this.Column1.HeaderText = "Column1";
this.Column1.Name = "Column1";
this.Column1.ReadOnly = true;
this.Column1.Width = 5;
//
// cmdFeatureSet1
//
this.cmdFeatureSet1.BackColor = System.Drawing.SystemColors.Control;
this.cmdFeatureSet1.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdFeatureSet1.Enabled = false;
this.cmdFeatureSet1.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmdFeatureSet1.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdFeatureSet1.Location = new System.Drawing.Point(120, 16);
this.cmdFeatureSet1.Name = "cmdFeatureSet1";
this.cmdFeatureSet1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdFeatureSet1.Size = new System.Drawing.Size(113, 25);
this.cmdFeatureSet1.TabIndex = 14;
this.cmdFeatureSet1.Text = "<< Previous Feature";
this.cmdFeatureSet1.UseVisualStyleBackColor = false;
this.cmdFeatureSet1.Click += new System.EventHandler(this.cmdFeatureSet_Click);
//
// cmdFeature3
//
this.cmdFeature3.BackColor = System.Drawing.SystemColors.Control;
this.cmdFeature3.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdFeature3.Enabled = false;
this.cmdFeature3.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmdFeature3.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdFeature3.Location = new System.Drawing.Point(176, 328);
this.cmdFeature3.Name = "cmdFeature3";
this.cmdFeature3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdFeature3.Size = new System.Drawing.Size(57, 33);
this.cmdFeature3.TabIndex = 11;
this.cmdFeature3.Text = "Flicker";
this.cmdFeature3.UseVisualStyleBackColor = false;
this.cmdFeature3.Click += new System.EventHandler(this.cmdFeature_Click);
//
// cmdFeature2
//
this.cmdFeature2.BackColor = System.Drawing.SystemColors.Control;
this.cmdFeature2.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdFeature2.Enabled = false;
this.cmdFeature2.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmdFeature2.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdFeature2.Location = new System.Drawing.Point(120, 328);
this.cmdFeature2.Name = "cmdFeature2";
this.cmdFeature2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdFeature2.Size = new System.Drawing.Size(57, 33);
this.cmdFeature2.TabIndex = 10;
this.cmdFeature2.Text = "Flash";
this.cmdFeature2.UseVisualStyleBackColor = false;
this.cmdFeature2.Click += new System.EventHandler(this.cmdFeature_Click);
//
// cmdFeature1
//
this.cmdFeature1.BackColor = System.Drawing.SystemColors.Control;
this.cmdFeature1.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdFeature1.Enabled = false;
this.cmdFeature1.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmdFeature1.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdFeature1.Location = new System.Drawing.Point(64, 328);
this.cmdFeature1.Name = "cmdFeature1";
this.cmdFeature1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdFeature1.Size = new System.Drawing.Size(57, 33);
this.cmdFeature1.TabIndex = 9;
this.cmdFeature1.Text = "CenterAt";
this.cmdFeature1.UseVisualStyleBackColor = false;
this.cmdFeature1.Click += new System.EventHandler(this.cmdFeature_Click);
//
// cmdFeature0
//
this.cmdFeature0.BackColor = System.Drawing.SystemColors.Control;
this.cmdFeature0.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdFeature0.Enabled = false;
this.cmdFeature0.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmdFeature0.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdFeature0.Location = new System.Drawing.Point(8, 328);
this.cmdFeature0.Name = "cmdFeature0";
this.cmdFeature0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdFeature0.Size = new System.Drawing.Size(57, 33);
this.cmdFeature0.TabIndex = 8;
this.cmdFeature0.Text = "ZoomTo";
this.cmdFeature0.UseVisualStyleBackColor = false;
this.cmdFeature0.Click += new System.EventHandler(this.cmdFeature_Click);
//
// cmdFeatureSet0
//
this.cmdFeatureSet0.BackColor = System.Drawing.SystemColors.Control;
this.cmdFeatureSet0.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdFeatureSet0.Enabled = false;
this.cmdFeatureSet0.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmdFeatureSet0.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdFeatureSet0.Location = new System.Drawing.Point(8, 16);
this.cmdFeatureSet0.Name = "cmdFeatureSet0";
this.cmdFeatureSet0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdFeatureSet0.Size = new System.Drawing.Size(113, 25);
this.cmdFeatureSet0.TabIndex = 7;
this.cmdFeatureSet0.Text = "Next Feature >>";
this.cmdFeatureSet0.UseVisualStyleBackColor = false;
this.cmdFeatureSet0.Click += new System.EventHandler(this.cmdFeatureSet_Click);
//
// lblRecords
//
this.lblRecords.BackColor = System.Drawing.SystemColors.Control;
this.lblRecords.Cursor = System.Windows.Forms.Cursors.Default;
this.lblRecords.Enabled = false;
this.lblRecords.Font = new System.Drawing.Font("Arial", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblRecords.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblRecords.Location = new System.Drawing.Point(8, 48);
this.lblRecords.Name = "lblRecords";
this.lblRecords.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblRecords.Size = new System.Drawing.Size(225, 17);
this.lblRecords.TabIndex = 13;
this.lblRecords.Text = "0 of 0 features";
//
// Label2
//
this.Label2.BackColor = System.Drawing.SystemColors.Control;
this.Label2.Cursor = System.Windows.Forms.Cursors.Default;
this.Label2.Font = new System.Drawing.Font("Verdana", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Label2.ForeColor = System.Drawing.SystemColors.Highlight;
this.Label2.Location = new System.Drawing.Point(448, 8);
this.Label2.Name = "Label2";
this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label2.Size = new System.Drawing.Size(249, 17);
this.Label2.TabIndex = 23;
this.Label2.Text = "1) Browse to a PMF to load.";
//
// Label3
//
this.Label3.BackColor = System.Drawing.SystemColors.Control;
this.Label3.Cursor = System.Windows.Forms.Cursors.Default;
this.Label3.Font = new System.Drawing.Font("Verdana", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Label3.ForeColor = System.Drawing.SystemColors.Highlight;
this.Label3.Location = new System.Drawing.Point(448, 24);
this.Label3.Name = "Label3";
this.Label3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label3.Size = new System.Drawing.Size(249, 17);
this.Label3.TabIndex = 22;
this.Label3.Text = "2) Navigate to some features of interest. ";
//
// Label5
//
this.Label5.BackColor = System.Drawing.SystemColors.Control;
this.Label5.Cursor = System.Windows.Forms.Cursors.Default;
this.Label5.Font = new System.Drawing.Font("Verdana", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Label5.ForeColor = System.Drawing.SystemColors.Highlight;
this.Label5.Location = new System.Drawing.Point(448, 72);
this.Label5.Name = "Label5";
this.Label5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label5.Size = new System.Drawing.Size(225, 56);
this.Label5.TabIndex = 21;
this.Label5.Text = "4) Loop through the features to display field values and use the buttons to ident" +
"ify each feature on the map.";
//
// Label6
//
this.Label6.BackColor = System.Drawing.SystemColors.Control;
this.Label6.Cursor = System.Windows.Forms.Cursors.Default;
this.Label6.Font = new System.Drawing.Font("Verdana", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Label6.ForeColor = System.Drawing.SystemColors.Highlight;
this.Label6.Location = new System.Drawing.Point(448, 48);
this.Label6.Name = "Label6";
this.Label6.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label6.Size = new System.Drawing.Size(249, 30);
this.Label6.TabIndex = 20;
this.Label6.Text = "3) Query the focus map for all visible features within the current map extent. ";
//
// axArcReaderControl1
//
this.axArcReaderControl1.Location = new System.Drawing.Point(8, 64);
this.axArcReaderControl1.Name = "axArcReaderControl1";
this.axArcReaderControl1.Size = new System.Drawing.Size(432, 424);
this.axArcReaderControl1.TabIndex = 24;
this.axArcReaderControl1.OnCurrentViewChanged += new ESRI.ArcGIS.PublisherControls.IARControlEvents_Ax_OnCurrentViewChangedEventHandler(this.axArcReaderControl1_OnCurrentViewChanged);
//
// SpatialQuery
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(696, 502);
this.Controls.Add(this.axArcReaderControl1);
this.Controls.Add(this.Frame1);
this.Controls.Add(this.Label2);
this.Controls.Add(this.Label3);
this.Controls.Add(this.Label5);
this.Controls.Add(this.Label6);
this.Controls.Add(this.cmdQuery);
this.Controls.Add(this.cmdFullExtent);
this.Controls.Add(this.optTool2);
this.Controls.Add(this.optTool1);
this.Controls.Add(this.optTool0);
this.Controls.Add(this.cmdLoad);
this.Name = "SpatialQuery";
this.Text = "SpatialQuery";
this.Load += new System.EventHandler(this.Form1_Load);
this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
this.Frame1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axArcReaderControl1)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
if (!ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.ArcReader))
{
if (!ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.EngineOrDesktop))
{
MessageBox.Show("Unable to bind to ArcGIS runtime. Application will be shut down.");
return;
}
}
Application.Run(new SpatialQuery());
}
private void Form1_Load(object sender, System.EventArgs e)
{
//Load command button images from the resource editor
System.Drawing.Bitmap bitmap1 = new System.Drawing.Bitmap (GetType().Assembly.GetManifestResourceStream(GetType(), "browse.bmp"));
bitmap1.MakeTransparent(System.Drawing.Color.Teal);
cmdLoad.Image = bitmap1;
System.Drawing.Bitmap bitmap2 = new System.Drawing.Bitmap (GetType().Assembly.GetManifestResourceStream(GetType(), "ZoomIn.bmp"));
bitmap2.MakeTransparent(System.Drawing.Color.Teal);
optTool0.Image = bitmap2;
System.Drawing.Bitmap bitmap3 = new System.Drawing.Bitmap (GetType().Assembly.GetManifestResourceStream(GetType(), "ZoomOut.bmp"));
bitmap3.MakeTransparent(System.Drawing.Color.Teal);
optTool1.Image = bitmap3;
System.Drawing.Bitmap bitmap4 = new System.Drawing.Bitmap (GetType().Assembly.GetManifestResourceStream(GetType(), "Pan.bmp"));
bitmap4.MakeTransparent(System.Drawing.Color.Teal);
optTool2.Image = bitmap4;
System.Drawing.Bitmap bitmap5 = new System.Drawing.Bitmap (GetType().Assembly.GetManifestResourceStream(GetType(), "FullExtent.bmp"));
bitmap5.MakeTransparent(System.Drawing.Color.Teal);
cmdFullExtent.Image = bitmap5;
}
private void cmdFeature_Click(object sender, System.EventArgs e)
{
Button b = (Button) sender;
//Navigate or show the selected feature
switch (b.Name)
{
case "cmdFeature0":
m_feature.ZoomTo();
break;
case "cmdFeature1":
m_feature.CenterAt();
break;
case "cmdFeature2":
m_feature.Flash();
break;
case "cmdFeature3":
m_feature.Flicker();
break;
}
}
private void cmdFeatureSet_Click(object sender, System.EventArgs e)
{
Button b = (Button) sender;
switch (b.Name)
{
case "cmdFeatureSet0":
//Next record
m_record = m_record + 1;
break;
case "cmdFeatureSet1":
//Previous record
m_record = m_record - 1;
break;
}
//Get the next/previous feature
m_feature = m_featureSet.get_ARFeature(m_record);
//Display attribute values
UpdateValueDisplay();
}
private void cmdFullExtent_Click(object sender, System.EventArgs e)
{
double dXmax=0; double dXmin=0; double dYmin=0; double dYmax=0;
//Get the coordinates of data's full extent
axArcReaderControl1.ARPageLayout.FocusARMap.GetFullExtent(ref dXmin, ref dYmin, ref dXmax, ref dYmax);
//Set the extent of the focus map
axArcReaderControl1.ARPageLayout.FocusARMap.SetExtent(dXmin, dYmin, dXmax, dYmax);
//Refresh the display
axArcReaderControl1.ARPageLayout.FocusARMap.Refresh(true);
}
private void cmdLoad_Click(object sender, System.EventArgs e)
{
//Open a file dialog for selecting map documents
openFileDialog1.Title = "Select Published Map Document";
openFileDialog1.Filter = "Published Map Documents (*.pmf)|*.pmf";
openFileDialog1.ShowDialog();
//Exit if no map document is selected
string sFilePath = openFileDialog1.FileName;
if (sFilePath == "") return;
//Load the specified pmf
if (axArcReaderControl1.CheckDocument(sFilePath) == true)
{
axArcReaderControl1.LoadDocument(sFilePath,"");
}
else
{
System.Windows.Forms.MessageBox.Show("This document cannot be loaded!");
return;
}
//Determine whether permission to search layers and query field values
m_queryFeatures = axArcReaderControl1.HasDocumentPermission(esriARDocumentPermissions.esriARDocumentPermissionsQueryFeatures);
m_queryValues = axArcReaderControl1.HasDocumentPermission(esriARDocumentPermissions.esriARDocumentPermissionsQueryValues);
//Set current tool
optTool0.Checked = true;
}
private void cmdQuery_Click(object sender, System.EventArgs e)
{
//Determine whether permission to search layers
if (m_queryFeatures == false)
{
System.Windows.Forms.MessageBox.Show("You do not have permission to search for features!");
return;
}
//Get IARQueryDef interface
ArcReaderSearchDefClass searchDef = new ArcReaderSearchDefClass();
//Set the spatial searching to intersects
searchDef.SpatialRelationship = esriARSpatialRelationship.esriARSpatialRelationshipIntersects;
//Get the coordinates of the current extent
double dXmax=0; double dXmin=0; double dYmin=0; double dYmax=0;
axArcReaderControl1.ARPageLayout.FocusARMap.GetExtent(ref dXmin, ref dYmin, ref dXmax, ref dYmax);
//Set the envelope coordinates as the search shape
searchDef.SetEnvelopeShape(dXmin, dYmin, dXmax, dYmax,0);
//Get IARFeatureSet interface
m_featureSet = axArcReaderControl1.ARPageLayout.FocusARMap.QueryARFeatures(searchDef);
//Reset the featureset
m_featureSet.Reset();
//Get the IARFeature interface
m_feature = m_featureSet.Next();
//Display attribute values
m_record = 0;
UpdateValueDisplay();
}
private void CurrentTool_Click(object sender, System.EventArgs e)
{
RadioButton b = (RadioButton) sender;
//Navigate or show the selected feature
switch (b.Name)
{
//Set current tool
case "optTool0":
axArcReaderControl1.CurrentARTool = esriARTool.esriARToolMapZoomIn;
break;
case "optTool1":
axArcReaderControl1.CurrentARTool = esriARTool.esriARToolMapZoomOut;
break;
case "optTool2":
axArcReaderControl1.CurrentARTool = esriARTool.esriARToolMapPan;
break;
}
}
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
//Release COM objects
ESRI.ArcGIS.ADF.COMSupport.AOUninitialize.Shutdown();
}
private void axArcReaderControl1_OnCurrentViewChanged(object sender, ESRI.ArcGIS.PublisherControls.IARControlEvents_OnCurrentViewChangedEvent e)
{
bool enabled;
//Set the current tool
if (axArcReaderControl1.CurrentViewType == esriARViewType.esriARViewTypeNone)
{
enabled = false;
}
else if (axArcReaderControl1.CurrentViewType == esriARViewType.esriARViewTypePageLayout)
{
enabled = false;
if (axArcReaderControl1.CurrentARTool != esriARTool.esriARToolNoneSelected)
{
axArcReaderControl1.CurrentARTool = esriARTool.esriARToolNoneSelected;
}
}
else
{
enabled = true;
if (axArcReaderControl1.CurrentARTool != esriARTool.esriARToolMapZoomIn)
{
optTool0.Checked = true;
}
}
//Enable\disable controls
cmdQuery.Enabled = enabled;
optTool0.Enabled = enabled;
optTool1.Enabled = enabled;
optTool2.Enabled = enabled;
cmdFullExtent.Enabled = enabled;
}
private void UpdateValueDisplay()
{
Graphics graphics = this.CreateGraphics();
dataGridView1.Rows.Clear();
//For each field that isn't the 'Shape' field
int iRow=0;
string fieldName; string fieldValue;
for (int i = 0; i<= m_feature.FieldCount - 1; i++)
{
if (m_feature.get_FieldType(i) != esriARFieldType.esriARFieldTypeGeometry & (m_feature.get_FieldType(i) != esriARFieldType.esriARFieldTypeRaster) & (m_feature.get_FieldType(i) != esriARFieldType.esriARFieldTypeBlob))
{
DataGridViewRow dataGridViewRow = new DataGridViewRow();
//Display field names
fieldName = m_feature.get_FieldAliasName(i);
dataGridViewRow.HeaderCell.Value = fieldName;
//display field values
if (m_queryValues == true)
{
fieldValue = m_feature.get_ValueAsString(i);
}
else
{
fieldValue = "No Permission";
}
DataGridViewCell cell = new DataGridViewTextBoxCell();
cell.Value = fieldValue;
dataGridViewRow.Cells.Add(cell);
dataGridView1.Rows.Add(dataGridViewRow);
iRow = iRow + 1;
}
}
//Enabled/disbale controls
bool enabled;
if( m_featureSet.ARFeatureCount == 0)
{
enabled = false;
cmdFeatureSet0.Enabled = false;
cmdFeatureSet1.Enabled = false;
lblRecords.Text = m_record + " of " + m_featureSet.ARFeatureCount;
}
else if (m_featureSet.ARFeatureCount == 1)
{
enabled = true;
cmdFeatureSet0.Enabled = false;
cmdFeatureSet1.Enabled = false;
lblRecords.Text = m_record + 1 + " of " + m_featureSet.ARFeatureCount;
}
else
{
enabled = true;
if (m_record == 0)
{
cmdFeatureSet1.Enabled = false;
}
else
{
cmdFeatureSet1.Enabled = true;
}
if (m_record + 1 == m_featureSet.ARFeatureCount)
{
cmdFeatureSet0.Enabled = false;
}
else
{
cmdFeatureSet0.Enabled = true;
}
lblRecords.Text = m_record + 1 + " of " + m_featureSet.ARFeatureCount;
}
cmdFeature0.Enabled = enabled;
cmdFeature1.Enabled = enabled;
cmdFeature2.Enabled = enabled;
cmdFeature3.Enabled = enabled;
//Clean up the Graphics object
graphics.Dispose();
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="MaterialCollection.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.Collections;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Markup;
using System.Windows.Media.Media3D.Converters;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using System.Windows.Media.Imaging;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;
namespace System.Windows.Media.Media3D
{
/// <summary>
/// A collection of Material objects.
/// </summary>
public sealed partial class MaterialCollection : Animatable, IList, IList<Material>
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new MaterialCollection Clone()
{
return (MaterialCollection)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new MaterialCollection CloneCurrentValue()
{
return (MaterialCollection)base.CloneCurrentValue();
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region IList<T>
/// <summary>
/// Adds "value" to the list
/// </summary>
public void Add(Material value)
{
AddHelper(value);
}
/// <summary>
/// Removes all elements from the list
/// </summary>
public void Clear()
{
WritePreamble();
// As part of Clear()'ing the collection, we will iterate it and call
// OnFreezablePropertyChanged and OnRemove for each item.
// However, OnRemove assumes that the item to be removed has already been
// pulled from the underlying collection. To statisfy this condition,
// we store the old collection and clear _collection before we call these methods.
// As Clear() semantics do not include TrimToFit behavior, we create the new
// collection storage at the same size as the previous. This is to provide
// as close as possible the same perf characteristics as less complicated collections.
FrugalStructList<Material> oldCollection = _collection;
_collection = new FrugalStructList<Material>(_collection.Capacity);
for (int i = oldCollection.Count - 1; i >= 0; i--)
{
OnFreezablePropertyChanged(/* oldValue = */ oldCollection[i], /* newValue = */ null);
// Fire the OnRemove handlers for each item. We're not ensuring that
// all OnRemove's get called if a resumable exception is thrown.
// At this time, these call-outs are not public, so we do not handle exceptions.
OnRemove( /* oldValue */ oldCollection[i]);
}
++_version;
WritePostscript();
}
/// <summary>
/// Determines if the list contains "value"
/// </summary>
public bool Contains(Material value)
{
ReadPreamble();
return _collection.Contains(value);
}
/// <summary>
/// Returns the index of "value" in the list
/// </summary>
public int IndexOf(Material value)
{
ReadPreamble();
return _collection.IndexOf(value);
}
/// <summary>
/// Inserts "value" into the list at the specified position
/// </summary>
public void Insert(int index, Material value)
{
if (value == null)
{
throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull));
}
WritePreamble();
OnFreezablePropertyChanged(/* oldValue = */ null, /* newValue = */ value);
_collection.Insert(index, value);
OnInsert(value);
++_version;
WritePostscript();
}
/// <summary>
/// Removes "value" from the list
/// </summary>
public bool Remove(Material value)
{
WritePreamble();
// By design collections "succeed silently" if you attempt to remove an item
// not in the collection. Therefore we need to first verify the old value exists
// before calling OnFreezablePropertyChanged. Since we already need to locate
// the item in the collection we keep the index and use RemoveAt(...) to do
// the work. (Windows OS #1016178)
// We use the public IndexOf to guard our UIContext since OnFreezablePropertyChanged
// is only called conditionally. IList.IndexOf returns -1 if the value is not found.
int index = IndexOf(value);
if (index >= 0)
{
Material oldValue = _collection[index];
OnFreezablePropertyChanged(oldValue, null);
_collection.RemoveAt(index);
OnRemove(oldValue);
++_version;
WritePostscript();
return true;
}
// Collection_Remove returns true, calls WritePostscript,
// increments version, and does UpdateResource if it succeeds
return false;
}
/// <summary>
/// Removes the element at the specified index
/// </summary>
public void RemoveAt(int index)
{
RemoveAtWithoutFiringPublicEvents(index);
// RemoveAtWithoutFiringPublicEvents incremented the version
WritePostscript();
}
/// <summary>
/// Removes the element at the specified index without firing
/// the public Changed event.
/// The caller - typically a public method - is responsible for calling
/// WritePostscript if appropriate.
/// </summary>
internal void RemoveAtWithoutFiringPublicEvents(int index)
{
WritePreamble();
Material oldValue = _collection[ index ];
OnFreezablePropertyChanged(oldValue, null);
_collection.RemoveAt(index);
OnRemove(oldValue);
++_version;
// No WritePostScript to avoid firing the Changed event.
}
/// <summary>
/// Indexer for the collection
/// </summary>
public Material this[int index]
{
get
{
ReadPreamble();
return _collection[index];
}
set
{
if (value == null)
{
throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull));
}
WritePreamble();
if (!Object.ReferenceEquals(_collection[ index ], value))
{
Material oldValue = _collection[ index ];
OnFreezablePropertyChanged(oldValue, value);
_collection[ index ] = value;
OnSet(oldValue, value);
}
++_version;
WritePostscript();
}
}
#endregion
#region ICollection<T>
/// <summary>
/// The number of elements contained in the collection.
/// </summary>
public int Count
{
get
{
ReadPreamble();
return _collection.Count;
}
}
/// <summary>
/// Copies the elements of the collection into "array" starting at "index"
/// </summary>
public void CopyTo(Material[] array, int index)
{
ReadPreamble();
if (array == null)
{
throw new ArgumentNullException("array");
}
// This will not throw in the case that we are copying
// from an empty collection. This is consistent with the
// BCL Collection implementations. (Windows 1587365)
if (index < 0 || (index + _collection.Count) > array.Length)
{
throw new ArgumentOutOfRangeException("index");
}
_collection.CopyTo(array, index);
}
bool ICollection<Material>.IsReadOnly
{
get
{
ReadPreamble();
return IsFrozen;
}
}
#endregion
#region IEnumerable<T>
/// <summary>
/// Returns an enumerator for the collection
/// </summary>
public Enumerator GetEnumerator()
{
ReadPreamble();
return new Enumerator(this);
}
IEnumerator<Material> IEnumerable<Material>.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region IList
bool IList.IsReadOnly
{
get
{
return ((ICollection<Material>)this).IsReadOnly;
}
}
bool IList.IsFixedSize
{
get
{
ReadPreamble();
return IsFrozen;
}
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
// Forwards to typed implementation
this[index] = Cast(value);
}
}
int IList.Add(object value)
{
// Forward to typed helper
return AddHelper(Cast(value));
}
bool IList.Contains(object value)
{
return Contains(value as Material);
}
int IList.IndexOf(object value)
{
return IndexOf(value as Material);
}
void IList.Insert(int index, object value)
{
// Forward to IList<T> Insert
Insert(index, Cast(value));
}
void IList.Remove(object value)
{
Remove(value as Material);
}
#endregion
#region ICollection
void ICollection.CopyTo(Array array, int index)
{
ReadPreamble();
if (array == null)
{
throw new ArgumentNullException("array");
}
// This will not throw in the case that we are copying
// from an empty collection. This is consistent with the
// BCL Collection implementations. (Windows 1587365)
if (index < 0 || (index + _collection.Count) > array.Length)
{
throw new ArgumentOutOfRangeException("index");
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Get(SRID.Collection_BadRank));
}
// Elsewhere in the collection we throw an AE when the type is
// bad so we do it here as well to be consistent
try
{
int count = _collection.Count;
for (int i = 0; i < count; i++)
{
array.SetValue(_collection[i], index + i);
}
}
catch (InvalidCastException e)
{
throw new ArgumentException(SR.Get(SRID.Collection_BadDestArray, this.GetType().Name), e);
}
}
bool ICollection.IsSynchronized
{
get
{
ReadPreamble();
return IsFrozen || Dispatcher != null;
}
}
object ICollection.SyncRoot
{
get
{
ReadPreamble();
return this;
}
}
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region Internal Helpers
/// <summary>
/// A frozen empty MaterialCollection.
/// </summary>
internal static MaterialCollection Empty
{
get
{
if (s_empty == null)
{
MaterialCollection collection = new MaterialCollection();
collection.Freeze();
s_empty = collection;
}
return s_empty;
}
}
/// <summary>
/// Helper to return read only access.
/// </summary>
internal Material Internal_GetItem(int i)
{
return _collection[i];
}
/// <summary>
/// Freezable collections need to notify their contained Freezables
/// about the change in the InheritanceContext
/// </summary>
internal override void OnInheritanceContextChangedCore(EventArgs args)
{
base.OnInheritanceContextChangedCore(args);
for (int i=0; i<this.Count; i++)
{
DependencyObject inheritanceChild = _collection[i];
if (inheritanceChild!= null && inheritanceChild.InheritanceContext == this)
{
inheritanceChild.OnInheritanceContextChanged(args);
}
}
}
#endregion
#region Private Helpers
private Material Cast(object value)
{
if( value == null )
{
throw new System.ArgumentNullException("value");
}
if (!(value is Material))
{
throw new System.ArgumentException(SR.Get(SRID.Collection_BadType, this.GetType().Name, value.GetType().Name, "Material"));
}
return (Material) value;
}
// IList.Add returns int and IList<T>.Add does not. This
// is called by both Adds and IList<T>'s just ignores the
// integer
private int AddHelper(Material value)
{
int index = AddWithoutFiringPublicEvents(value);
// AddAtWithoutFiringPublicEvents incremented the version
WritePostscript();
return index;
}
internal int AddWithoutFiringPublicEvents(Material value)
{
int index = -1;
if (value == null)
{
throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull));
}
WritePreamble();
Material newValue = value;
OnFreezablePropertyChanged(/* oldValue = */ null, newValue);
index = _collection.Add(newValue);
OnInsert(newValue);
++_version;
// No WritePostScript to avoid firing the Changed event.
return index;
}
internal event ItemInsertedHandler ItemInserted;
internal event ItemRemovedHandler ItemRemoved;
private void OnInsert(object item)
{
if (ItemInserted != null)
{
ItemInserted(this, item);
}
}
private void OnRemove(object oldValue)
{
if (ItemRemoved != null)
{
ItemRemoved(this, oldValue);
}
}
private void OnSet(object oldValue, object newValue)
{
OnInsert(newValue);
OnRemove(oldValue);
}
#endregion Private Helpers
private static MaterialCollection s_empty;
#region Public Properties
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new MaterialCollection();
}
/// <summary>
/// Implementation of Freezable.CloneCore()
/// </summary>
protected override void CloneCore(Freezable source)
{
MaterialCollection sourceMaterialCollection = (MaterialCollection) source;
base.CloneCore(source);
int count = sourceMaterialCollection._collection.Count;
_collection = new FrugalStructList<Material>(count);
for (int i = 0; i < count; i++)
{
Material newValue = (Material) sourceMaterialCollection._collection[i].Clone();
OnFreezablePropertyChanged(/* oldValue = */ null, newValue);
_collection.Add(newValue);
OnInsert(newValue);
}
}
/// <summary>
/// Implementation of Freezable.CloneCurrentValueCore()
/// </summary>
protected override void CloneCurrentValueCore(Freezable source)
{
MaterialCollection sourceMaterialCollection = (MaterialCollection) source;
base.CloneCurrentValueCore(source);
int count = sourceMaterialCollection._collection.Count;
_collection = new FrugalStructList<Material>(count);
for (int i = 0; i < count; i++)
{
Material newValue = (Material) sourceMaterialCollection._collection[i].CloneCurrentValue();
OnFreezablePropertyChanged(/* oldValue = */ null, newValue);
_collection.Add(newValue);
OnInsert(newValue);
}
}
/// <summary>
/// Implementation of Freezable.GetAsFrozenCore()
/// </summary>
protected override void GetAsFrozenCore(Freezable source)
{
MaterialCollection sourceMaterialCollection = (MaterialCollection) source;
base.GetAsFrozenCore(source);
int count = sourceMaterialCollection._collection.Count;
_collection = new FrugalStructList<Material>(count);
for (int i = 0; i < count; i++)
{
Material newValue = (Material) sourceMaterialCollection._collection[i].GetAsFrozen();
OnFreezablePropertyChanged(/* oldValue = */ null, newValue);
_collection.Add(newValue);
OnInsert(newValue);
}
}
/// <summary>
/// Implementation of Freezable.GetCurrentValueAsFrozenCore()
/// </summary>
protected override void GetCurrentValueAsFrozenCore(Freezable source)
{
MaterialCollection sourceMaterialCollection = (MaterialCollection) source;
base.GetCurrentValueAsFrozenCore(source);
int count = sourceMaterialCollection._collection.Count;
_collection = new FrugalStructList<Material>(count);
for (int i = 0; i < count; i++)
{
Material newValue = (Material) sourceMaterialCollection._collection[i].GetCurrentValueAsFrozen();
OnFreezablePropertyChanged(/* oldValue = */ null, newValue);
_collection.Add(newValue);
OnInsert(newValue);
}
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>.
/// </summary>
protected override bool FreezeCore(bool isChecking)
{
bool canFreeze = base.FreezeCore(isChecking);
int count = _collection.Count;
for (int i = 0; i < count && canFreeze; i++)
{
canFreeze &= Freezable.Freeze(_collection[i], isChecking);
}
return canFreeze;
}
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal FrugalStructList<Material> _collection;
internal uint _version = 0;
#endregion Internal Fields
#region Enumerator
/// <summary>
/// Enumerates the items in a MaterialCollection
/// </summary>
public struct Enumerator : IEnumerator, IEnumerator<Material>
{
#region Constructor
internal Enumerator(MaterialCollection list)
{
Debug.Assert(list != null, "list may not be null.");
_list = list;
_version = list._version;
_index = -1;
_current = default(Material);
}
#endregion
#region Methods
void IDisposable.Dispose()
{
}
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next element,
/// false if the enumerator has passed the end of the collection.
/// </returns>
public bool MoveNext()
{
_list.ReadPreamble();
if (_version == _list._version)
{
if (_index > -2 && _index < _list._collection.Count - 1)
{
_current = _list._collection[++_index];
return true;
}
else
{
_index = -2; // -2 indicates "past the end"
return false;
}
}
else
{
throw new InvalidOperationException(SR.Get(SRID.Enumerator_CollectionChanged));
}
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the
/// first element in the collection.
/// </summary>
public void Reset()
{
_list.ReadPreamble();
if (_version == _list._version)
{
_index = -1;
}
else
{
throw new InvalidOperationException(SR.Get(SRID.Enumerator_CollectionChanged));
}
}
#endregion
#region Properties
object IEnumerator.Current
{
get
{
return this.Current;
}
}
/// <summary>
/// Current element
///
/// The behavior of IEnumerable<T>.Current is undefined
/// before the first MoveNext and after we have walked
/// off the end of the list. However, the IEnumerable.Current
/// contract requires that we throw exceptions
/// </summary>
public Material Current
{
get
{
if (_index > -1)
{
return _current;
}
else if (_index == -1)
{
throw new InvalidOperationException(SR.Get(SRID.Enumerator_NotStarted));
}
else
{
Debug.Assert(_index == -2, "expected -2, got " + _index + "\n");
throw new InvalidOperationException(SR.Get(SRID.Enumerator_ReachedEnd));
}
}
}
#endregion
#region Data
private Material _current;
private MaterialCollection _list;
private uint _version;
private int _index;
#endregion
}
#endregion
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
/// <summary>
/// Initializes a new instance that is empty.
/// </summary>
public MaterialCollection()
{
_collection = new FrugalStructList<Material>();
}
/// <summary>
/// Initializes a new instance that is empty and has the specified initial capacity.
/// </summary>
/// <param name="capacity"> int - The number of elements that the new list is initially capable of storing. </param>
public MaterialCollection(int capacity)
{
_collection = new FrugalStructList<Material>(capacity);
}
/// <summary>
/// Creates a MaterialCollection with all of the same elements as collection
/// </summary>
public MaterialCollection(IEnumerable<Material> collection)
{
// The WritePreamble and WritePostscript aren't technically necessary
// in the constructor as of 1/20/05 but they are put here in case
// their behavior changes at a later date
WritePreamble();
if (collection != null)
{
bool needsItemValidation = true;
ICollection<Material> icollectionOfT = collection as ICollection<Material>;
if (icollectionOfT != null)
{
_collection = new FrugalStructList<Material>(icollectionOfT);
}
else
{
ICollection icollection = collection as ICollection;
if (icollection != null) // an IC but not and IC<T>
{
_collection = new FrugalStructList<Material>(icollection);
}
else // not a IC or IC<T> so fall back to the slower Add
{
_collection = new FrugalStructList<Material>();
foreach (Material item in collection)
{
if (item == null)
{
throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull));
}
Material newValue = item;
OnFreezablePropertyChanged(/* oldValue = */ null, newValue);
_collection.Add(newValue);
OnInsert(newValue);
}
needsItemValidation = false;
}
}
if (needsItemValidation)
{
foreach (Material item in collection)
{
if (item == null)
{
throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull));
}
OnFreezablePropertyChanged(/* oldValue = */ null, item);
OnInsert(item);
}
}
WritePostscript();
}
else
{
throw new ArgumentNullException("collection");
}
}
#endregion Constructors
}
}
| |
// 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: Capture execution context for a thread
**
**
===========================================================*/
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Threading
{
public delegate void ContextCallback(Object state);
internal struct ExecutionContextSwitcher
{
internal ExecutionContext m_ec;
internal SynchronizationContext m_sc;
internal void Undo()
{
SynchronizationContext.SetSynchronizationContext(m_sc);
ExecutionContext.Restore(m_ec);
}
}
public sealed class ExecutionContext
{
public static readonly ExecutionContext Default = new ExecutionContext();
[ThreadStatic]
private static ExecutionContext t_currentMaybeNull;
private readonly LowLevelDictionaryWithIEnumerable<IAsyncLocal, object> m_localValues;
private readonly LowLevelListWithIList<IAsyncLocal> m_localChangeNotifications;
private ExecutionContext()
{
m_localValues = new LowLevelDictionaryWithIEnumerable<IAsyncLocal, object>();
m_localChangeNotifications = new LowLevelListWithIList<IAsyncLocal>();
}
private ExecutionContext(ExecutionContext other)
{
m_localValues = new LowLevelDictionaryWithIEnumerable<IAsyncLocal, object>();
foreach (KeyValuePair<IAsyncLocal, object> kvp in other.m_localValues)
{
m_localValues.Add(kvp.Key, kvp.Value);
}
m_localChangeNotifications = new LowLevelListWithIList<IAsyncLocal>(other.m_localChangeNotifications);
}
public static ExecutionContext Capture()
{
return t_currentMaybeNull ?? ExecutionContext.Default;
}
public static void Run(ExecutionContext executionContext, ContextCallback callback, Object state)
{
ExecutionContextSwitcher ecsw = default(ExecutionContextSwitcher);
try
{
EstablishCopyOnWriteScope(ref ecsw);
ExecutionContext.Restore(executionContext);
callback(state);
}
catch
{
// Note: we have a "catch" rather than a "finally" because we want
// to stop the first pass of EH here. That way we can restore the previous
// context before any of our callers' EH filters run. That means we need to
// end the scope separately in the non-exceptional case below.
ecsw.Undo();
throw;
}
ecsw.Undo();
}
internal static void Restore(ExecutionContext executionContext)
{
if (executionContext == null)
throw new InvalidOperationException(SR.InvalidOperation_NullContext);
ExecutionContext previous = t_currentMaybeNull ?? Default;
t_currentMaybeNull = executionContext;
if (previous != executionContext)
OnContextChanged(previous, executionContext);
}
internal static void EstablishCopyOnWriteScope(ref ExecutionContextSwitcher ecsw)
{
ecsw.m_ec = Capture();
ecsw.m_sc = SynchronizationContext.CurrentExplicit;
}
private static void OnContextChanged(ExecutionContext previous, ExecutionContext current)
{
previous = previous ?? Default;
foreach (IAsyncLocal local in previous.m_localChangeNotifications)
{
object previousValue;
object currentValue;
previous.m_localValues.TryGetValue(local, out previousValue);
current.m_localValues.TryGetValue(local, out currentValue);
if (previousValue != currentValue)
local.OnValueChanged(previousValue, currentValue, true);
}
if (current.m_localChangeNotifications != previous.m_localChangeNotifications)
{
try
{
foreach (IAsyncLocal local in current.m_localChangeNotifications)
{
// If the local has a value in the previous context, we already fired the event for that local
// in the code above.
object previousValue;
if (!previous.m_localValues.TryGetValue(local, out previousValue))
{
object currentValue;
current.m_localValues.TryGetValue(local, out currentValue);
if (previousValue != currentValue)
local.OnValueChanged(previousValue, currentValue, true);
}
}
}
catch (Exception ex)
{
Environment.FailFast(SR.ExecutionContext_ExceptionInAsyncLocalNotification, ex);
}
}
}
internal static object GetLocalValue(IAsyncLocal local)
{
ExecutionContext current = t_currentMaybeNull;
if (current == null)
return null;
object value;
current.m_localValues.TryGetValue(local, out value);
return value;
}
internal static void SetLocalValue(IAsyncLocal local, object newValue, bool needChangeNotifications)
{
ExecutionContext current = t_currentMaybeNull ?? ExecutionContext.Default;
object previousValue;
bool hadPreviousValue = current.m_localValues.TryGetValue(local, out previousValue);
if (previousValue == newValue)
return;
current = new ExecutionContext(current);
current.m_localValues[local] = newValue;
t_currentMaybeNull = current;
if (needChangeNotifications)
{
if (hadPreviousValue)
Debug.Assert(current.m_localChangeNotifications.Contains(local));
else
current.m_localChangeNotifications.Add(local);
local.OnValueChanged(previousValue, newValue, false);
}
}
[Flags]
internal enum CaptureOptions
{
None = 0x00,
IgnoreSyncCtx = 0x01,
OptimizeDefaultCase = 0x02,
}
internal static ExecutionContext PreAllocatedDefault
{
get
{ return ExecutionContext.Default; }
}
internal bool IsPreAllocatedDefault
{
get { return this == ExecutionContext.Default; }
}
}
}
| |
using System;
using System.Linq;
using System.Web;
using System.Web.Compilation;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.SessionState;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Composing;
using Umbraco.Web.Models;
using Umbraco.Web.Routing;
using System.Collections.Generic;
using Current = Umbraco.Web.Composing.Current;
using Umbraco.Web.Features;
namespace Umbraco.Web.Mvc
{
public class RenderRouteHandler : IRouteHandler
{
// Define reserved dictionary keys for controller, action and area specified in route additional values data
internal static class ReservedAdditionalKeys
{
internal const string Controller = "c";
internal const string Action = "a";
internal const string Area = "ar";
}
private readonly IControllerFactory _controllerFactory;
private readonly IUmbracoContextAccessor _umbracoContextAccessor;
private readonly UmbracoContext _umbracoContext;
public RenderRouteHandler(IUmbracoContextAccessor umbracoContextAccessor, IControllerFactory controllerFactory)
{
_umbracoContextAccessor = umbracoContextAccessor ?? throw new ArgumentNullException(nameof(umbracoContextAccessor));
_controllerFactory = controllerFactory ?? throw new ArgumentNullException(nameof(controllerFactory));
}
public RenderRouteHandler(UmbracoContext umbracoContext, IControllerFactory controllerFactory)
{
_umbracoContext = umbracoContext ?? throw new ArgumentNullException(nameof(umbracoContext));
_controllerFactory = controllerFactory ?? throw new ArgumentNullException(nameof(controllerFactory));
}
private UmbracoContext UmbracoContext => _umbracoContext ?? _umbracoContextAccessor.UmbracoContext;
private UmbracoFeatures Features => Current.Factory.GetInstance<UmbracoFeatures>(); // TODO: inject
#region IRouteHandler Members
/// <summary>
/// Assigns the correct controller based on the Umbraco request and returns a standard MvcHandler to process the response,
/// this also stores the render model into the data tokens for the current RouteData.
/// </summary>
/// <param name="requestContext"></param>
/// <returns></returns>
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
if (UmbracoContext == null)
{
throw new NullReferenceException("There is no current UmbracoContext, it must be initialized before the RenderRouteHandler executes");
}
var request = UmbracoContext.PublishedRequest;
if (request == null)
{
throw new NullReferenceException("There is no current PublishedRequest, it must be initialized before the RenderRouteHandler executes");
}
SetupRouteDataForRequest(
new ContentModel(request.PublishedContent),
requestContext,
request);
return GetHandlerForRoute(requestContext, request);
}
#endregion
/// <summary>
/// Ensures that all of the correct DataTokens are added to the route values which are all required for rendering front-end umbraco views
/// </summary>
/// <param name="contentModel"></param>
/// <param name="requestContext"></param>
/// <param name="frequest"></param>
internal void SetupRouteDataForRequest(ContentModel contentModel, RequestContext requestContext, PublishedRequest frequest)
{
//put essential data into the data tokens, the 'umbraco' key is required to be there for the view engine
requestContext.RouteData.DataTokens.Add(Core.Constants.Web.UmbracoDataToken, contentModel); //required for the ContentModelBinder and view engine
requestContext.RouteData.DataTokens.Add(Core.Constants.Web.PublishedDocumentRequestDataToken, frequest); //required for RenderMvcController
requestContext.RouteData.DataTokens.Add(Core.Constants.Web.UmbracoContextDataToken, UmbracoContext); //required for UmbracoViewPage
}
private void UpdateRouteDataForRequest(ContentModel contentModel, RequestContext requestContext)
{
if (contentModel == null) throw new ArgumentNullException(nameof(contentModel));
if (requestContext == null) throw new ArgumentNullException(nameof(requestContext));
requestContext.RouteData.DataTokens[Core.Constants.Web.UmbracoDataToken] = contentModel;
// the rest should not change -- it's only the published content that has changed
}
/// <summary>
/// Checks the request and query strings to see if it matches the definition of having a Surface controller
/// posted/get value, if so, then we return a PostedDataProxyInfo object with the correct information.
/// </summary>
/// <param name="requestContext"></param>
/// <returns></returns>
internal static PostedDataProxyInfo GetFormInfo(RequestContext requestContext)
{
if (requestContext == null) throw new ArgumentNullException(nameof(requestContext));
//if it is a POST/GET then a value must be in the request
if (requestContext.HttpContext.Request.QueryString["ufprt"].IsNullOrWhiteSpace()
&& requestContext.HttpContext.Request.Form["ufprt"].IsNullOrWhiteSpace())
{
return null;
}
string encodedVal;
switch (requestContext.HttpContext.Request.RequestType)
{
case "POST":
//get the value from the request.
//this field will contain an encrypted version of the surface route vals.
encodedVal = requestContext.HttpContext.Request.Form["ufprt"];
break;
case "GET":
//this field will contain an encrypted version of the surface route vals.
encodedVal = requestContext.HttpContext.Request.QueryString["ufprt"];
break;
default:
return null;
}
if (!UmbracoHelper.DecryptAndValidateEncryptedRouteString(encodedVal, out var decodedParts))
return null;
foreach (var item in decodedParts.Where(x => new[] {
ReservedAdditionalKeys.Controller,
ReservedAdditionalKeys.Action,
ReservedAdditionalKeys.Area }.Contains(x.Key) == false))
{
// Populate route with additional values which aren't reserved values so they eventually to action parameters
requestContext.RouteData.Values[item.Key] = item.Value;
}
//return the proxy info without the surface id... could be a local controller.
return new PostedDataProxyInfo
{
ControllerName = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Controller).Value),
ActionName = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Action).Value),
Area = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Area).Value),
};
}
/// <summary>
/// Handles a posted form to an Umbraco URL and ensures the correct controller is routed to and that
/// the right DataTokens are set.
/// </summary>
/// <param name="requestContext"></param>
/// <param name="postedInfo"></param>
internal static IHttpHandler HandlePostedValues(RequestContext requestContext, PostedDataProxyInfo postedInfo)
{
if (requestContext == null) throw new ArgumentNullException(nameof(requestContext));
if (postedInfo == null) throw new ArgumentNullException(nameof(postedInfo));
//set the standard route values/tokens
requestContext.RouteData.Values["controller"] = postedInfo.ControllerName;
requestContext.RouteData.Values["action"] = postedInfo.ActionName;
IHttpHandler handler;
//get the route from the defined routes
using (RouteTable.Routes.GetReadLock())
{
Route surfaceRoute;
//find the controller in the route table
var surfaceRoutes = RouteTable.Routes.OfType<Route>()
.Where(x => x.Defaults != null &&
x.Defaults.ContainsKey("controller") &&
x.Defaults["controller"].ToString().InvariantEquals(postedInfo.ControllerName) &&
// Only return surface controllers
x.DataTokens["umbraco"].ToString().InvariantEquals("surface") &&
// Check for area token if the area is supplied
(postedInfo.Area.IsNullOrWhiteSpace() ? !x.DataTokens.ContainsKey("area") : x.DataTokens["area"].ToString().InvariantEquals(postedInfo.Area)))
.ToList();
// If more than one route is found, find one with a matching action
if (surfaceRoutes.Count > 1)
{
surfaceRoute = surfaceRoutes.FirstOrDefault(x =>
x.Defaults["action"] != null &&
x.Defaults["action"].ToString().InvariantEquals(postedInfo.ActionName));
}
else
{
surfaceRoute = surfaceRoutes.FirstOrDefault();
}
if (surfaceRoute == null)
throw new InvalidOperationException("Could not find a Surface controller route in the RouteTable for controller name " + postedInfo.ControllerName);
//set the area if one is there.
if (surfaceRoute.DataTokens.ContainsKey("area"))
{
requestContext.RouteData.DataTokens["area"] = surfaceRoute.DataTokens["area"];
}
//set the 'Namespaces' token so the controller factory knows where to look to construct it
if (surfaceRoute.DataTokens.ContainsKey("Namespaces"))
{
requestContext.RouteData.DataTokens["Namespaces"] = surfaceRoute.DataTokens["Namespaces"];
}
handler = surfaceRoute.RouteHandler.GetHttpHandler(requestContext);
}
return handler;
}
/// <summary>
/// Returns a RouteDefinition object based on the current content request
/// </summary>
/// <param name="requestContext"></param>
/// <param name="request"></param>
/// <returns></returns>
internal virtual RouteDefinition GetUmbracoRouteDefinition(RequestContext requestContext, PublishedRequest request)
{
if (requestContext == null) throw new ArgumentNullException(nameof(requestContext));
if (request == null) throw new ArgumentNullException(nameof(request));
var defaultControllerType = Current.DefaultRenderMvcControllerType;
var defaultControllerName = ControllerExtensions.GetControllerName(defaultControllerType);
//creates the default route definition which maps to the 'UmbracoController' controller
var def = new RouteDefinition
{
ControllerName = defaultControllerName,
ControllerType = defaultControllerType,
PublishedRequest = request,
ActionName = ((Route)requestContext.RouteData.Route).Defaults["action"].ToString(),
HasHijackedRoute = false
};
//check that a template is defined), if it doesn't and there is a hijacked route it will just route
// to the index Action
if (request.HasTemplate)
{
//the template Alias should always be already saved with a safe name.
//if there are hyphens in the name and there is a hijacked route, then the Action will need to be attributed
// with the action name attribute.
var templateName = request.TemplateAlias.Split(Umbraco.Core.Constants.CharArrays.Period)[0].ToSafeAlias();
def.ActionName = templateName;
}
//check if there's a custom controller assigned, base on the document type alias.
var controllerType = _controllerFactory.GetControllerTypeInternal(requestContext, request.PublishedContent.ContentType.Alias);
//check if that controller exists
if (controllerType != null)
{
//ensure the controller is of type IRenderMvcController and ControllerBase
if (TypeHelper.IsTypeAssignableFrom<IRenderController>(controllerType)
&& TypeHelper.IsTypeAssignableFrom<ControllerBase>(controllerType))
{
//set the controller and name to the custom one
def.ControllerType = controllerType;
def.ControllerName = ControllerExtensions.GetControllerName(controllerType);
if (def.ControllerName != defaultControllerName)
{
def.HasHijackedRoute = true;
}
}
else
{
Current.Logger.Warn<RenderRouteHandler>("The current Document Type {ContentTypeAlias} matches a locally declared controller of type {ControllerName}. Custom Controllers for Umbraco routing must implement '{UmbracoRenderController}' and inherit from '{UmbracoControllerBase}'.",
request.PublishedContent.ContentType.Alias,
controllerType.FullName,
typeof(IRenderController).FullName,
typeof(ControllerBase).FullName);
//we cannot route to this custom controller since it is not of the correct type so we'll continue with the defaults
// that have already been set above.
}
}
//store the route definition
requestContext.RouteData.DataTokens[Core.Constants.Web.UmbracoRouteDefinitionDataToken] = def;
return def;
}
internal IHttpHandler GetHandlerOnMissingTemplate(PublishedRequest request)
{
if (request == null) throw new ArgumentNullException(nameof(request));
// missing template, so we're in a 404 here
// so the content, if any, is a custom 404 page of some sort
if (request.HasPublishedContent == false)
// means the builder could not find a proper document to handle 404
return new PublishedContentNotFoundHandler();
if (request.HasTemplate == false)
// means the engine could find a proper document, but the document has no template
// at that point there isn't much we can do and there is no point returning
// to Mvc since Mvc can't do much
return new PublishedContentNotFoundHandler("In addition, no template exists to render the custom 404.");
return null;
}
/// <summary>
/// this will determine the controller and set the values in the route data
/// </summary>
/// <param name="requestContext"></param>
/// <param name="request"></param>
internal IHttpHandler GetHandlerForRoute(RequestContext requestContext, PublishedRequest request)
{
if (requestContext == null) throw new ArgumentNullException(nameof(requestContext));
if (request == null) throw new ArgumentNullException(nameof(request));
var routeDef = GetUmbracoRouteDefinition(requestContext, request);
//Need to check for a special case if there is form data being posted back to an Umbraco URL
var postedInfo = GetFormInfo(requestContext);
if (postedInfo != null)
{
return HandlePostedValues(requestContext, postedInfo);
}
//Here we need to check if there is no hijacked route and no template assigned,
//if this is the case we want to return a blank page, but we'll leave that up to the NoTemplateHandler.
//We also check if templates have been disabled since if they are then we're allowed to render even though there's no template,
//for example for json rendering in headless.
if ((request.HasTemplate == false && Features.Disabled.DisableTemplates == false)
&& routeDef.HasHijackedRoute == false)
{
request.UpdateToNotFound(); // request will go 404
// HandleHttpResponseStatus returns a value indicating that the request should
// not be processed any further, eg because it has been redirect. then, exit.
if (UmbracoModule.HandleHttpResponseStatus(requestContext.HttpContext, request, Current.Logger))
return null;
var handler = GetHandlerOnMissingTemplate(request);
// if it's not null it's the PublishedContentNotFoundHandler (no document was found to handle 404, or document with no template was found)
// if it's null it means that a document was found
// if we have a handler, return now
if (handler != null)
return handler;
// else we are running Mvc
// update the route data - because the PublishedContent has changed
UpdateRouteDataForRequest(
new ContentModel(request.PublishedContent),
requestContext);
// update the route definition
routeDef = GetUmbracoRouteDefinition(requestContext, request);
}
//no post values, just route to the controller/action required (local)
requestContext.RouteData.Values["controller"] = routeDef.ControllerName;
if (string.IsNullOrWhiteSpace(routeDef.ActionName) == false)
requestContext.RouteData.Values["action"] = routeDef.ActionName;
// Set the session state requirements
requestContext.HttpContext.SetSessionStateBehavior(GetSessionStateBehavior(requestContext, routeDef.ControllerName));
// reset the friendly path so in the controllers and anything occurring after this point in time,
//the URL is reset back to the original request.
requestContext.HttpContext.RewritePath(UmbracoContext.OriginalRequestUrl.PathAndQuery);
return new UmbracoMvcHandler(requestContext);
}
private SessionStateBehavior GetSessionStateBehavior(RequestContext requestContext, string controllerName)
{
return _controllerFactory.GetControllerSessionBehavior(requestContext, controllerName);
}
}
}
| |
#if !(UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2)
#define SupportCustomYieldInstruction
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using UniRx.InternalUtil;
using UnityEngine;
namespace UniRx
{
public sealed class MainThreadDispatcher : MonoBehaviour
{
public enum CullingMode
{
/// <summary>
/// Won't remove any MainThreadDispatchers.
/// </summary>
Disabled,
/// <summary>
/// Checks if there is an existing MainThreadDispatcher on Awake(). If so, the new dispatcher removes itself.
/// </summary>
Self,
/// <summary>
/// Search for excess MainThreadDispatchers and removes them all on Awake().
/// </summary>
All
}
public static CullingMode cullingMode = CullingMode.Self;
#if UNITY_EDITOR
// In UnityEditor's EditorMode can't instantiate and work MonoBehaviour.Update.
// EditorThreadDispatcher use EditorApplication.update instead of MonoBehaviour.Update.
class EditorThreadDispatcher
{
static object gate = new object();
static EditorThreadDispatcher instance;
public static EditorThreadDispatcher Instance
{
get
{
// Activate EditorThreadDispatcher is dangerous, completely Lazy.
lock (gate)
{
if (instance == null)
{
instance = new EditorThreadDispatcher();
}
return instance;
}
}
}
ThreadSafeQueueWorker editorQueueWorker = new ThreadSafeQueueWorker();
EditorThreadDispatcher()
{
UnityEditor.EditorApplication.update += Update;
}
public void Enqueue(Action<object> action, object state)
{
editorQueueWorker.Enqueue(action, state);
}
public void UnsafeInvoke(Action action)
{
try
{
action();
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
public void UnsafeInvoke<T>(Action<T> action, T state)
{
try
{
action(state);
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
public void PseudoStartCoroutine(IEnumerator routine)
{
editorQueueWorker.Enqueue(_ => ConsumeEnumerator(routine), null);
}
void Update()
{
editorQueueWorker.ExecuteAll(x => Debug.LogException(x));
}
void ConsumeEnumerator(IEnumerator routine)
{
if (routine.MoveNext())
{
var current = routine.Current;
if (current == null)
{
goto ENQUEUE;
}
var type = current.GetType();
if (type == typeof(AsyncOperation))
{
var asyncOperation = (AsyncOperation)current;
editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapWaitAsyncOperation(asyncOperation, routine)), null);
return;
}
else if (type == typeof(WaitForSeconds))
{
var waitForSeconds = (WaitForSeconds)current;
var accessor = typeof(WaitForSeconds).GetField("m_Seconds", BindingFlags.Instance | BindingFlags.GetField | BindingFlags.NonPublic);
var second = (float)accessor.GetValue(waitForSeconds);
editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapWaitForSeconds(second, routine)), null);
return;
}
else if (type == typeof(Coroutine))
{
Debug.Log("Can't wait coroutine on UnityEditor");
goto ENQUEUE;
}
#if SupportCustomYieldInstruction
else if (current is IEnumerator)
{
var enumerator = (IEnumerator)current;
editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapEnumerator(enumerator, routine)), null);
return;
}
#endif
ENQUEUE:
editorQueueWorker.Enqueue(_ => ConsumeEnumerator(routine), null); // next update
}
}
IEnumerator UnwrapWaitAsyncOperation(AsyncOperation asyncOperation, IEnumerator continuation)
{
while (!asyncOperation.isDone)
{
yield return null;
}
ConsumeEnumerator(continuation);
}
IEnumerator UnwrapWaitForSeconds(float second, IEnumerator continuation)
{
var startTime = DateTimeOffset.UtcNow;
while (true)
{
yield return null;
var elapsed = (DateTimeOffset.UtcNow - startTime).TotalSeconds;
if (elapsed >= second)
{
break;
}
};
ConsumeEnumerator(continuation);
}
IEnumerator UnwrapEnumerator(IEnumerator enumerator, IEnumerator continuation)
{
while (enumerator.MoveNext())
{
yield return null;
}
ConsumeEnumerator(continuation);
}
}
#endif
/// <summary>Dispatch Asyncrhonous action.</summary>
public static void Post(Action<object> action, object state)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.Enqueue(action, state); return; }
#endif
var dispatcher = Instance;
if (!isQuitting && !object.ReferenceEquals(dispatcher, null))
{
dispatcher.queueWorker.Enqueue(action, state);
}
}
/// <summary>Dispatch Synchronous action if possible.</summary>
public static void Send(Action<object> action, object state)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.Enqueue(action, state); return; }
#endif
if (mainThreadToken != null)
{
try
{
action(state);
}
catch (Exception ex)
{
var dispatcher = MainThreadDispatcher.Instance;
if (dispatcher != null)
{
dispatcher.unhandledExceptionCallback(ex);
}
}
}
else
{
Post(action, state);
}
}
/// <summary>Run Synchronous action.</summary>
public static void UnsafeSend(Action action)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.UnsafeInvoke(action); return; }
#endif
try
{
action();
}
catch (Exception ex)
{
var dispatcher = MainThreadDispatcher.Instance;
if (dispatcher != null)
{
dispatcher.unhandledExceptionCallback(ex);
}
}
}
/// <summary>Run Synchronous action.</summary>
public static void UnsafeSend<T>(Action<T> action, T state)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.UnsafeInvoke(action, state); return; }
#endif
try
{
action(state);
}
catch (Exception ex)
{
var dispatcher = MainThreadDispatcher.Instance;
if (dispatcher != null)
{
dispatcher.unhandledExceptionCallback(ex);
}
}
}
/// <summary>ThreadSafe StartCoroutine.</summary>
public static void SendStartCoroutine(IEnumerator routine)
{
if (mainThreadToken != null)
{
StartCoroutine(routine);
}
else
{
#if UNITY_EDITOR
// call from other thread
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; }
#endif
var dispatcher = Instance;
if (!isQuitting && !object.ReferenceEquals(dispatcher, null))
{
dispatcher.queueWorker.Enqueue(_ =>
{
var dispacher2 = Instance;
if (dispacher2 != null)
{
(dispacher2 as MonoBehaviour).StartCoroutine(routine);
}
}, null);
}
}
}
public static void StartUpdateMicroCoroutine(IEnumerator routine)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; }
#endif
var dispatcher = Instance;
if (dispatcher != null)
{
dispatcher.updateMicroCoroutine.AddCoroutine(routine);
}
}
public static void StartFixedUpdateMicroCoroutine(IEnumerator routine)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; }
#endif
var dispatcher = Instance;
if (dispatcher != null)
{
dispatcher.fixedUpdateMicroCoroutine.AddCoroutine(routine);
}
}
public static void StartEndOfFrameMicroCoroutine(IEnumerator routine)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; }
#endif
var dispatcher = Instance;
if (dispatcher != null)
{
dispatcher.endOfFrameMicroCoroutine.AddCoroutine(routine);
}
}
new public static Coroutine StartCoroutine(IEnumerator routine)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return null; }
#endif
var dispatcher = Instance;
if (dispatcher != null)
{
return (dispatcher as MonoBehaviour).StartCoroutine(routine);
}
else
{
return null;
}
}
public static void RegisterUnhandledExceptionCallback(Action<Exception> exceptionCallback)
{
if (exceptionCallback == null)
{
// do nothing
Instance.unhandledExceptionCallback = Stubs<Exception>.Ignore;
}
else
{
Instance.unhandledExceptionCallback = exceptionCallback;
}
}
ThreadSafeQueueWorker queueWorker = new ThreadSafeQueueWorker();
Action<Exception> unhandledExceptionCallback = ex => Debug.LogException(ex); // default
MicroCoroutine updateMicroCoroutine = null;
MicroCoroutine fixedUpdateMicroCoroutine = null;
MicroCoroutine endOfFrameMicroCoroutine = null;
static MainThreadDispatcher instance;
static bool initialized;
static bool isQuitting = false;
public static string InstanceName
{
get
{
if (instance == null)
{
throw new NullReferenceException("MainThreadDispatcher is not initialized.");
}
return instance.name;
}
}
public static bool IsInitialized
{
get { return initialized && instance != null; }
}
[ThreadStatic]
static object mainThreadToken;
static MainThreadDispatcher Instance
{
get
{
Initialize();
return instance;
}
}
public static void Initialize()
{
if (!initialized)
{
#if UNITY_EDITOR
// Don't try to add a GameObject when the scene is not playing. Only valid in the Editor, EditorView.
if (!ScenePlaybackDetector.IsPlaying) return;
#endif
MainThreadDispatcher dispatcher = null;
try
{
dispatcher = GameObject.FindObjectOfType<MainThreadDispatcher>();
}
catch
{
// Throw exception when calling from a worker thread.
var ex = new Exception("UniRx requires a MainThreadDispatcher component created on the main thread. Make sure it is added to the scene before calling UniRx from a worker thread.");
UnityEngine.Debug.LogException(ex);
throw ex;
}
if (isQuitting)
{
// don't create new instance after quitting
// avoid "Some objects were not cleaned up when closing the scene find target" error.
return;
}
if (dispatcher == null)
{
// awake call immediately from UnityEngine
new GameObject("MainThreadDispatcher").AddComponent<MainThreadDispatcher>();
}
else
{
dispatcher.Awake(); // force awake
}
}
}
public static bool IsInMainThread
{
get
{
return (mainThreadToken != null);
}
}
void Awake()
{
if (instance == null)
{
instance = this;
mainThreadToken = new object();
initialized = true;
updateMicroCoroutine = new MicroCoroutine(ex => unhandledExceptionCallback(ex));
fixedUpdateMicroCoroutine = new MicroCoroutine(ex => unhandledExceptionCallback(ex));
endOfFrameMicroCoroutine = new MicroCoroutine(ex => unhandledExceptionCallback(ex));
StartCoroutine(RunUpdateMicroCoroutine());
StartCoroutine(RunFixedUpdateMicroCoroutine());
StartCoroutine(RunEndOfFrameMicroCoroutine());
DontDestroyOnLoad(gameObject);
}
else
{
if (this != instance)
{
if (cullingMode == CullingMode.Self)
{
// Try to destroy this dispatcher if there's already one in the scene.
Debug.LogWarning("There is already a MainThreadDispatcher in the scene. Removing myself...");
DestroyDispatcher(this);
}
else if (cullingMode == CullingMode.All)
{
Debug.LogWarning("There is already a MainThreadDispatcher in the scene. Cleaning up all excess dispatchers...");
CullAllExcessDispatchers();
}
else
{
Debug.LogWarning("There is already a MainThreadDispatcher in the scene.");
}
}
}
}
IEnumerator RunUpdateMicroCoroutine()
{
while (true)
{
yield return null;
updateMicroCoroutine.Run();
}
}
IEnumerator RunFixedUpdateMicroCoroutine()
{
while (true)
{
yield return YieldInstructionCache.WaitForFixedUpdate;
fixedUpdateMicroCoroutine.Run();
}
}
IEnumerator RunEndOfFrameMicroCoroutine()
{
while (true)
{
yield return YieldInstructionCache.WaitForEndOfFrame;
endOfFrameMicroCoroutine.Run();
}
}
static void DestroyDispatcher(MainThreadDispatcher aDispatcher)
{
if (aDispatcher != instance)
{
// Try to remove game object if it's empty
var components = aDispatcher.gameObject.GetComponents<Component>();
if (aDispatcher.gameObject.transform.childCount == 0 && components.Length == 2)
{
if (components[0] is Transform && components[1] is MainThreadDispatcher)
{
Destroy(aDispatcher.gameObject);
}
}
else
{
// Remove component
MonoBehaviour.Destroy(aDispatcher);
}
}
}
public static void CullAllExcessDispatchers()
{
var dispatchers = GameObject.FindObjectsOfType<MainThreadDispatcher>();
for (int i = 0; i < dispatchers.Length; i++)
{
DestroyDispatcher(dispatchers[i]);
}
}
void OnDestroy()
{
if (instance == this)
{
instance = GameObject.FindObjectOfType<MainThreadDispatcher>();
initialized = instance != null;
/*
// Although `this` still refers to a gameObject, it won't be found.
var foundDispatcher = GameObject.FindObjectOfType<MainThreadDispatcher>();
if (foundDispatcher != null)
{
// select another game object
Debug.Log("new instance: " + foundDispatcher.name);
instance = foundDispatcher;
initialized = true;
}
*/
}
}
void Update()
{
if (update != null)
{
try
{
update.OnNext(Unit.Default);
}
catch (Exception ex)
{
unhandledExceptionCallback(ex);
}
}
queueWorker.ExecuteAll(unhandledExceptionCallback);
}
// for Lifecycle Management
Subject<Unit> update;
public static IObservable<Unit> UpdateAsObservable()
{
return Instance.update ?? (Instance.update = new Subject<Unit>());
}
Subject<Unit> lateUpdate;
void LateUpdate()
{
if (lateUpdate != null) lateUpdate.OnNext(Unit.Default);
}
public static IObservable<Unit> LateUpdateAsObservable()
{
return Instance.lateUpdate ?? (Instance.lateUpdate = new Subject<Unit>());
}
Subject<bool> onApplicationFocus;
void OnApplicationFocus(bool focus)
{
if (onApplicationFocus != null) onApplicationFocus.OnNext(focus);
}
public static IObservable<bool> OnApplicationFocusAsObservable()
{
return Instance.onApplicationFocus ?? (Instance.onApplicationFocus = new Subject<bool>());
}
Subject<bool> onApplicationPause;
void OnApplicationPause(bool pause)
{
if (onApplicationPause != null) onApplicationPause.OnNext(pause);
}
public static IObservable<bool> OnApplicationPauseAsObservable()
{
return Instance.onApplicationPause ?? (Instance.onApplicationPause = new Subject<bool>());
}
Subject<Unit> onApplicationQuit;
void OnApplicationQuit()
{
isQuitting = true;
if (onApplicationQuit != null) onApplicationQuit.OnNext(Unit.Default);
}
public static IObservable<Unit> OnApplicationQuitAsObservable()
{
return Instance.onApplicationQuit ?? (Instance.onApplicationQuit = new Subject<Unit>());
}
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
namespace Terraria.ModLoader
{
/// <summary>
/// This class represents a type of wall that can be added by a mod. Only one instance of this class will ever exist for each type of wall that is added. Any hooks that are called will be called by the instance corresponding to the wall type.
/// </summary>
public class ModWall
{
/// <summary>
/// The mod which has added this type of ModWall.
/// </summary>
public Mod mod
{
get;
internal set;
}
/// <summary>
/// The name of this type of wall.
/// </summary>
public string Name
{
get;
internal set;
}
/// <summary>
/// The internal ID of this type of wall.
/// </summary>
public ushort Type
{
get;
internal set;
}
internal string texture;
/// <summary>
/// The default type of sound made when this wall is hit. Defaults to 0.
/// </summary>
public int soundType = 0;
/// <summary>
/// The default style of sound made when this wall is hit. Defaults to 1.
/// </summary>
public int soundStyle = 1;
/// <summary>
/// The default type of dust made when this wall is hit. Defaults to 0.
/// </summary>
public int dustType = 0;
/// <summary>
/// The default type of item dropped when this wall is killed. Defaults to 0, which means no item.
/// </summary>
public int drop = 0;
/// <summary>
/// Adds an entry to the minimap for this wall with the given color and display name. This should be called in SetDefaults.
/// </summary>
public void AddMapEntry(Color color, string name = "")
{
if (!MapLoader.initialized)
{
MapEntry entry = new MapEntry(color, name);
if (!MapLoader.wallEntries.Keys.Contains(Type))
{
MapLoader.wallEntries[Type] = new List<MapEntry>();
}
MapLoader.wallEntries[Type].Add(entry);
}
}
/// <summary>
/// Adds an entry to the minimap for this wall with the given color, default display name, and display name function. The parameters for the function are the default display name, x-coordinate, and y-coordinate. This should be called in SetDefaults.
/// </summary>
public void AddMapEntry(Color color, string name, Func<string, int, int, string> nameFunc)
{
if (!MapLoader.initialized)
{
MapEntry entry = new MapEntry(color, name, nameFunc);
if (!MapLoader.wallEntries.Keys.Contains(Type))
{
MapLoader.wallEntries[Type] = new List<MapEntry>();
}
MapLoader.wallEntries[Type].Add(entry);
}
}
/// <summary>
/// Allows you to modify the name and texture path of this wall when it is autoloaded. Return true to autoload this wall. When a wall is autoloaded, that means you do not need to manually call Mod.AddWall. By default returns the mod's autoload property.
/// </summary>
public virtual bool Autoload(ref string name, ref string texture)
{
return mod.Properties.Autoload;
}
/// <summary>
/// Allows you to set the properties of this wall. Many properties are stored as arrays throughout Terraria's code.
/// </summary>
public virtual void SetDefaults()
{
}
/// <summary>
/// Allows you to customize which sound you want to play when the wall at the given coordinates is hit. Return false to stop the game from playing its default sound for the wall. Returns true by default.
/// </summary>
public virtual bool KillSound(int i, int j)
{
return true;
}
/// <summary>
/// Allows you to change how many dust particles are created when the wall at the given coordinates is hit.
/// </summary>
public virtual void NumDust(int i, int j, bool fail, ref int num)
{
}
/// <summary>
/// Allows you to modify the default type of dust created when the wall at the given coordinates is hit. Return false to stop the default dust (the type parameter) from being created. Returns true by default.
/// </summary>
public virtual bool CreateDust(int i, int j, ref int type)
{
type = dustType;
return true;
}
/// <summary>
/// Allows you to customize which items the wall at the given coordinates drops. Return false to stop the game from dropping the tile's default item (the type parameter). Returns true by default.
/// </summary>
public virtual bool Drop(int i, int j, ref int type)
{
type = drop;
return true;
}
/// <summary>
/// Allows you to determine what happens when the tile at the given coordinates is killed or hit with a hammer. Fail determines whether the tile is mined (whether it is killed).
/// </summary>
public virtual void KillWall(int i, int j, ref bool fail)
{
}
/// <summary>
/// Whether or not the wall at the given coordinates can be killed by an explosion (ie. bombs). Returns true by default; return false to stop an explosion from destroying it.
/// </summary>
public virtual bool CanExplode(int i, int j)
{
return true;
}
/// <summary>
/// Allows you to choose which minimap entry the wall at the given coordinates will use. 0 is the first entry added by AddMapEntry, 1 is the second entry, etc. Returns 0 by default.
/// </summary>
public virtual ushort GetMapOption(int i, int j)
{
return 0;
}
/// <summary>
/// Allows you to determine how much light this wall emits. This can also let you light up the block in front of this wall.
/// </summary>
public virtual void ModifyLight(int i, int j, ref float r, ref float g, ref float b)
{
}
/// <summary>
/// Called whenever the world randomly decides to update the tile containing this wall in a given tick. Useful for things such as growing or spreading.
/// </summary>
public virtual void RandomUpdate(int i, int j)
{
}
/// <summary>
/// Allows you to animate your wall. Use frameCounter to keep track of how long the current frame has been active, and use frame to change the current frame.
/// </summary>
public virtual void AnimateWall(ref byte frame, ref byte frameCounter)
{
}
/// <summary>
/// Allows you to draw things behind the wall at the given coordinates. Return false to stop the game from drawing the wall normally. Returns true by default.
/// </summary>
public virtual bool PreDraw(int i, int j, SpriteBatch spriteBatch)
{
return true;
}
/// <summary>
/// Allows you to draw things in front of the wall at the given coordinates.
/// </summary>
public virtual void PostDraw(int i, int j, SpriteBatch spriteBatch)
{
}
/// <summary>
/// Called after this wall is placed in the world by way of the item provided.
/// </summary>
public virtual void PlaceInWorld(int i, int j, Item item)
{
}
}
}
| |
using System;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
using TribalWars.Maps.AttackPlans.EventArg;
using TribalWars.Maps.Manipulators.Managers;
using TribalWars.Villages.ContextMenu;
using TribalWars.Worlds;
using TribalWars.Worlds.Events;
namespace TribalWars.Maps.AttackPlans.Controls
{
/// <summary>
/// Control with for one <see cref="AttackPlan" />
/// </summary>
public partial class AttackPlanControl : UserControl
{
#region Fields
private readonly ImageList _unitImageList;
private bool _settingControlValues;
private AttackPlanFromControl _activeAttacker;
#endregion
#region Properties
public AttackPlan Plan { get; private set; }
#endregion
#region Constructors
public AttackPlanControl(ImageList imageList, AttackPlan plan)
{
InitializeComponent();
_unitImageList = imageList;
Plan = plan;
SetControlProperties();
}
#endregion
#region EventHandlers
private void Close_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
World.Default.Map.EventPublisher.AttackRemoveTarget(this, Plan);
}
private void Date_DateSelected(object sender, TribalWars.Controls.TimeConverter.DateEventArgs e)
{
if (!_settingControlValues)
{
Plan.ArrivalTime = e.SelectedDate;
World.Default.Map.EventPublisher.AttackUpdateTarget(this, AttackUpdateEventArgs.Update());
}
}
private void Coords_VillageSelected(object sender, Worlds.Events.Impls.VillageEventArgs e)
{
if (!_settingControlValues)
{
Plan.Target = e.FirstVillage;
SetControlProperties();
World.Default.Map.EventPublisher.AttackUpdateTarget(this, AttackUpdateEventArgs.Update());
}
}
private void _Village_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
var cm = new VillageContextMenu(World.Default.Map, Plan.Target);
cm.Show(_Village, e.Location);
}
else if (e.Button == MouseButtons.Left)
{
World.Default.Map.Manipulators.SetManipulator(ManipulatorManagerTypes.Attack);
World.Default.Map.EventPublisher.AttackSelect(this, Plan);
}
}
private void _Village_DoubleClick(object sender, EventArgs e)
{
Plan.Pinpoint(null);
}
private void _Player_MouseClick(object sender, MouseEventArgs e)
{
if (Plan.Target.HasPlayer)
{
if (e.Button == MouseButtons.Right)
{
var cm = new PlayerContextMenu(World.Default.Map, Plan.Target.Player, false);
cm.Show(_Player, e.Location);
}
else if (e.Button == MouseButtons.Left)
{
World.Default.Map.Manipulators.SetManipulator(ManipulatorManagerTypes.Default);
World.Default.Map.EventPublisher.SelectVillages(null, Plan.Target.Player, VillageTools.PinPoint);
}
}
}
private void Player_DoubleClick(object sender, EventArgs e)
{
if (Plan.Target.HasPlayer)
{
World.Default.Map.Manipulators.SetManipulator(ManipulatorManagerTypes.Default);
World.Default.Map.EventPublisher.SelectVillages(this, Plan.Target.Player, VillageTools.PinPoint);
World.Default.Map.SetCenter(Plan.Target.Player);
}
}
private void _Tribe_MouseClick(object sender, MouseEventArgs e)
{
if (Plan.Target.HasTribe)
{
if (e.Button == MouseButtons.Right)
{
var cm = new TribeContextMenu(World.Default.Map, Plan.Target.Player.Tribe);
cm.Show(_Tribe, e.Location);
}
else if (e.Button == MouseButtons.Left)
{
World.Default.Map.Manipulators.SetManipulator(ManipulatorManagerTypes.Default);
World.Default.Map.EventPublisher.SelectVillages(null, Plan.Target.Player.Tribe, VillageTools.PinPoint);
}
}
}
private void Tribe_DoubleClick(object sender, EventArgs e)
{
if (Plan.Target.HasTribe)
{
World.Default.Map.Manipulators.SetManipulator(ManipulatorManagerTypes.Default);
World.Default.Map.EventPublisher.SelectVillages(this, Plan.Target.Player.Tribe, VillageTools.PinPoint);
World.Default.Map.SetCenter(Plan.Target.Player.Tribe);
}
}
#endregion
#region Update Display
/// <summary>
/// Update the display times for all attacking villages
/// </summary>
public void UpdateDisplay()
{
AttackCountLabel.Text = Plan.Attacks.Count().ToString(CultureInfo.InvariantCulture);
Comments.Text = Plan.Comments;
foreach (var attackFrom in DistanceContainer.Controls.OfType<AttackPlanFromControl>())
{
attackFrom.UpdateDisplay();
}
}
/// <summary>
/// Sort attackers, with attackers that need to be send first on top
/// </summary>
public void SortOnTimeLeft()
{
var list = DistanceContainer.Controls
.OfType<AttackPlanFromControl>()
.Select(x => x.Attacker)
.OrderBy(x => x.GetTimeLeftBeforeSendDate())
.ToArray();
for (int i = 0; i < DistanceContainer.Controls.Count; i++)
{
var mdv = DistanceContainer.Controls[i] as AttackPlanFromControl;
if (mdv != null)
{
mdv.SetVillage(list[i]);
}
}
}
private void SetControlProperties()
{
_settingControlValues = true;
Date.Value = Plan.ArrivalTime;
Coords.Text = Plan.Target.LocationString;
_Village.Text = string.Format("{0} ({1})", Plan.Target.Name, Plan.Target.Points.ToString("#,0"));
toolTip1.SetToolTip(_Village, Plan.Target.Tooltip.Text);
if (Plan.Target.HasPlayer)
{
_Player.Text = Plan.Target.Player.ToString();
toolTip1.SetToolTip(_Player, Plan.Target.Player.Tooltip);
_Tribe.Text = Plan.Target.HasTribe ? Plan.Target.Player.Tribe.Tag : "";
toolTip1.SetToolTip(_Tribe, Plan.Target.HasTribe ? Plan.Target.Player.Tribe.Tooltip : "");
}
else
{
_Player.Text = "";
_Tribe.Text = "";
toolTip1.SetToolTip(_Player, "");
toolTip1.SetToolTip(_Tribe, "");
}
_settingControlValues = false;
}
#endregion
#region Attacker Changes
/// <summary>
/// Visual indication of currently selected attacker in the plan
/// </summary>
public void SetActiveAttacker(AttackPlanFrom activeAttacker)
{
if (_activeAttacker != null)
{
_activeAttacker.BackColor = SystemColors.Control;
}
AttackPlanFromControl attackerControl = GetControlForAttackPlan(activeAttacker);
if (attackerControl != null)
{
attackerControl.BackColor = SystemColors.ControlDark;
_activeAttacker = attackerControl;
DistanceContainer.ScrollControlIntoView(_activeAttacker);
}
}
public AttackPlanFromControl AddAttacker(AttackPlanFrom attackFrom)
{
var ctl = new AttackPlanFromControl(_unitImageList, attackFrom);
DistanceContainer.Controls.Add(ctl);
return ctl;
}
public void RemoveAttacker(AttackPlanFrom attacker)
{
AttackPlanFromControl attackerControl = GetControlForAttackPlan(attacker);
if (attackerControl != null)
{
DistanceContainer.Controls.Remove(attackerControl);
}
}
/// <summary>
/// Gets the UI control that represents the parameter
/// </summary>
private AttackPlanFromControl GetControlForAttackPlan(AttackPlanFrom attacker)
{
var attackerControl = DistanceContainer.Controls.OfType<AttackPlanFromControl>().SingleOrDefault(x => x.Attacker == attacker);
return attackerControl;
}
#endregion
public override string ToString()
{
return Plan.ToString();
}
private void ToggleComments_Click(object sender, EventArgs e)
{
CommentsToggle1.Visible = !CommentsToggle1.Visible;
Comments.Visible = !Comments.Visible;
}
private void Comments_TextChanged(object sender, EventArgs e)
{
Plan.Comments = Comments.Text;
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Tests;
using Xunit;
namespace System.Net.Tests
{
public partial class WebHeaderCollectionTest
{
[Fact]
public void Ctor_Success()
{
new WebHeaderCollection();
}
[Fact]
public void DefaultPropertyValues_ReturnEmptyAfterConstruction_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
Assert.Equal(0, w.AllKeys.Length);
Assert.Equal(0, w.Count);
Assert.Equal("\r\n", w.ToString());
Assert.Empty(w);
Assert.Empty(w.AllKeys);
}
[Fact]
public void HttpRequestHeader_Add_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w[HttpRequestHeader.Connection] = "keep-alive";
Assert.Equal(1, w.Count);
Assert.Equal("keep-alive", w[HttpRequestHeader.Connection]);
Assert.Equal("Connection", w.AllKeys[0]);
}
[Theory]
[InlineData((HttpRequestHeader)int.MinValue)]
[InlineData((HttpRequestHeader)(-1))]
[InlineData((HttpRequestHeader)int.MaxValue)]
public void HttpRequestHeader_AddInvalid_Throws(HttpRequestHeader header)
{
WebHeaderCollection w = new WebHeaderCollection();
Assert.Throws<IndexOutOfRangeException>(() => w[header] = "foo");
}
[Theory]
[InlineData((HttpResponseHeader)int.MinValue)]
[InlineData((HttpResponseHeader)(-1))]
[InlineData((HttpResponseHeader)int.MaxValue)]
public void HttpResponseHeader_AddInvalid_Throws(HttpResponseHeader header)
{
WebHeaderCollection w = new WebHeaderCollection();
Assert.Throws<IndexOutOfRangeException>(() => w[header] = "foo");
}
[Fact]
public void CustomHeader_AddQuery_Success()
{
string customHeader = "Custom-Header";
string customValue = "Custom;.-Value";
WebHeaderCollection w = new WebHeaderCollection();
w[customHeader] = customValue;
Assert.Equal(1, w.Count);
Assert.Equal(customValue, w[customHeader]);
Assert.Equal(customHeader, w.AllKeys[0]);
}
[Fact]
public void HttpResponseHeader_AddQuery_CommonHeader_Success()
{
string headerValue = "value123";
WebHeaderCollection w = new WebHeaderCollection();
w[HttpResponseHeader.ProxyAuthenticate] = headerValue;
w[HttpResponseHeader.WwwAuthenticate] = headerValue;
Assert.Equal(headerValue, w[HttpResponseHeader.ProxyAuthenticate]);
Assert.Equal(headerValue, w[HttpResponseHeader.WwwAuthenticate]);
}
[Fact]
public void HttpRequest_AddQuery_CommonHeader_Success()
{
string headerValue = "value123";
WebHeaderCollection w = new WebHeaderCollection();
w[HttpRequestHeader.Accept] = headerValue;
Assert.Equal(headerValue, w[HttpRequestHeader.Accept]);
}
[Fact]
public void RequestThenResponseHeaders_Add_Throws()
{
WebHeaderCollection w = new WebHeaderCollection();
w[HttpRequestHeader.Accept] = "text/json";
Assert.Throws<InvalidOperationException>(() => w[HttpResponseHeader.ContentLength] = "123");
}
[Fact]
public void ResponseThenRequestHeaders_Add_Throws()
{
WebHeaderCollection w = new WebHeaderCollection();
w[HttpResponseHeader.ContentLength] = "123";
Assert.Throws<InvalidOperationException>(() => w[HttpRequestHeader.Accept] = "text/json");
}
[Fact]
public void ResponseHeader_QueryRequest_Throws()
{
WebHeaderCollection w = new WebHeaderCollection();
w[HttpResponseHeader.ContentLength] = "123";
Assert.Throws<InvalidOperationException>(() => w[HttpRequestHeader.Accept]);
}
[Fact]
public void RequestHeader_QueryResponse_Throws()
{
WebHeaderCollection w = new WebHeaderCollection();
w[HttpRequestHeader.Accept] = "text/json";
Assert.Throws<InvalidOperationException>(() => w[HttpResponseHeader.ContentLength]);
}
[Fact]
public void Setter_ValidName_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w["Accept"] = "text/json";
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void Setter_NullOrEmptyName_Throws(string name)
{
WebHeaderCollection w = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentNullException>("name", () => w[name] = "test");
}
public static object[][] InvalidNames = {
new object[] { "(" },
new object[] { "\u1234" },
new object[] { "\u0019" }
};
[Theory, MemberData(nameof(InvalidNames))]
public void Setter_InvalidName_Throws(string name)
{
WebHeaderCollection w = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentException>("name", () => w[name] = "test");
}
public static object[][] InvalidValues = {
new object[] { "value1\rvalue2\r" },
new object[] { "value1\nvalue2\r" },
new object[] { "value1\u007fvalue2" },
new object[] { "value1\r\nvalue2" },
new object[] { "value1\u0019value2" }
};
[Theory, MemberData(nameof(InvalidValues))]
public void Setter_InvalidValue_Throws(string value)
{
WebHeaderCollection w = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentException>("value", () => w["custom"] = value);
}
public static object[][] ValidValues = {
new object[] { null },
new object[] { "" },
new object[] { "value1\r\n" },
new object[] { "value1\tvalue2" },
new object[] { "value1\r\n\tvalue2" },
new object[] { "value1\r\n value2" }
};
[Theory, MemberData(nameof(ValidValues))]
public void Setter_ValidValue_Success(string value)
{
WebHeaderCollection w = new WebHeaderCollection();
w["custom"] = value;
}
[Theory]
[InlineData("name", "name")]
[InlineData("name", "NaMe")]
[InlineData("nAmE", "name")]
public void Setter_SameHeaderTwice_Success(string firstName, string secondName)
{
WebHeaderCollection w = new WebHeaderCollection();
w[firstName] = "first";
w[secondName] = "second";
Assert.Equal(1, w.Count);
Assert.NotEmpty(w);
Assert.NotEmpty(w.AllKeys);
Assert.Equal(new[] { firstName }, w.AllKeys);
Assert.Equal("second", w[firstName]);
Assert.Equal("second", w[secondName]);
}
[Theory]
[InlineData("name")]
[InlineData("nAMe")]
public void Remove_HeaderExists_RemovesFromCollection(string name)
{
var headers = new WebHeaderCollection()
{
{ "name", "value" }
};
headers.Remove(name);
Assert.Empty(headers);
headers.Remove(name);
Assert.Empty(headers);
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void Remove_NullOrEmptyHeader_ThrowsArgumentNullException(string name)
{
var headers = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentNullException>("name", () => headers.Remove(name));
}
[Theory]
[InlineData(" \r \t \n")]
[InlineData(" name ")]
[MemberData(nameof(InvalidValues))]
public void Remove_InvalidHeader_ThrowsArgumentException(string name)
{
var headers = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentException>("name", () => headers.Remove(name));
}
[Fact]
public void Remove_IllegalCharacter_Throws()
{
WebHeaderCollection w = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentException>("name", () => w.Remove("{"));
}
[Fact]
public void Remove_EmptyCollection_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Remove("foo");
Assert.Equal(0, w.Count);
Assert.Empty(w);
Assert.Empty(w.AllKeys);
}
[Theory]
[InlineData("name", "name")]
[InlineData("name", "NaMe")]
public void Remove_SetThenRemove_Success(string setName, string removeName)
{
WebHeaderCollection w = new WebHeaderCollection();
w[setName] = "value";
w.Remove(removeName);
Assert.Equal(0, w.Count);
Assert.Empty(w);
Assert.Empty(w.AllKeys);
}
[Theory]
[InlineData("name", "name")]
[InlineData("name", "NaMe")]
public void Remove_SetTwoThenRemoveOne_Success(string setName, string removeName)
{
WebHeaderCollection w = new WebHeaderCollection();
w[setName] = "value";
w["foo"] = "bar";
w.Remove(removeName);
Assert.Equal(1, w.Count);
Assert.NotEmpty(w);
Assert.NotEmpty(w.AllKeys);
Assert.Equal(new[] { "foo" }, w.AllKeys);
Assert.Equal("bar", w["foo"]);
}
[Fact]
public void Getter_EmptyCollection_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
Assert.Null(w["name"]);
Assert.Equal(0, w.Count);
Assert.Empty(w);
Assert.Empty(w.AllKeys);
}
[Fact]
public void Getter_NonEmptyCollectionNonExistentHeader_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w["name"] = "value";
Assert.Null(w["foo"]);
Assert.Equal(1, w.Count);
Assert.NotEmpty(w);
Assert.NotEmpty(w.AllKeys);
Assert.Equal(new[] { "name" }, w.AllKeys);
Assert.Equal("value", w["name"]);
}
[Fact]
public void Getter_Success()
{
string[] keys = { "Accept", "uPgRaDe", "Custom" };
string[] values = { "text/plain, text/html", " HTTP/2.0 , SHTTP/1.3, , RTA/x11 ", "\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\"" };
WebHeaderCollection w = new WebHeaderCollection();
for (int i = 0; i < keys.Length; ++i)
{
string key = keys[i];
string value = values[i];
w[key] = value;
}
for (int i = 0; i < keys.Length; ++i)
{
string key = keys[i];
string expected = values[i].Trim();
Assert.Equal(expected, w[key]);
Assert.Equal(expected, w[key.ToUpperInvariant()]);
Assert.Equal(expected, w[key.ToLowerInvariant()]);
}
}
[Fact]
public void ToString_Empty_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
Assert.Equal("\r\n", w.ToString());
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void ToString_SingleHeaderWithEmptyValue_Success(string value)
{
WebHeaderCollection w = new WebHeaderCollection();
w["name"] = value;
Assert.Equal("name: \r\n\r\n", w.ToString());
}
[Fact]
public void ToString_NotEmpty_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w["Accept"] = "text/plain";
w["Content-Length"] = "123";
Assert.Equal(
"Accept: text/plain\r\nContent-Length: 123\r\n\r\n",
w.ToString());
}
[Fact]
public void IterateCollection_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w["Accept"] = "text/plain";
w["Content-Length"] = "123";
string result = "";
foreach (var item in w)
{
result += item;
}
Assert.Equal("AcceptContent-Length", result);
}
[Fact]
public void Enumerator_Success()
{
string item1 = "Accept";
string item2 = "Content-Length";
string item3 = "Name";
WebHeaderCollection w = new WebHeaderCollection();
w[item1] = "text/plain";
w[item2] = "123";
w[item3] = "value";
IEnumerable collection = w;
IEnumerator e = collection.GetEnumerator();
for (int i = 0; i < 2; i++)
{
// Not started
Assert.Throws<InvalidOperationException>(() => e.Current);
Assert.True(e.MoveNext());
Assert.Same(item1, e.Current);
Assert.True(e.MoveNext());
Assert.Same(item2, e.Current);
Assert.True(e.MoveNext());
Assert.Same(item3, e.Current);
Assert.False(e.MoveNext());
Assert.False(e.MoveNext());
Assert.False(e.MoveNext());
// Ended
Assert.Throws<InvalidOperationException>(() => e.Current);
e.Reset();
}
}
public static IEnumerable<object[]> SerializeDeserialize_Roundtrip_MemberData()
{
for (int i = 0; i < 10; i++)
{
var wc = new WebHeaderCollection();
for (int j = 0; j < i; j++)
{
wc[$"header{j}"] = $"value{j}";
}
yield return new object[] { wc };
}
}
public static IEnumerable<object[]> Add_Value_TestData()
{
yield return new object[] { null, string.Empty };
yield return new object[] { string.Empty, string.Empty };
yield return new object[] { "VaLue", "VaLue" };
yield return new object[] { " value ", "value" };
// Documentation says this should fail but it does not.
string longString = new string('a', 65536);
yield return new object[] { longString, longString };
}
[Theory]
[MemberData(nameof(Add_Value_TestData))]
public void Add_ValidValue_Success(string value, string expectedValue)
{
var headers = new WebHeaderCollection
{
{ "name", value }
};
Assert.Equal(expectedValue, headers["name"]);
}
[Fact]
public void Add_HeaderAlreadyExists_AppendsValue()
{
var headers = new WebHeaderCollection
{
{ "name", "value1" },
{ "name", null },
{ "name", "value2" },
{ "NAME", "value3" },
{ "name", "" }
};
Assert.Equal("value1,,value2,value3,", headers["name"]);
}
[Fact]
public void Add_NullName_ThrowsArgumentNullException()
{
var headers = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentNullException>("name", () => headers.Add(null, "value"));
}
[Theory]
[InlineData("")]
[InlineData("(")]
[InlineData("\r \t \n")]
[InlineData(" name ")]
[MemberData(nameof(InvalidValues))]
public void Add_InvalidName_ThrowsArgumentException(string name)
{
var headers = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentException>("name", () => headers.Add(name, "value"));
}
[Theory]
[MemberData(nameof(InvalidValues))]
public void Add_InvalidValue_ThrowsArgumentException(string value)
{
var headers = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentException>("value", () => headers.Add("name", value));
}
[Fact]
public void Add_ValidHeader_AddsToHeaders()
{
var headers = new WebHeaderCollection()
{
"name:value1",
"name:",
"NaMe:value2",
"name: ",
};
Assert.Equal("value1,,value2,", headers["name"]);
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void Add_NullHeader_ThrowsArgumentNullException(string header)
{
var headers = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentNullException>("header", () => headers.Add(header));
}
[Theory]
[InlineData(" \r \t \n", "header")]
[InlineData("nocolon", "header")]
[InlineData(" :value", "name")]
[InlineData("name :value", "name")]
[InlineData("name:va\rlue", "value")]
public void Add_InvalidHeader_ThrowsArgumentException(string header, string paramName)
{
var headers = new WebHeaderCollection();
AssertExtensions.Throws<ArgumentException>(paramName, () => headers.Add(header));
}
private const string HeaderType = "Set-Cookie";
private const string Cookie1 = "locale=en; path=/; expires=Fri, 05 Oct 2018 06:28:57 -0000";
private const string Cookie2 = "uuid=123abc; path=/; expires=Fri, 05 Oct 2018 06:28:57 -0000; secure; HttpOnly";
private const string Cookie3 = "country=US; path=/; expires=Fri, 05 Oct 2018 06:28:57 -0000";
private const string Cookie4 = "m_session=session1; path=/; expires=Sun, 08 Oct 2017 00:28:57 -0000; secure; HttpOnly";
private const string Cookie1NoAttribute = "locale=en";
private const string Cookie2NoAttribute = "uuid=123abc";
private const string Cookie3NoAttribute = "country=US";
private const string Cookie4NoAttribute = "m_session=session1";
private const string CookieInvalid = "helloWorld";
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Mono, "Does not work in Mono")]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Requires fix shipping in .NET 4.7.2")]
public void GetValues_MultipleSetCookieHeadersWithExpiresAttribute_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add(HeaderType, Cookie1);
w.Add(HeaderType, Cookie2);
w.Add(HeaderType, Cookie3);
w.Add(HeaderType, Cookie4);
string[] values = w.GetValues(HeaderType);
Assert.Equal(4, values.Length);
Assert.Equal(Cookie1, values[0]);
Assert.Equal(Cookie2, values[1]);
Assert.Equal(Cookie3, values[2]);
Assert.Equal(Cookie4, values[3]);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Mono, "Does not work in Mono")]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Requires fix shipping in .NET 4.7.2")]
public void GetValues_SingleSetCookieHeaderWithMultipleCookiesWithExpiresAttribute_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add(HeaderType, Cookie1 + "," + Cookie2 + "," + Cookie3 + "," + Cookie4);
string[] values = w.GetValues(HeaderType);
Assert.Equal(4, values.Length);
Assert.Equal(Cookie1, values[0]);
Assert.Equal(Cookie2, values[1]);
Assert.Equal(Cookie3, values[2]);
Assert.Equal(Cookie4, values[3]);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Requires fix shipping in .NET 4.7.2")]
public void GetValues_MultipleSetCookieHeadersWithNoAttribute_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add(HeaderType, Cookie1NoAttribute);
w.Add(HeaderType, Cookie2NoAttribute);
w.Add(HeaderType, Cookie3NoAttribute);
w.Add(HeaderType, Cookie4NoAttribute);
string[] values = w.GetValues(HeaderType);
Assert.Equal(4, values.Length);
Assert.Equal(Cookie1NoAttribute, values[0]);
Assert.Equal(Cookie2NoAttribute, values[1]);
Assert.Equal(Cookie3NoAttribute, values[2]);
Assert.Equal(Cookie4NoAttribute, values[3]);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Requires fix shipping in .NET 4.7.2")]
public void GetValues_SingleSetCookieHeaderWithMultipleCookiesWithNoAttribute_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add(HeaderType, Cookie1NoAttribute + "," + Cookie2NoAttribute + "," + Cookie3NoAttribute + "," + Cookie4NoAttribute);
string[] values = w.GetValues(HeaderType);
Assert.Equal(4, values.Length);
Assert.Equal(Cookie1NoAttribute, values[0]);
Assert.Equal(Cookie2NoAttribute, values[1]);
Assert.Equal(Cookie3NoAttribute, values[2]);
Assert.Equal(Cookie4NoAttribute, values[3]);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Mono, "Does not work in Mono")]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Requires fix shipping in .NET 4.7.2")]
public void GetValues_InvalidSetCookieHeader_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add(HeaderType, CookieInvalid);
string[] values = w.GetValues(HeaderType);
Assert.Equal(0, values.Length);
}
[Fact]
public void GetValues_MultipleValuesHeader_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
string headerType = "Accept";
w.Add(headerType, "text/plain, text/html");
string[] values = w.GetValues(headerType);
Assert.Equal(2, values.Length);
Assert.Equal("text/plain", values[0]);
Assert.Equal("text/html", values[1]);
}
[Fact]
public void HttpRequestHeader_Add_Rmemove_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add(HttpRequestHeader.Warning, "Warning1");
Assert.Equal(1, w.Count);
Assert.Equal("Warning1", w[HttpRequestHeader.Warning]);
Assert.Equal("Warning", w.AllKeys[0]);
w.Remove(HttpRequestHeader.Warning);
Assert.Equal(0, w.Count);
}
[Fact]
public void HttpRequestHeader_Get_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add("header1", "value1");
w.Add("header1", "value2");
string[] values = w.GetValues(0);
Assert.Equal("value1", values[0]);
Assert.Equal("value2", values[1]);
}
[Fact]
public void HttpRequestHeader_ToByteArray_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add("header1", "value1");
w.Add("header1", "value2");
byte[] byteArr = w.ToByteArray();
Assert.NotEmpty(byteArr);
}
[Fact]
public void HttpRequestHeader_GetKey_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add("header1", "value1");
w.Add("header1", "value2");
Assert.NotEmpty(w.GetKey(0));
}
[Fact]
public void HttpRequestHeader_GetValues_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add("header1", "value1");
Assert.Equal("value1", w.GetValues("header1")[0]);
}
[Fact]
public void HttpRequestHeader_Clear_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add("header1", "value1");
w.Add("header1", "value2");
w.Clear();
Assert.Equal(0, w.Count);
}
[Fact]
public void HttpRequestHeader_IsRestricted_Success()
{
Assert.True(WebHeaderCollection.IsRestricted("Accept"));
Assert.False(WebHeaderCollection.IsRestricted("Age"));
Assert.False(WebHeaderCollection.IsRestricted("Accept", true));
}
[Fact]
public void HttpRequestHeader_AddHeader_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add(HttpRequestHeader.ContentLength, "10");
w.Add(HttpRequestHeader.ContentType, "text/html");
Assert.Equal(2,w.Count);
}
[Fact]
public void WebHeaderCollection_Keys_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Add(HttpRequestHeader.ContentLength, "10");
w.Add(HttpRequestHeader.ContentType, "text/html");
Assert.Equal(2, w.Keys.Count);
}
[Fact]
public void HttpRequestHeader_AddHeader_Failure()
{
WebHeaderCollection w = new WebHeaderCollection();
char[] arr = new char[ushort.MaxValue + 1];
string maxStr = new string(arr);
AssertExtensions.Throws<ArgumentException>("value", () => w.Add(HttpRequestHeader.ContentLength,maxStr));
AssertExtensions.Throws<ArgumentException>("value", () => w.Add("ContentLength", maxStr));
}
[Fact]
public void HttpResponseHeader_Set_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Set(HttpResponseHeader.ProxyAuthenticate, "value123");
Assert.Equal("value123", w[HttpResponseHeader.ProxyAuthenticate]);
}
[Fact]
public void HttpRequestHeader_Set_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Set(HttpRequestHeader.Connection, "keep-alive");
Assert.Equal(1, w.Count);
Assert.Equal("keep-alive", w[HttpRequestHeader.Connection]);
Assert.Equal("Connection", w.AllKeys[0]);
}
[Fact]
public void NameValue_Set_Success()
{
WebHeaderCollection w = new WebHeaderCollection();
w.Set("firstName", "first");
Assert.Equal(1, w.Count);
Assert.NotEmpty(w);
Assert.NotEmpty(w.AllKeys);
Assert.Equal(new[] { "firstName" }, w.AllKeys);
Assert.Equal("first", w["firstName"]);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Storage;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices
{
public class PersistentStorageTests : IDisposable
{
private const int NumThreads = 10;
private const string PersistentFolderPrefix = "PersistentStorageTests_";
private readonly Encoding _encoding = Encoding.UTF8;
private readonly IOptionService _persistentEnabledOptionService = new OptionServiceMock(new Dictionary<IOption, object>
{
{ PersistentStorageOptions.Enabled, true },
{ PersistentStorageOptions.EsentPerformanceMonitor, false }
});
private readonly string _persistentFolder;
private const string Data1 = "Hello ESENT";
private const string Data2 = "Goodbye ESENT";
public PersistentStorageTests()
{
_persistentFolder = Path.Combine(Path.GetTempPath(), PersistentFolderPrefix + Guid.NewGuid());
Directory.CreateDirectory(_persistentFolder);
int workerThreads, completionPortThreads;
ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
ThreadPool.SetMinThreads(Math.Max(workerThreads, NumThreads), completionPortThreads);
}
public void Dispose()
{
if (Directory.Exists(_persistentFolder))
{
Directory.Delete(_persistentFolder, true);
}
}
private void CleanUpPersistentFolder()
{
}
[Fact]
public async Task PersistentService_Solution_WriteReadDifferentInstances()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_WriteReadDifferentInstances1";
var streamName2 = "PersistentService_Solution_WriteReadDifferentInstances2";
using (var storage = GetStorage(solution))
{
Assert.True(await storage.WriteStreamAsync(streamName1, EncodeString(Data1)));
Assert.True(await storage.WriteStreamAsync(streamName2, EncodeString(Data2)));
}
using (var storage = GetStorage(solution))
{
Assert.Equal(Data1, ReadStringToEnd(await storage.ReadStreamAsync(streamName1)));
Assert.Equal(Data2, ReadStringToEnd(await storage.ReadStreamAsync(streamName2)));
}
}
[Fact]
public async Task PersistentService_Solution_WriteReadReopenSolution()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_WriteReadReopenSolution1";
var streamName2 = "PersistentService_Solution_WriteReadReopenSolution2";
using (var storage = GetStorage(solution))
{
Assert.True(await storage.WriteStreamAsync(streamName1, EncodeString(Data1)));
Assert.True(await storage.WriteStreamAsync(streamName2, EncodeString(Data2)));
}
solution = CreateOrOpenSolution();
using (var storage = GetStorage(solution))
{
Assert.Equal(Data1, ReadStringToEnd(await storage.ReadStreamAsync(streamName1)));
Assert.Equal(Data2, ReadStringToEnd(await storage.ReadStreamAsync(streamName2)));
}
}
[Fact]
public async Task PersistentService_Solution_WriteReadSameInstance()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_WriteReadSameInstance1";
var streamName2 = "PersistentService_Solution_WriteReadSameInstance2";
using (var storage = GetStorage(solution))
{
Assert.True(await storage.WriteStreamAsync(streamName1, EncodeString(Data1)));
Assert.True(await storage.WriteStreamAsync(streamName2, EncodeString(Data2)));
Assert.Equal(Data1, ReadStringToEnd(await storage.ReadStreamAsync(streamName1)));
Assert.Equal(Data2, ReadStringToEnd(await storage.ReadStreamAsync(streamName2)));
}
}
[Fact]
public async Task PersistentService_Project_WriteReadSameInstance()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Project_WriteReadSameInstance1";
var streamName2 = "PersistentService_Project_WriteReadSameInstance2";
using (var storage = GetStorage(solution))
{
var project = solution.Projects.Single();
Assert.True(await storage.WriteStreamAsync(project, streamName1, EncodeString(Data1)));
Assert.True(await storage.WriteStreamAsync(project, streamName2, EncodeString(Data2)));
Assert.Equal(Data1, ReadStringToEnd(await storage.ReadStreamAsync(project, streamName1)));
Assert.Equal(Data2, ReadStringToEnd(await storage.ReadStreamAsync(project, streamName2)));
}
}
[Fact]
public async Task PersistentService_Document_WriteReadSameInstance()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Document_WriteReadSameInstance1";
var streamName2 = "PersistentService_Document_WriteReadSameInstance2";
using (var storage = GetStorage(solution))
{
var document = solution.Projects.Single().Documents.Single();
Assert.True(await storage.WriteStreamAsync(document, streamName1, EncodeString(Data1)));
Assert.True(await storage.WriteStreamAsync(document, streamName2, EncodeString(Data2)));
Assert.Equal(Data1, ReadStringToEnd(await storage.ReadStreamAsync(document, streamName1)));
Assert.Equal(Data2, ReadStringToEnd(await storage.ReadStreamAsync(document, streamName2)));
}
}
[Fact]
public async Task PersistentService_Solution_SimultaneousWrites()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_SimultaneousWrites1";
using (var storage = GetStorage(solution))
{
DoSimultaneousWrites(s => storage.WriteStreamAsync(streamName1, EncodeString(s)));
int value = int.Parse(ReadStringToEnd(await storage.ReadStreamAsync(streamName1)));
Assert.True(value >= 0);
Assert.True(value < NumThreads);
}
}
[Fact]
public async Task PersistentService_Project_SimultaneousWrites()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Project_SimultaneousWrites1";
using (var storage = GetStorage(solution))
{
DoSimultaneousWrites(s => storage.WriteStreamAsync(solution.Projects.Single(), streamName1, EncodeString(s)));
int value = int.Parse(ReadStringToEnd(await storage.ReadStreamAsync(solution.Projects.Single(), streamName1)));
Assert.True(value >= 0);
Assert.True(value < NumThreads);
}
}
[Fact]
public async Task PersistentService_Document_SimultaneousWrites()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Document_SimultaneousWrites1";
using (var storage = GetStorage(solution))
{
DoSimultaneousWrites(s => storage.WriteStreamAsync(solution.Projects.Single().Documents.Single(), streamName1, EncodeString(s)));
int value = int.Parse(ReadStringToEnd(await storage.ReadStreamAsync(solution.Projects.Single().Documents.Single(), streamName1)));
Assert.True(value >= 0);
Assert.True(value < NumThreads);
}
}
private void DoSimultaneousWrites(Func<string, Task> write)
{
var barrier = new Barrier(NumThreads);
var countdown = new CountdownEvent(NumThreads);
for (int i = 0; i < NumThreads; i++)
{
ThreadPool.QueueUserWorkItem(s =>
{
int id = (int)s;
barrier.SignalAndWait();
write(id + "").Wait();
countdown.Signal();
}, i);
}
countdown.Wait();
}
[Fact]
public async Task PersistentService_Solution_SimultaneousReads()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Solution_SimultaneousReads1";
using (var storage = GetStorage(solution))
{
await storage.WriteStreamAsync(streamName1, EncodeString(Data1));
DoSimultaneousReads(async () => ReadStringToEnd(await storage.ReadStreamAsync(streamName1)), Data1);
}
}
[Fact]
public async Task PersistentService_Project_SimultaneousReads()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Project_SimultaneousReads1";
using (var storage = GetStorage(solution))
{
await storage.WriteStreamAsync(solution.Projects.Single(), streamName1, EncodeString(Data1));
DoSimultaneousReads(async () => ReadStringToEnd(await storage.ReadStreamAsync(solution.Projects.Single(), streamName1)), Data1);
}
}
[Fact]
public async Task PersistentService_Document_SimultaneousReads()
{
var solution = CreateOrOpenSolution();
var streamName1 = "PersistentService_Document_SimultaneousReads1";
using (var storage = GetStorage(solution))
{
await storage.WriteStreamAsync(solution.Projects.Single().Documents.Single(), streamName1, EncodeString(Data1));
DoSimultaneousReads(async () => ReadStringToEnd(await storage.ReadStreamAsync(solution.Projects.Single().Documents.Single(), streamName1)), Data1);
}
}
private void DoSimultaneousReads(Func<Task<string>> read, string expectedValue)
{
var barrier = new Barrier(NumThreads);
var countdown = new CountdownEvent(NumThreads);
for (int i = 0; i < NumThreads; i++)
{
Task.Run(async () =>
{
barrier.SignalAndWait();
Assert.Equal(expectedValue, await read());
countdown.Signal();
});
}
countdown.Wait();
}
private Solution CreateOrOpenSolution()
{
string solutionFile = Path.Combine(_persistentFolder, "Solution1.sln");
bool newSolution;
if (newSolution = !File.Exists(solutionFile))
{
File.WriteAllText(solutionFile, "");
}
var info = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), solutionFile);
var workspace = new AdhocWorkspace();
workspace.AddSolution(info);
var solution = workspace.CurrentSolution;
if (newSolution)
{
string projectFile = Path.Combine(Path.GetDirectoryName(solutionFile), "Project1.csproj");
File.WriteAllText(projectFile, "");
solution = solution.AddProject(ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "Project1", "Project1", LanguageNames.CSharp, projectFile));
var project = solution.Projects.Single();
string documentFile = Path.Combine(Path.GetDirectoryName(projectFile), "Document1.cs");
File.WriteAllText(documentFile, "");
solution = solution.AddDocument(DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "Document1", filePath: documentFile));
}
return solution;
}
private IPersistentStorage GetStorage(Solution solution)
{
var storage = new PersistentStorageService(_persistentEnabledOptionService, testing: true).GetStorage(solution);
Assert.NotEqual(PersistentStorageService.NoOpPersistentStorageInstance, storage);
return storage;
}
private Stream EncodeString(string text)
{
var bytes = _encoding.GetBytes(text);
var stream = new MemoryStream(bytes);
return stream;
}
private string ReadStringToEnd(Stream stream)
{
using (stream)
{
var bytes = new byte[stream.Length];
int count = 0;
while (count < stream.Length)
{
count = stream.Read(bytes, count, (int)stream.Length - count);
}
return _encoding.GetString(bytes);
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (C) LogicKing.com
//-----------------------------------------------------------------------------
function createDataControl(%type, %position, %extent, %profile)
{
%guiElement = "";
switch$(%type)
{
case "text": %guiElement = new GuiTextCtrl() {
canSaveDynamicFields = "0";
Enabled = "1";
isContainer = "0";
HorizSizing = "right";
VertSizing = "bottom";
position = "15 45";
Extent = "64 18";
MinExtent = "8 2";
canSave = "1";
Visible = "1";
hovertime = "1000";
Margin = "0 0 0 0";
Padding = "0 0 0 0";
AnchorTop = "1";
AnchorBottom = "0";
AnchorLeft = "1";
AnchorRight = "0";
maxLength = "1024";
Profile = %profile;
};
case "textEdit": %guiElement = new GuiTextEditCtrl() {
canSaveDynamicFields = "0";
Enabled = "1";
isContainer = "0";
HorizSizing = "right";
VertSizing = "bottom";
position = "10 20";
Extent = "70 18";
MinExtent = "8 2";
canSave = "1";
Visible = "1";
hovertime = "1000";
Margin = "0 0 0 0";
Padding = "0 0 0 0";
AnchorTop = "1";
AnchorBottom = "0";
AnchorLeft = "1";
AnchorRight = "0";
maxLength = "1024";
historySize = "0";
password = "0";
tabComplete = "0";
sinkAllKeyEvents = "0";
password = "0";
passwordMask = "*";
};
case "button": %guiElement = new GuiButtonCtrl() {
canSaveDynamicFields = "0";
Enabled = "1";
isContainer = "0";
HorizSizing = "right";
VertSizing = "bottom";
position = "10 20";
Extent = "40 18";
MinExtent = "8 2";
canSave = "1";
Visible = "1";
hovertime = "1000";
text = "";
groupNum = "-1";
buttonType = "PushButton";
useMouseEvents = "0";
};
case "list": %guiElement = new GuiPopUpMenuCtrl() {
canSaveDynamicFields = "0";
Enabled = "1";
isContainer = "0";
HorizSizing = "right";
VertSizing = "bottom";
position = "83 149";
Extent = "64 20";
MinExtent = "8 2";
canSave = "1";
Visible = "1";
hovertime = "1000";
Margin = "0 0 0 0";
Padding = "0 0 0 0";
AnchorTop = "1";
AnchorBottom = "0";
AnchorLeft = "1";
AnchorRight = "0";
maxLength = "1024";
maxPopupHeight = "200";
sbUsesNAColor = "0";
reverseTextList = "0";
bitmapBounds = "16 16";
};
case "icon": %guiElement = new GuiBitmapButtonCtrl() {
canSaveDynamicFields = "0";
Enabled = "1";
isContainer = "0";
HorizSizing = "right";
VertSizing = "bottom";
position = "10 10";
Extent = "48 48";
MinExtent = "8 2";
canSave = "1";
Visible = "1";
hovertime = "1000";
groupNum = "-1";
buttonType = "PushButton";
useMouseEvents = "0";
};
case "iconButton": %guiElement = new GuiIconButtonCtrl() {
canSaveDynamicFields = "0";
Enabled = "1";
isContainer = "0";
HorizSizing = "right";
VertSizing = "bottom";
position = "447 4";
Extent = "140 30";
MinExtent = "8 2";
canSave = "1";
Visible = "1";
hovertime = "1000";
text = "";
groupNum = "-1";
buttonType = "PushButton";
useMouseEvents = "0";
buttonMargin = "4 4";
iconBitmap = "";
iconLocation = "Left";
sizeIconToButton = "0";
textLocation = "Right";
textMargin = "10";
};
case "rollOut": %guiElement = new GuiRolloutCtrl() {
canSaveDynamicFields = "0";
Enabled = "1";
isContainer = "1";
Profile = "LogicMechanicsGuiRollOutProfile";
HorizSizing = "right";
VertSizing = "bottom";
position = "86 52";
Extent = "132 40";
MinExtent = "8 2";
canSave = "0";
Visible = "1";
hovertime = "1000";
Caption = "";
Margin = "2 2";
DefaultHeight = "40";
Collapsed = "1";
ClickCollapse = "1";
};
case "stack": %guiElement = new GuiStackControl() {
StackingType = "Vertical";
HorizStacking = "Left to Right";
VertStacking = "Top to Bottom";
Padding = "0";
canSaveDynamicFields = "0";
Enabled = "1";
isContainer = "1";
HorizSizing = "right";
VertSizing = "bottom";
position = "16 38";
Extent = "204 16";
MinExtent = "16 16";
canSave = "1";
Visible = "1";
hovertime = "1000";
};
case "editorTextEdit": %guiElement = new GuiTextEditCtrl() {
canSaveDynamicFields = "0";
Enabled = "1";
isContainer = "0";
Profile = "GuiInspectorTextEditProfile";
HorizSizing = "right";
VertSizing = "bottom";
position = "0 0";
Extent = "245 18";
MinExtent = "8 2";
canSave = "1";
Visible = "1";
hovertime = "1000";
Margin = "0 0 0 0";
Padding = "0 0 0 0";
AnchorTop = "1";
AnchorBottom = "0";
AnchorLeft = "1";
AnchorRight = "0";
maxLength = "1024";
historySize = "0";
password = "0";
tabComplete = "0";
sinkAllKeyEvents = "0";
password = "0";
passwordMask = "*";
};
case "checkBox": %guiElement = new GuiCheckBoxCtrl() {
canSaveDynamicFields = "0";
Enabled = "1";
isContainer = "0";
HorizSizing = "right";
VertSizing = "bottom";
position = "0 0";
Extent = "50 18";
MinExtent = "8 2";
canSave = "1";
Visible = "1";
Command = " ";
hovertime = "1000";
text = "";
groupNum = "-1";
buttonType = "ToggleButton";
useMouseEvents = "0";
useInactiveState = "0";
};
case "progress": %guiElement = new GuiProgressCtrl() {
canSaveDynamicFields = "0";
Enabled = "1";
isContainer = "0";
Profile = "LogicMechanicsProgressProfile";
HorizSizing = "right";
VertSizing = "bottom";
Position = "0 0";
Extent = "64 21";
MinExtent = "8 2";
canSave = "1";
Visible = "1";
tooltipprofile = "GuiToolTipProfile";
hovertime = "1000";
Margin = "0 0 0 0";
Padding = "0 0 0 0";
AnchorTop = "1";
AnchorBottom = "0";
AnchorLeft = "1";
AnchorRight = "0";
maxLength = "1024";
};
}
%guiElement.setPosition(getWord(%position, 0), getWord(%position, 1));
%guiElement.setExtent(getWord(%extent, 0), getWord(%extent, 1));
return %guiElement;
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Analysis.Analyzer;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter.Ast;
using Microsoft.PythonTools.Interpreter.Default;
using Microsoft.PythonTools.Parsing;
namespace Microsoft.PythonTools.Interpreter {
/// <summary>
/// Provides access to an on-disk store of cached intellisense information.
/// </summary>
public sealed class PythonTypeDatabase : ITypeDatabaseReader {
private readonly PythonInterpreterFactoryWithDatabase _factory;
private readonly SharedDatabaseState _sharedState;
/// <summary>
/// Gets the version of the analysis format that this class reads.
/// </summary>
public static readonly int CurrentVersion = 25;
private static string _completionDatabasePath;
private static string _referencesDatabasePath;
private static string _baselineDatabasePath;
public PythonTypeDatabase(
PythonInterpreterFactoryWithDatabase factory,
IEnumerable<string> databaseDirectories = null,
PythonTypeDatabase innerDatabase = null
) {
if (innerDatabase != null && factory.Configuration.Version != innerDatabase.LanguageVersion) {
throw new InvalidOperationException("Language versions do not match");
}
_factory = factory;
if (innerDatabase != null) {
_sharedState = new SharedDatabaseState(innerDatabase._sharedState);
} else {
_sharedState = new SharedDatabaseState(_factory.Configuration.Version);
}
if (databaseDirectories != null) {
foreach (var d in databaseDirectories) {
LoadDatabase(d);
}
}
_sharedState.ListenForCorruptDatabase(this);
}
private PythonTypeDatabase(
PythonInterpreterFactoryWithDatabase factory,
string databaseDirectory,
bool isDefaultDatabase
) {
_factory = factory;
_sharedState = new SharedDatabaseState(
factory.Configuration.Version,
databaseDirectory,
defaultDatabase: isDefaultDatabase
);
}
public PythonTypeDatabase Clone() {
return new PythonTypeDatabase(_factory, null, this);
}
public PythonTypeDatabase CloneWithNewFactory(PythonInterpreterFactoryWithDatabase newFactory) {
return new PythonTypeDatabase(newFactory, null, this);
}
public PythonTypeDatabase CloneWithNewBuiltins(IBuiltinPythonModule newBuiltins) {
var newDb = new PythonTypeDatabase(_factory, null, this);
newDb._sharedState.BuiltinModule = newBuiltins;
return newDb;
}
public IPythonInterpreterFactoryWithDatabase InterpreterFactory {
get {
return _factory;
}
}
/// <summary>
/// Gets the Python version associated with this database.
/// </summary>
public Version LanguageVersion {
get {
return _factory.Configuration.Version;
}
}
/// <summary>
/// Loads modules from the specified path. Except for a builtins module,
/// these will override any currently loaded modules.
/// </summary>
public void LoadDatabase(string databasePath) {
_sharedState.LoadDatabase(databasePath);
}
/// <summary>
/// Asynchrously loads the specified extension module into the type
/// database making the completions available.
///
/// If the module has not already been analyzed it will be analyzed and
/// then loaded.
///
/// If the specified module was already loaded it replaces the existing
/// module.
///
/// Returns a new Task which can be blocked upon until the analysis of
/// the new extension module is available.
///
/// If the extension module cannot be analyzed an exception is reproted.
/// </summary>
/// <param name="cancellationToken">A cancellation token which can be
/// used to cancel the async loading of the module</param>
/// <param name="extensionModuleFilename">The filename of the extension
/// module to be loaded</param>
/// <param name="interpreter">The Python interprefer which will be used
/// to analyze the extension module.</param>
/// <param name="moduleName">The module name of the extension module.</param>
public void LoadExtensionModule(
ModulePath moduleName,
CancellationToken cancellationToken = default(CancellationToken)
) {
var loader = new ExtensionModuleLoader(
this,
_factory,
moduleName,
cancellationToken
);
loader.LoadExtensionModule();
}
public void AddModule(string moduleName, IPythonModule module) {
_sharedState.Modules[moduleName] = module;
}
public bool UnloadModule(string moduleName) {
IPythonModule dummy;
return _sharedState.Modules.TryRemove(moduleName, out dummy);
}
private static Task MakeExceptionTask(Exception e) {
var res = new TaskCompletionSource<Task>();
res.SetException(e);
return res.Task;
}
internal class ExtensionModuleLoader {
private readonly PythonTypeDatabase _typeDb;
private readonly IPythonInterpreterFactory _factory;
private readonly ModulePath _moduleName;
private readonly CancellationToken _cancel;
const string _extensionModuleInfoFile = "extensions.$list";
public ExtensionModuleLoader(PythonTypeDatabase typeDb, IPythonInterpreterFactory factory, ModulePath moduleName, CancellationToken cancel) {
_typeDb = typeDb;
_factory = factory;
_moduleName = moduleName;
_cancel = cancel;
}
public void LoadExtensionModule() {
List<string> existingModules = new List<string>();
string dbFile = null;
// open the file locking it - only one person can look at the "database" of per-project analysis.
using (var fs = OpenProjectExtensionList()) {
dbFile = FindDbFile(_factory, _moduleName.SourceFile, existingModules, dbFile, fs);
if (dbFile == null) {
dbFile = GenerateDbFile(_factory, _moduleName, existingModules, dbFile, fs);
}
}
_typeDb._sharedState.Modules[_moduleName.FullName] = new CPythonModule(_typeDb, _moduleName.FullName, dbFile, false);
}
private FileStream OpenProjectExtensionList() {
Directory.CreateDirectory(ReferencesDatabasePath);
for (int i = 0; i < 50 && !_cancel.IsCancellationRequested; i++) {
try {
return new FileStream(Path.Combine(ReferencesDatabasePath, _extensionModuleInfoFile), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
} catch (IOException) {
if (_cancel.CanBeCanceled) {
_cancel.WaitHandle.WaitOne(100);
} else {
Thread.Sleep(100);
}
}
}
throw new CannotAnalyzeExtensionException("Cannot access per-project extension registry.");
}
private string GenerateDbFile(IPythonInterpreterFactory interpreter, ModulePath moduleName, List<string> existingModules, string dbFile, FileStream fs) {
// we need to generate the DB file
dbFile = Path.Combine(ReferencesDatabasePath, moduleName + ".$project.idb");
int retryCount = 0;
while (File.Exists(dbFile)) {
dbFile = Path.Combine(ReferencesDatabasePath, moduleName + "." + ++retryCount + ".$project.idb");
}
var args = new List<string> {
PythonToolsInstallPath.GetFile("ExtensionScraper.py"),
"scrape",
};
if (moduleName.IsNativeExtension) {
args.Add("-");
args.Add(moduleName.SourceFile);
} else {
args.Add(moduleName.ModuleName);
args.Add(moduleName.LibraryPath);
}
args.Add(Path.ChangeExtension(dbFile, null));
using (var output = interpreter.Run(args.ToArray())) {
if (_cancel.CanBeCanceled) {
if (WaitHandle.WaitAny(new[] { _cancel.WaitHandle, output.WaitHandle }) != 1) {
// we were cancelled
return null;
}
} else {
output.Wait();
}
if (output.ExitCode == 0) {
// [FileName]|interpGuid|interpVersion|DateTimeStamp|[db_file.idb]
// save the new entry in the DB file
existingModules.Add(
String.Format("{0}|{1}|{2}|{3}",
moduleName.SourceFile,
interpreter.Configuration.Id,
new FileInfo(moduleName.SourceFile).LastWriteTime.ToString("O"),
dbFile
)
);
fs.Seek(0, SeekOrigin.Begin);
fs.SetLength(0);
using (var sw = new StreamWriter(fs)) {
sw.Write(String.Join(Environment.NewLine, existingModules));
sw.Flush();
}
} else {
throw new CannotAnalyzeExtensionException(string.Join(Environment.NewLine, output.StandardErrorLines));
}
}
return dbFile;
}
const int extensionModuleFilenameIndex = 0;
const int interpreteIdIndex = 1;
const int extensionTimeStamp = 2;
const int dbFileIndex = 3;
internal static bool AlwaysGenerateDb = false;
/// <summary>
/// Finds the appropriate entry in our database file and returns the name of the .idb file to be loaded or null
/// if we do not have a generated .idb file.
/// </summary>
private static string FindDbFile(IPythonInterpreterFactory interpreter, string extensionModuleFilename, List<string> existingModules, string dbFile, FileStream fs) {
if (AlwaysGenerateDb) {
return null;
}
var reader = new StreamReader(fs);
string line;
while ((line = reader.ReadLine()) != null) {
// [FileName]|interpId|DateTimeStamp|[db_file.idb]
string[] columns = line.Split('|');
if (columns.Length != 5) {
// malformed data...
continue;
}
if (File.Exists(columns[dbFileIndex])) {
// db file still exists
DateTime lastModified;
if (!File.Exists(columns[extensionModuleFilenameIndex]) || // extension has been deleted
!DateTime.TryParseExact(columns[extensionTimeStamp], "O", null, System.Globalization.DateTimeStyles.RoundtripKind, out lastModified) ||
lastModified != File.GetLastWriteTime(columns[extensionModuleFilenameIndex])) { // extension has been modified
// cleanup the stale DB files as we go...
try {
File.Delete(columns[dbFileIndex]);
} catch (IOException) {
} catch (UnauthorizedAccessException) {
}
continue;
}
} else {
continue;
}
// check if this is the file we're looking for...
if (columns[interpreteIdIndex] != interpreter.Configuration.Id ||
String.Compare(columns[extensionModuleFilenameIndex], extensionModuleFilename, StringComparison.OrdinalIgnoreCase) != 0) { // not our interpreter
// nope, but remember the line for when we re-write out the DB.
existingModules.Add(line);
continue;
}
// this is our file, but continue reading the other lines for when we write out the DB...
dbFile = columns[dbFileIndex];
}
return dbFile;
}
}
public static PythonTypeDatabase CreateDefaultTypeDatabase(PythonInterpreterFactoryWithDatabase factory) {
return new PythonTypeDatabase(factory, BaselineDatabasePath, isDefaultDatabase: true);
}
internal static PythonTypeDatabase CreateDefaultTypeDatabase() {
return CreateDefaultTypeDatabase(new Version(2, 7));
}
internal static PythonTypeDatabase CreateDefaultTypeDatabase(Version languageVersion) {
return new PythonTypeDatabase(InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(languageVersion),
BaselineDatabasePath, isDefaultDatabase: true);
}
public IEnumerable<string> GetModuleNames() {
return _sharedState.GetModuleNames();
}
public IPythonModule GetModule(string name) {
return _sharedState.GetModule(name);
}
public string DatabaseDirectory {
get {
return _sharedState.DatabaseDirectory;
}
}
public IBuiltinPythonModule BuiltinModule {
get {
return _sharedState.BuiltinModule;
}
}
/// <summary>
/// The exit code returned when database generation fails due to an
/// invalid argument.
/// </summary>
public const int InvalidArgumentExitCode = -1;
/// <summary>
/// The exit code returned when database generation fails due to a
/// non-specific error.
/// </summary>
public const int InvalidOperationExitCode = -2;
/// <summary>
/// The exit code returned when a database is already being generated
/// for the interpreter factory.
/// </summary>
public const int AlreadyGeneratingExitCode = -3;
/// <summary>
/// The exit code returned when a database cannot be created for the
/// interpreter factory.
/// </summary>
public const int NotSupportedExitCode = -4;
public static async Task<int> GenerateAsync(PythonTypeDatabaseCreationRequest request) {
var fact = request.Factory;
var evt = request.OnExit;
if (fact == null) {
evt?.Invoke(NotSupportedExitCode);
return NotSupportedExitCode;
}
var outPath = request.OutputPath;
var analyzerPath = PythonToolsInstallPath.GetFile("Microsoft.PythonTools.Analyzer.exe");
Directory.CreateDirectory(CompletionDatabasePath);
var baseDb = BaselineDatabasePath;
if (request.ExtraInputDatabases.Any()) {
baseDb = baseDb + ";" + string.Join(";", request.ExtraInputDatabases);
}
var logPath = Path.Combine(outPath, "AnalysisLog.txt");
var glogPath = Path.Combine(CompletionDatabasePath, "AnalysisLog.txt");
using (var output = ProcessOutput.RunHiddenAndCapture(
analyzerPath,
"/id", fact.Configuration.Id,
"/version", fact.Configuration.Version.ToString(),
"/python", fact.Configuration.InterpreterPath,
"/outdir", outPath,
"/basedb", baseDb,
(request.SkipUnchanged ? null : "/all"), // null will be filtered out; empty strings are quoted
"/log", logPath,
"/glog", glogPath,
"/wait", (request.WaitFor != null ? AnalyzerStatusUpdater.GetIdentifier(request.WaitFor) : "")
)) {
output.PriorityClass = ProcessPriorityClass.BelowNormal;
int exitCode = await output;
if (exitCode > -10 && exitCode < 0) {
try {
File.AppendAllLines(
glogPath,
new[] { string.Format("FAIL_STDLIB: ({0}) {1}", exitCode, output.Arguments) }
.Concat(output.StandardErrorLines)
);
} catch (IOException) {
} catch (ArgumentException) {
} catch (SecurityException) {
} catch (UnauthorizedAccessException) {
}
}
if (evt != null) {
evt(exitCode);
}
return exitCode;
}
}
/// <summary>
/// Invokes Analyzer.exe for the specified factory.
/// </summary>
[Obsolete("Use GenerateAsync instead")]
public static void Generate(PythonTypeDatabaseCreationRequest request) {
var onExit = request.OnExit;
GenerateAsync(request).ContinueWith(t => {
var exc = t.Exception;
if (exc == null) {
return;
}
try {
var message = string.Format(
"ERROR_STDLIB: {0}\\{1}{2}",
request.Factory.Configuration.Id,
Environment.NewLine,
(exc.InnerException ?? exc).ToString()
);
Debug.WriteLine(message);
var glogPath = Path.Combine(CompletionDatabasePath, "AnalysisLog.txt");
File.AppendAllText(glogPath, message);
} catch (IOException) {
} catch (ArgumentException) {
} catch (SecurityException) {
} catch (UnauthorizedAccessException) {
}
if (onExit != null) {
onExit(PythonTypeDatabase.InvalidOperationExitCode);
}
}, TaskContinuationOptions.OnlyOnFaulted);
}
private static bool DatabaseExists(string path) {
string versionFile = Path.Combine(path, "database.ver");
if (File.Exists(versionFile)) {
try {
string allLines = File.ReadAllText(versionFile);
int version;
return Int32.TryParse(allLines, out version) && version == PythonTypeDatabase.CurrentVersion;
} catch (IOException) {
}
}
return false;
}
public static string GlobalLogFilename {
get {
return Path.Combine(CompletionDatabasePath, "AnalysisLog.txt");
}
}
internal static string BaselineDatabasePath {
get {
if (_baselineDatabasePath == null) {
_baselineDatabasePath = Path.GetDirectoryName(
PythonToolsInstallPath.GetFile("CompletionDB\\__builtin__.idb")
);
}
return _baselineDatabasePath;
}
}
public static string CompletionDatabasePath {
get {
if (_completionDatabasePath == null) {
_completionDatabasePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Python Tools",
"CompletionDB",
#if DEBUG
"Debug",
#endif
AssemblyVersionInfo.Version
);
}
return _completionDatabasePath;
}
}
private static string ReferencesDatabasePath {
get {
if (_referencesDatabasePath == null) {
_referencesDatabasePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Python Tools",
"ReferencesDB",
#if DEBUG
"Debug",
#endif
AssemblyVersionInfo.Version
);
}
return _referencesDatabasePath;
}
}
void ITypeDatabaseReader.LookupType(object type, Action<IPythonType> assign) {
_sharedState.LookupType(type, assign);
}
string ITypeDatabaseReader.GetBuiltinTypeName(BuiltinTypeId id) {
return _sharedState.GetBuiltinTypeName(id);
}
void ITypeDatabaseReader.ReadMember(string memberName, Dictionary<string, object> memberValue, Action<string, IMember> assign, IMemberContainer container) {
_sharedState.ReadMember(memberName, memberValue, assign, container);
}
void ITypeDatabaseReader.OnDatabaseCorrupt() {
OnDatabaseCorrupt();
}
public void OnDatabaseCorrupt() {
_factory.NotifyCorruptDatabase();
}
internal CPythonConstant GetConstant(IPythonType type) {
return _sharedState.GetConstant(type);
}
internal static bool TryGetLocation(Dictionary<string, object> table, ref int line, ref int column) {
object value;
if (table.TryGetValue("location", out value)) {
object[] locationInfo = value as object[];
if (locationInfo != null && locationInfo.Length == 2 && locationInfo[0] is int && locationInfo[1] is int) {
line = (int)locationInfo[0];
column = (int)locationInfo[1];
return true;
}
}
return false;
}
public bool BeginModuleLoad(IPythonModule module, int millisecondsTimeout) {
return _sharedState.BeginModuleLoad(module, millisecondsTimeout);
}
public void EndModuleLoad(IPythonModule module) {
_sharedState.EndModuleLoad(module);
}
/// <summary>
/// Returns true if the specified database has a version specified that
/// matches the current build of PythonTypeDatabase. If false, attempts
/// to load the database may fail with an exception.
/// </summary>
public static bool IsDatabaseVersionCurrent(string databasePath) {
if (// Also ensures databasePath won't crash Path.Combine()
Directory.Exists(databasePath) &&
// Ensures that the database is not currently regenerating
!File.Exists(Path.Combine(databasePath, "database.pid"))) {
string versionFile = Path.Combine(databasePath, "database.ver");
if (File.Exists(versionFile)) {
try {
return int.Parse(File.ReadAllText(versionFile)) == CurrentVersion;
} catch (IOException) {
} catch (UnauthorizedAccessException) {
} catch (SecurityException) {
} catch (InvalidOperationException) {
} catch (ArgumentException) {
} catch (OverflowException) {
} catch (FormatException) {
}
}
}
return false;
}
/// <summary>
/// Returns true if the specified database is currently regenerating.
/// </summary>
public static bool IsDatabaseRegenerating(string databasePath) {
return Directory.Exists(databasePath) &&
File.Exists(Path.Combine(databasePath, "database.pid"));
}
/// <summary>
/// Gets the default set of search paths based on the path to the root
/// of the standard library.
/// </summary>
/// <param name="library">Root of the standard library.</param>
/// <returns>A list of search paths for the interpreter.</returns>
/// <remarks>New in 2.2</remarks>
public static List<PythonLibraryPath> GetDefaultDatabaseSearchPaths(string library) {
var result = new List<PythonLibraryPath>();
if (!Directory.Exists(library)) {
return result;
}
result.Add(new PythonLibraryPath(library, true, null));
var sitePackages = Path.Combine(library, "site-packages");
if (!Directory.Exists(sitePackages)) {
return result;
}
result.Add(new PythonLibraryPath(sitePackages, false, null));
result.AddRange(ModulePath.ExpandPathFiles(sitePackages)
.Select(p => new PythonLibraryPath(p, false, null))
);
return result;
}
/// <summary>
/// Gets the set of search paths for the specified factory as
/// efficiently as possible. This may involve executing the
/// interpreter, and may cache the paths for retrieval later.
/// </summary>
public static async Task<IList<PythonLibraryPath>> GetDatabaseSearchPathsAsync(IPythonInterpreterFactory factory) {
var dbPath = (factory as PythonInterpreterFactoryWithDatabase)?.DatabasePath;
for (int retries = 5; retries > 0; --retries) {
if (!string.IsNullOrEmpty(dbPath)) {
var paths = GetCachedDatabaseSearchPaths(dbPath);
if (paths != null) {
return paths;
}
}
try {
var paths = await GetUncachedDatabaseSearchPathsAsync(factory.Configuration.InterpreterPath);
if (!string.IsNullOrEmpty(dbPath)) {
WriteDatabaseSearchPaths(dbPath, paths);
}
return paths;
} catch (InvalidOperationException) {
// Failed to get paths
break;
} catch (IOException) {
// Failed to write paths - sleep and then loop
Thread.Sleep(50);
}
}
var ospy = PathUtils.FindFile(factory.Configuration.PrefixPath, "os.py", firstCheck: new[] { "Lib" });
if (!string.IsNullOrEmpty(ospy)) {
return GetDefaultDatabaseSearchPaths(PathUtils.GetParent(ospy));
}
return Array.Empty<PythonLibraryPath>();
}
/// <summary>
/// Gets the set of search paths by running the interpreter.
/// </summary>
/// <param name="interpreter">Path to the interpreter.</param>
/// <returns>A list of search paths for the interpreter.</returns>
/// <remarks>Added in 2.2</remarks>
public static async Task<List<PythonLibraryPath>> GetUncachedDatabaseSearchPathsAsync(string interpreter) {
List<string> lines;
// sys.path will include the working directory, so we make an empty
// path that we can filter out later
var tempWorkingDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Directory.CreateDirectory(tempWorkingDir);
var srcGetSearchPaths = PythonToolsInstallPath.GetFile("get_search_paths.py", typeof(PythonTypeDatabase).Assembly);
var getSearchPaths = PathUtils.GetAbsoluteFilePath(tempWorkingDir, PathUtils.GetFileOrDirectoryName(srcGetSearchPaths));
File.Copy(srcGetSearchPaths, getSearchPaths);
try {
using (var proc = ProcessOutput.Run(
interpreter,
new[] {
"-S", // don't import site - we do that in code
"-E", // ignore environment
getSearchPaths
},
tempWorkingDir,
null,
false,
null
)) {
int exitCode = -1;
try {
exitCode = await proc;
} catch (OperationCanceledException) {
}
if (exitCode != 0) {
throw new InvalidOperationException(string.Format(
"Cannot obtain list of paths{0}{1}",
Environment.NewLine,
string.Join(Environment.NewLine, proc.StandardErrorLines))
);
}
lines = proc.StandardOutputLines.ToList();
}
} finally {
try {
Directory.Delete(tempWorkingDir, true);
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
}
}
return lines.Select(s => {
if (s.StartsWith(tempWorkingDir, StringComparison.OrdinalIgnoreCase)) {
return null;
}
try {
return PythonLibraryPath.Parse(s);
} catch (FormatException) {
Debug.Fail("Invalid format for search path: " + s);
return null;
}
}).Where(p => p != null).ToList();
}
/// <summary>
/// Gets the set of search paths that were last saved for a database.
/// </summary>
/// <param name="databasePath">Path containing the database.</param>
/// <returns>The cached list of search paths.</returns>
/// <remarks>Added in 2.2</remarks>
public static List<PythonLibraryPath> GetCachedDatabaseSearchPaths(string databasePath) {
var cacheFile = Path.Combine(databasePath, "database.path");
if (!File.Exists(cacheFile)) {
return null;
}
if (!IsDatabaseVersionCurrent(databasePath)) {
// Cache file with no database is only valid for one hour
try {
var time = File.GetLastWriteTimeUtc(cacheFile);
if (time.AddHours(1) < DateTime.UtcNow) {
File.Delete(cacheFile);
return null;
}
} catch (IOException) {
return null;
}
}
try {
var result = new List<PythonLibraryPath>();
using (var file = File.OpenText(cacheFile)) {
string line;
while ((line = file.ReadLine()) != null) {
try {
result.Add(PythonLibraryPath.Parse(line));
} catch (FormatException) {
Debug.Fail("Invalid format: " + line);
}
}
}
return result;
} catch (IOException) {
return null;
}
}
/// <summary>
/// Saves search paths for a database.
/// </summary>
/// <param name="databasePath">The path to the database.</param>
/// <param name="paths">The list of search paths.</param>
/// <remarks>Added in 2.2</remarks>
public static void WriteDatabaseSearchPaths(string databasePath, IEnumerable<PythonLibraryPath> paths) {
Directory.CreateDirectory(databasePath);
using (var file = new StreamWriter(Path.Combine(databasePath, "database.path"))) {
foreach (var path in paths) {
file.WriteLine(path.ToString());
}
}
}
/// <summary>
/// Returns ModulePaths representing the modules that should be analyzed
/// for the given search paths.
/// </summary>
/// <param name="languageVersion">
/// The Python language version to assume. This affects whether
/// namespace packages are supported or not.
/// </param>
/// <param name="searchPaths">A sequence of paths to search.</param>
/// <returns>
/// All the expected modules, grouped based on codependency. When
/// analyzing modules, all those in the same list should be analyzed
/// together.
/// </returns>
/// <remarks>Added in 2.2</remarks>
public static IEnumerable<List<ModulePath>> GetDatabaseExpectedModules(
Version languageVersion,
IEnumerable<PythonLibraryPath> searchPaths
) {
var requireInitPy = ModulePath.PythonVersionRequiresInitPyFiles(languageVersion);
var stdlibGroup = new List<ModulePath>();
var packages = new List<List<ModulePath>> { stdlibGroup };
foreach (var path in searchPaths ?? Enumerable.Empty<PythonLibraryPath>()) {
if (path.IsStandardLibrary) {
stdlibGroup.AddRange(ModulePath.GetModulesInPath(
path.Path,
includeTopLevelFiles: true,
recurse: true,
// Always require __init__.py for stdlib folders
// Otherwise we will probably include libraries multiple
// times, and while Python 3.3+ allows this, it's really
// not a good idea.
requireInitPy: true
));
} else {
packages.Add(ModulePath.GetModulesInPath(
path.Path,
includeTopLevelFiles: true,
recurse: false,
basePackage: path.ModulePrefix
).ToList());
packages.AddRange(ModulePath.GetModulesInPath(
path.Path,
includeTopLevelFiles: false,
recurse: true,
basePackage: path.ModulePrefix,
requireInitPy: requireInitPy
).GroupBy(g => g.LibraryPath).Select(g => g.ToList()));
}
}
return packages;
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Management.FolderBinding", Namespace="urn:iControl")]
public partial class ManagementFolder : iControlInterface {
public ManagementFolder() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
public void create(
string [] folders
) {
this.Invoke("create", new object [] {
folders});
}
public System.IAsyncResult Begincreate(string [] folders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
folders}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_folders
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
public void delete_all_folders(
) {
this.Invoke("delete_all_folders", new object [0]);
}
public System.IAsyncResult Begindelete_all_folders(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_folders", new object[0], callback, asyncState);
}
public void Enddelete_all_folders(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_folder
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
public void delete_folder(
string [] folders
) {
this.Invoke("delete_folder", new object [] {
folders});
}
public System.IAsyncResult Begindelete_folder(string [] folders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_folder", new object[] {
folders}, callback, asyncState);
}
public void Enddelete_folder(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] folders
) {
object [] results = this.Invoke("get_description", new object [] {
folders});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] folders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
folders}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_device_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_device_group(
string [] folders
) {
object [] results = this.Invoke("get_device_group", new object [] {
folders});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_device_group(string [] folders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_device_group", new object[] {
folders}, callback, asyncState);
}
public string [] Endget_device_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_no_reference_check_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_no_reference_check_state(
string [] folders
) {
object [] results = this.Invoke("get_no_reference_check_state", new object [] {
folders});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_no_reference_check_state(string [] folders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_no_reference_check_state", new object[] {
folders}, callback, asyncState);
}
public CommonEnabledState [] Endget_no_reference_check_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_traffic_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_traffic_group(
string [] folders
) {
object [] results = this.Invoke("get_traffic_group", new object [] {
folders});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_traffic_group(string [] folders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_traffic_group", new object[] {
folders}, callback, asyncState);
}
public string [] Endget_traffic_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// is_device_group_inherited
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool [] is_device_group_inherited(
string [] folders
) {
object [] results = this.Invoke("is_device_group_inherited", new object [] {
folders});
return ((bool [])(results[0]));
}
public System.IAsyncResult Beginis_device_group_inherited(string [] folders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("is_device_group_inherited", new object[] {
folders}, callback, asyncState);
}
public bool [] Endis_device_group_inherited(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool [])(results[0]));
}
//-----------------------------------------------------------------------
// is_traffic_group_inherited
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool [] is_traffic_group_inherited(
string [] folders
) {
object [] results = this.Invoke("is_traffic_group_inherited", new object [] {
folders});
return ((bool [])(results[0]));
}
public System.IAsyncResult Beginis_traffic_group_inherited(string [] folders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("is_traffic_group_inherited", new object[] {
folders}, callback, asyncState);
}
public bool [] Endis_traffic_group_inherited(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool [])(results[0]));
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
public void set_description(
string [] folders,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
folders,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] folders,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
folders,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_device_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
public void set_device_group(
string [] folders,
string [] groups
) {
this.Invoke("set_device_group", new object [] {
folders,
groups});
}
public System.IAsyncResult Beginset_device_group(string [] folders,string [] groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_device_group", new object[] {
folders,
groups}, callback, asyncState);
}
public void Endset_device_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_no_reference_check_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
public void set_no_reference_check_state(
string [] folders,
CommonEnabledState [] states
) {
this.Invoke("set_no_reference_check_state", new object [] {
folders,
states});
}
public System.IAsyncResult Beginset_no_reference_check_state(string [] folders,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_no_reference_check_state", new object[] {
folders,
states}, callback, asyncState);
}
public void Endset_no_reference_check_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_traffic_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
public void set_traffic_group(
string [] folders,
string [] groups
) {
this.Invoke("set_traffic_group", new object [] {
folders,
groups});
}
public System.IAsyncResult Beginset_traffic_group(string [] folders,string [] groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_traffic_group", new object[] {
folders,
groups}, callback, asyncState);
}
public void Endset_traffic_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace SupportTickets.React
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// This method is deprecated because the autohosted option is no longer available.
/// </summary>
[ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)]
public string GetDatabaseConnectionString()
{
throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available.");
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
bool contextTokenExpired = false;
try
{
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
}
catch (SecurityTokenExpiredException)
{
contextTokenExpired = true;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired)
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Microsoft.Build.Construction;
using System.Linq;
namespace Microsoft.DotNet.ProjectJsonMigration.Transforms
{
internal class ItemTransformApplicator : ITransformApplicator
{
private readonly ProjectRootElement _projectElementGenerator = ProjectRootElement.Create();
public void Execute<T, U>(
T element,
U destinationElement,
bool mergeExisting) where T : ProjectElement where U : ProjectElementContainer
{
if (typeof(T) != typeof(ProjectItemElement))
{
throw new ArgumentException(String.Format(
LocalizableStrings.ExpectedElementToBeOfTypeNotTypeError,
nameof(ProjectItemElement),
typeof(T)));
}
if (typeof(U) != typeof(ProjectItemGroupElement))
{
throw new ArgumentException(String.Format(
LocalizableStrings.ExpectedElementToBeOfTypeNotTypeError,
nameof(ProjectItemGroupElement),
typeof(U)));
}
if (element == null)
{
return;
}
if (destinationElement == null)
{
throw new ArgumentException(LocalizableStrings.NullDestinationElementError);
}
var item = element as ProjectItemElement;
var destinationItemGroup = destinationElement as ProjectItemGroupElement;
MigrationTrace.Instance.WriteLine(String.Format(
LocalizableStrings.ItemTransformApplicatorHeader,
nameof(ItemTransformApplicator),
item.ItemType,
item.Condition,
item.Include,
item.Exclude,
item.Update));
MigrationTrace.Instance.WriteLine(String.Format(
LocalizableStrings.ItemTransformApplicatorItemGroup,
nameof(ItemTransformApplicator),
destinationItemGroup.Condition));
if (mergeExisting)
{
// Don't duplicate items or includes
item = MergeWithExistingItemsWithSameCondition(item, destinationItemGroup);
if (item == null)
{
MigrationTrace.Instance.WriteLine(String.Format(
LocalizableStrings.ItemTransformAppliatorItemCompletelyMerged,
nameof(ItemTransformApplicator)));
return;
}
// Handle duplicate includes between different conditioned items
item = MergeWithExistingItemsWithNoCondition(item, destinationItemGroup);
if (item == null)
{
MigrationTrace.Instance.WriteLine(String.Format(
LocalizableStrings.ItemTransformAppliatorItemCompletelyMerged,
nameof(ItemTransformApplicator)));
return;
}
item = MergeWithExistingItemsWithACondition(item, destinationItemGroup);
if (item == null)
{
MigrationTrace.Instance.WriteLine(String.Format(
LocalizableStrings.ItemTransformAppliatorItemCompletelyMerged,
nameof(ItemTransformApplicator)));
return;
}
}
AddItemToItemGroup(item, destinationItemGroup);
}
public void Execute<T, U>(
IEnumerable<T> elements,
U destinationElement,
bool mergeExisting) where T : ProjectElement where U : ProjectElementContainer
{
foreach (var element in elements)
{
Execute(element, destinationElement, mergeExisting);
}
}
private void AddItemToItemGroup(ProjectItemElement item, ProjectItemGroupElement itemGroup)
{
var outputItem = itemGroup.ContainingProject.CreateItemElement("___TEMP___");
outputItem.CopyFrom(item);
MigrationTrace.Instance.WriteLine(String.Format(
LocalizableStrings.ItemTransformApplicatorAddItemHeader,
nameof(ItemTransformApplicator),
outputItem.ItemType,
outputItem.Condition,
outputItem.Include,
outputItem.Exclude,
outputItem.Update));
itemGroup.AppendChild(outputItem);
outputItem.AddMetadata(item.Metadata, MigrationTrace.Instance);
}
private ProjectItemElement MergeWithExistingItemsWithACondition(
ProjectItemElement item,
ProjectItemGroupElement destinationItemGroup)
{
// This logic only applies to conditionless items
if (item.ConditionChain().Any() || destinationItemGroup.ConditionChain().Any())
{
return item;
}
var existingItemsWithACondition =
FindExistingItemsWithACondition(item, destinationItemGroup.ContainingProject, destinationItemGroup);
MigrationTrace.Instance.WriteLine(String.Format(
LocalizableStrings.ItemTransformApplicatorMergingItemWithExistingItems,
nameof(ItemTransformApplicator),
existingItemsWithACondition.Count()));
foreach (var existingItem in existingItemsWithACondition)
{
if (!string.IsNullOrEmpty(item.Include))
{
MergeOnIncludesWithExistingItemsWithACondition(item, existingItem, destinationItemGroup);
}
if (!string.IsNullOrEmpty(item.Update))
{
MergeOnUpdatesWithExistingItemsWithACondition(item, existingItem, destinationItemGroup);
}
}
return item;
}
private void MergeOnIncludesWithExistingItemsWithACondition(
ProjectItemElement item,
ProjectItemElement existingItem,
ProjectItemGroupElement destinationItemGroup)
{
// If this item is encompassing items in a condition, remove the encompassed includes from the existing item
var encompassedIncludes = item.GetEncompassedIncludes(existingItem, MigrationTrace.Instance);
if (encompassedIncludes.Any())
{
MigrationTrace.Instance.WriteLine(String.Format(
LocalizableStrings.ItemTransformApplicatorEncompassedIncludes,
nameof(ItemTransformApplicator),
string.Join(", ", encompassedIncludes)));
existingItem.RemoveIncludes(encompassedIncludes);
}
// continue if the existing item is now empty
if (!existingItem.Includes().Any())
{
MigrationTrace.Instance.WriteLine(String.Format(
LocalizableStrings.ItemTransformApplicatorRemovingItem,
nameof(ItemTransformApplicator),
existingItem.ItemType,
existingItem.Condition,
existingItem.Include,
existingItem.Exclude));
existingItem.Parent.RemoveChild(existingItem);
return;
}
// If we haven't continued, the existing item may have includes
// that need to be removed before being redefined, to avoid duplicate includes
// Create or merge with existing remove
var remainingIntersectedIncludes = existingItem.IntersectIncludes(item);
if (remainingIntersectedIncludes.Any())
{
var existingRemoveItem = destinationItemGroup.Items
.Where(i =>
string.IsNullOrEmpty(i.Include)
&& string.IsNullOrEmpty(i.Exclude)
&& !string.IsNullOrEmpty(i.Remove))
.FirstOrDefault();
if (existingRemoveItem != null)
{
var removes = new HashSet<string>(existingRemoveItem.Remove.Split(';'));
foreach (var include in remainingIntersectedIncludes)
{
removes.Add(include);
}
existingRemoveItem.Remove = string.Join(";", removes);
}
else
{
var clearPreviousItem = _projectElementGenerator.CreateItemElement(item.ItemType);
clearPreviousItem.Remove = string.Join(";", remainingIntersectedIncludes);
AddItemToItemGroup(clearPreviousItem, existingItem.Parent as ProjectItemGroupElement);
}
}
}
private void MergeOnUpdatesWithExistingItemsWithACondition(
ProjectItemElement item,
ProjectItemElement existingItem,
ProjectItemGroupElement destinationItemGroup)
{
// If this item is encompassing items in a condition, remove the encompassed updates from the existing item
var encompassedUpdates = item.GetEncompassedUpdates(existingItem, MigrationTrace.Instance);
if (encompassedUpdates.Any())
{
MigrationTrace.Instance.WriteLine(String.Format(
LocalizableStrings.ItemTransformApplicatorEncompassedUpdates,
nameof(ItemTransformApplicator),
string.Join(", ", encompassedUpdates)));
existingItem.RemoveUpdates(encompassedUpdates);
}
// continue if the existing item is now empty
if (!existingItem.Updates().Any())
{
MigrationTrace.Instance.WriteLine(String.Format(
LocalizableStrings.ItemTransformApplicatorRemovingItem,
nameof(ItemTransformApplicator),
existingItem.ItemType,
existingItem.Condition,
existingItem.Update,
existingItem.Exclude));
existingItem.Parent.RemoveChild(existingItem);
return;
}
// If we haven't continued, the existing item may have updates
// that need to be removed before being redefined, to avoid duplicate updates
// Create or merge with existing remove
var remainingIntersectedUpdates = existingItem.IntersectUpdates(item);
if (remainingIntersectedUpdates.Any())
{
var existingRemoveItem = destinationItemGroup.Items
.Where(i =>
string.IsNullOrEmpty(i.Update)
&& string.IsNullOrEmpty(i.Exclude)
&& !string.IsNullOrEmpty(i.Remove))
.FirstOrDefault();
if (existingRemoveItem != null)
{
var removes = new HashSet<string>(existingRemoveItem.Remove.Split(';'));
foreach (var update in remainingIntersectedUpdates)
{
removes.Add(update);
}
existingRemoveItem.Remove = string.Join(";", removes);
}
else
{
var clearPreviousItem = _projectElementGenerator.CreateItemElement(item.ItemType);
clearPreviousItem.Remove = string.Join(";", remainingIntersectedUpdates);
AddItemToItemGroup(clearPreviousItem, existingItem.Parent as ProjectItemGroupElement);
}
}
}
private ProjectItemElement MergeWithExistingItemsWithNoCondition(
ProjectItemElement item,
ProjectItemGroupElement destinationItemGroup)
{
// This logic only applies to items being placed into a condition
if (!item.ConditionChain().Any() && !destinationItemGroup.ConditionChain().Any())
{
return item;
}
var existingItemsWithNoCondition =
FindExistingItemsWithNoCondition(item, destinationItemGroup.ContainingProject, destinationItemGroup);
MigrationTrace.Instance.WriteLine(String.Format(
LocalizableStrings.ItemTransformApplicatorMergingItemWithExistingItems,
nameof(ItemTransformApplicator),
existingItemsWithNoCondition.Count()));
if (!string.IsNullOrEmpty(item.Include))
{
// Handle the item being placed inside of a condition, when it is overlapping with a conditionless item
// If it is not definining new metadata or excludes, the conditioned item can be merged with the
// conditionless item
foreach (var existingItem in existingItemsWithNoCondition)
{
var encompassedIncludes = existingItem.GetEncompassedIncludes(item, MigrationTrace.Instance);
if (encompassedIncludes.Any())
{
MigrationTrace.Instance.WriteLine(String.Format(
LocalizableStrings.ItemTransformApplicatorEncompassedIncludes,
nameof(ItemTransformApplicator),
string.Join(", ", encompassedIncludes)));
item.RemoveIncludes(encompassedIncludes);
if (!item.Includes().Any())
{
MigrationTrace.Instance.WriteLine(String.Format(
LocalizableStrings.ItemTransformApplicatorIgnoringItem,
nameof(ItemTransformApplicator),
existingItem.ItemType,
existingItem.Condition,
existingItem.Include,
existingItem.Exclude));
return null;
}
}
}
}
if (!string.IsNullOrEmpty(item.Update))
{
// Handle the item being placed inside of a condition, when it is overlapping with a conditionless item
// If it is not definining new metadata or excludes, the conditioned item can be merged with the
// conditionless item
foreach (var existingItem in existingItemsWithNoCondition)
{
var encompassedUpdates = existingItem.GetEncompassedUpdates(item, MigrationTrace.Instance);
if (encompassedUpdates.Any())
{
MigrationTrace.Instance.WriteLine(String.Format(
LocalizableStrings.ItemTransformApplicatorEncompassedUpdates,
nameof(ItemTransformApplicator),
string.Join(", ", encompassedUpdates)));
item.RemoveUpdates(encompassedUpdates);
if (!item.Updates().Any())
{
MigrationTrace.Instance.WriteLine(String.Format(
LocalizableStrings.ItemTransformApplicatorIgnoringItem,
nameof(ItemTransformApplicator),
existingItem.ItemType,
existingItem.Condition,
existingItem.Update,
existingItem.Exclude));
return null;
}
}
}
}
// If we haven't returned, and there are existing items with a separate condition, we need to
// overwrite with those items inside the destinationItemGroup by using a Remove
if (existingItemsWithNoCondition.Any())
{
// Merge with the first remove if possible
var existingRemoveItem = destinationItemGroup.Items
.Where(i =>
string.IsNullOrEmpty(i.Include)
&& string.IsNullOrEmpty(i.Update)
&& string.IsNullOrEmpty(i.Exclude)
&& !string.IsNullOrEmpty(i.Remove))
.FirstOrDefault();
var itemsToRemove = string.IsNullOrEmpty(item.Include) ? item.Update : item.Include;
if (existingRemoveItem != null)
{
existingRemoveItem.Remove += ";" + itemsToRemove;
}
else
{
var clearPreviousItem = _projectElementGenerator.CreateItemElement(item.ItemType);
clearPreviousItem.Remove = itemsToRemove;
AddItemToItemGroup(clearPreviousItem, destinationItemGroup);
}
}
return item;
}
private ProjectItemElement MergeWithExistingItemsWithSameCondition(
ProjectItemElement item,
ProjectItemGroupElement destinationItemGroup)
{
var existingItemsWithSameCondition = FindExistingItemsWithSameCondition(
item,
destinationItemGroup.ContainingProject,
destinationItemGroup);
MigrationTrace.Instance.WriteLine(String.Format(
LocalizableStrings.ItemTransformApplicatorMergingItemWithExistingItemsSameChain,
nameof(TransformApplicator),
existingItemsWithSameCondition.Count()));
foreach (var existingItem in existingItemsWithSameCondition)
{
var mergeResult = MergeItems(item, existingItem);
item = mergeResult.InputItem;
// Existing Item is null when it's entire set of includes has been merged with the MergeItem
if (mergeResult.ExistingItem == null)
{
existingItem.Parent.RemoveChild(existingItem);
}
MigrationTrace.Instance.WriteLine(String.Format(
LocalizableStrings.ItemTransformApplicatorAddingMergedItem,
nameof(TransformApplicator),
mergeResult.MergedItem.ItemType,
mergeResult.MergedItem.Condition,
mergeResult.MergedItem.Include,
mergeResult.MergedItem.Exclude));
AddItemToItemGroup(mergeResult.MergedItem, destinationItemGroup);
}
return item;
}
private MergeResult MergeItems(ProjectItemElement item, ProjectItemElement existingItem)
{
if (!string.IsNullOrEmpty(item.Include))
{
return MergeItemsOnIncludes(item, existingItem);
}
if (!string.IsNullOrEmpty(item.Update))
{
return MergeItemsOnUpdates(item, existingItem);
}
throw new InvalidOperationException(LocalizableStrings.CannotMergeItemsWithoutCommonIncludeError);
}
/// <summary>
/// Merges two items on their common sets of includes.
/// The output is 3 items, the 2 input items and the merged items. If the common
/// set of includes spans the entirety of the includes of either of the 2 input
/// items, that item will be returned as null.
///
/// The 3rd output item, the merged item, will have the Union of the excludes and
/// metadata from the 2 input items. If any metadata between the 2 input items is different,
/// this will throw.
///
/// This function will mutate the Include property of the 2 input items, removing the common subset.
/// </summary>
private MergeResult MergeItemsOnIncludes(ProjectItemElement item, ProjectItemElement existingItem)
{
if (!string.Equals(item.ItemType, existingItem.ItemType, StringComparison.Ordinal))
{
throw new InvalidOperationException(LocalizableStrings.CannotMergeItemsOfDifferentTypesError);
}
var commonIncludes = item.IntersectIncludes(existingItem).ToList();
var mergedItem = _projectElementGenerator.AddItem(item.ItemType, string.Join(";", commonIncludes));
mergedItem.UnionExcludes(existingItem.Excludes());
mergedItem.UnionExcludes(item.Excludes());
mergedItem.AddMetadata(MergeMetadata(existingItem.Metadata, item.Metadata), MigrationTrace.Instance);
item.RemoveIncludes(commonIncludes);
existingItem.RemoveIncludes(commonIncludes);
var mergeResult = new MergeResult
{
InputItem = string.IsNullOrEmpty(item.Include) ? null : item,
ExistingItem = string.IsNullOrEmpty(existingItem.Include) ? null : existingItem,
MergedItem = mergedItem
};
return mergeResult;
}
private MergeResult MergeItemsOnUpdates(ProjectItemElement item, ProjectItemElement existingItem)
{
if (!string.Equals(item.ItemType, existingItem.ItemType, StringComparison.Ordinal))
{
throw new InvalidOperationException(LocalizableStrings.CannotMergeItemsOfDifferentTypesError);
}
var commonUpdates = item.IntersectUpdates(existingItem).ToList();
var mergedItem = _projectElementGenerator.AddItem(item.ItemType, "placeholder");
mergedItem.Include = string.Empty;
mergedItem.Update = string.Join(";", commonUpdates);
mergedItem.UnionExcludes(existingItem.Excludes());
mergedItem.UnionExcludes(item.Excludes());
mergedItem.AddMetadata(MergeMetadata(existingItem.Metadata, item.Metadata), MigrationTrace.Instance);
item.RemoveUpdates(commonUpdates);
existingItem.RemoveUpdates(commonUpdates);
var mergeResult = new MergeResult
{
InputItem = string.IsNullOrEmpty(item.Update) ? null : item,
ExistingItem = string.IsNullOrEmpty(existingItem.Update) ? null : existingItem,
MergedItem = mergedItem
};
return mergeResult;
}
private ICollection<ProjectMetadataElement> MergeMetadata(
ICollection<ProjectMetadataElement> existingMetadataElements,
ICollection<ProjectMetadataElement> newMetadataElements)
{
var mergedMetadata = new List<ProjectMetadataElement>(existingMetadataElements.Select(m => (ProjectMetadataElement) m.Clone()));
foreach (var newMetadata in newMetadataElements)
{
var existingMetadata = mergedMetadata.FirstOrDefault(m =>
m.Name.Equals(newMetadata.Name, StringComparison.OrdinalIgnoreCase));
if (existingMetadata == null)
{
mergedMetadata.Add((ProjectMetadataElement) newMetadata.Clone());
}
else
{
MergeMetadata(existingMetadata, (ProjectMetadataElement) newMetadata.Clone());
}
}
return mergedMetadata;
}
public void MergeMetadata(ProjectMetadataElement existingMetadata, ProjectMetadataElement newMetadata)
{
if (existingMetadata.Value != newMetadata.Value)
{
if (existingMetadata.Name == "CopyToOutputDirectory" ||
existingMetadata.Name == "CopyToPublishDirectory")
{
existingMetadata.Value =
existingMetadata.Value == "Never" || newMetadata.Value == "Never" ?
"Never" :
"PreserveNewest";
}
else if (existingMetadata.Name == "Pack")
{
existingMetadata.Value =
existingMetadata.Value == "false" || newMetadata.Value == "false" ?
"false" :
"true";
}
else
{
existingMetadata.Value = string.Join(";", new [] { existingMetadata.Value, newMetadata.Value });
}
}
}
private IEnumerable<ProjectItemElement> FindExistingItemsWithSameCondition(
ProjectItemElement item,
ProjectRootElement project,
ProjectElementContainer destinationContainer)
{
return project.Items
.Where(i => i.Condition == item.Condition)
.Where(i => i.Parent.ConditionChainsAreEquivalent(destinationContainer))
.Where(i => i.ItemType == item.ItemType)
.Where(i => i.IntersectIncludes(item).Any() ||
i.IntersectUpdates(item).Any());
}
private IEnumerable<ProjectItemElement> FindExistingItemsWithNoCondition(
ProjectItemElement item,
ProjectRootElement project,
ProjectElementContainer destinationContainer)
{
return project.Items
.Where(i => !i.ConditionChain().Any())
.Where(i => i.ItemType == item.ItemType)
.Where(i => i.IntersectIncludes(item).Any() ||
i.IntersectUpdates(item).Any());
}
private IEnumerable<ProjectItemElement> FindExistingItemsWithACondition(
ProjectItemElement item,
ProjectRootElement project,
ProjectElementContainer destinationContainer)
{
return project.Items
.Where(i => i.ConditionChain().Any())
.Where(i => i.ItemType == item.ItemType)
.Where(i => i.IntersectIncludes(item).Any() ||
i.IntersectUpdates(item).Any());
}
private class MergeResult
{
public ProjectItemElement InputItem { get; set; }
public ProjectItemElement ExistingItem { get; set; }
public ProjectItemElement MergedItem { get; set; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
namespace GodLesZ.Library.Controls.Html
{
/// <summary>
/// Represents a line of text.
/// </summary>
/// <remarks>
/// To learn more about line-boxes see CSS spec:
/// http://www.w3.org/TR/CSS21/visuren.html
/// </remarks>
internal class CssLineBox
{
#region Fields
private List<CssBoxWord> _words;
private CssBox _ownerBox;
private Dictionary<CssBox, RectangleF> _rects;
private List<CssBox> _relatedBoxes;
#endregion
#region Ctors
/// <summary>
/// Creates a new LineBox
/// </summary>
public CssLineBox(CssBox ownerBox)
{
_rects = new Dictionary<CssBox, RectangleF>();
_relatedBoxes = new List<CssBox>();
_words = new List<CssBoxWord>();
_ownerBox = ownerBox;
_ownerBox.LineBoxes.Add(this);
}
#endregion
#region Props
/// <summary>
/// Gets a list of boxes related with the linebox.
/// To know the words of the box inside this linebox, use the <see cref="WordsOf"/> method.
/// </summary>
public List<CssBox> RelatedBoxes
{
get { return _relatedBoxes; }
}
/// <summary>
/// Gets the words inside the linebox
/// </summary>
public List<CssBoxWord> Words
{
get { return _words; }
}
/// <summary>
/// Gets the owner box
/// </summary>
public CssBox OwnerBox
{
get { return _ownerBox; }
}
/// <summary>
/// Gets a List of rectangles that are to be painted on this linebox
/// </summary>
public Dictionary<CssBox, RectangleF> Rectangles
{
get { return _rects; }
}
#endregion
#region Methods
/// <summary>
/// Gets the maximum bottom of the words
/// </summary>
/// <returns></returns>
public float GetMaxWordBottom()
{
float res = float.MinValue;
foreach (CssBoxWord word in Words)
{
res = Math.Max(res, word.Bottom);
}
return res;
}
#endregion
/// <summary>
/// Lets the linebox add the word an its box to their lists if necessary.
/// </summary>
/// <param name="word"></param>
internal void ReportExistanceOf(CssBoxWord word)
{
if (!Words.Contains(word))
{
Words.Add(word);
}
if (!RelatedBoxes.Contains(word.OwnerBox))
{
RelatedBoxes.Add(word.OwnerBox);
}
}
/// <summary>
/// Return the words of the specified box that live in this linebox
/// </summary>
/// <param name="box"></param>
/// <returns></returns>
internal List<CssBoxWord> WordsOf(CssBox box)
{
List<CssBoxWord> r = new List<CssBoxWord>();
foreach (CssBoxWord word in Words)
if (word.OwnerBox.Equals(box)) r.Add(word);
return r;
}
/// <summary>
/// Updates the specified rectangle of the specified box.
/// </summary>
/// <param name="box"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="r"></param>
/// <param name="b"></param>
internal void UpdateRectangle(CssBox box, float x, float y, float r, float b)
{
float leftspacing = box.ActualBorderLeftWidth + box.ActualPaddingLeft;
float rightspacing = box.ActualBorderRightWidth + box.ActualPaddingRight;
float topspacing = box.ActualBorderTopWidth + box.ActualPaddingTop;
float bottomspacing = box.ActualBorderBottomWidth + box.ActualPaddingTop;
if ((box.FirstHostingLineBox != null && box.FirstHostingLineBox.Equals(this)) || box.IsImage) x -= leftspacing;
if ((box.LastHostingLineBox != null && box.LastHostingLineBox.Equals(this)) || box.IsImage) r += rightspacing;
if (!box.IsImage)
{
y -= topspacing;
b += bottomspacing;
}
if (!Rectangles.ContainsKey(box))
{
Rectangles.Add(box, RectangleF.FromLTRB(x, y, r, b));
}
else
{
RectangleF f = Rectangles[box];
Rectangles[box] = RectangleF.FromLTRB(
Math.Min(f.X, x), Math.Min(f.Y, y),
Math.Max(f.Right, r), Math.Max(f.Bottom, b));
}
if (box.ParentBox != null && box.ParentBox.Display == CssConstants.Inline)
{
UpdateRectangle(box.ParentBox, x, y, r, b);
}
}
/// <summary>
/// Copies the rectangles to their specified box
/// </summary>
internal void AssignRectanglesToBoxes()
{
foreach (CssBox b in Rectangles.Keys)
{
b.Rectangles.Add(this, Rectangles[b]);
}
}
/// <summary>
/// Draws the rectangles for debug purposes
/// </summary>
/// <param name="g"></param>
internal void DrawRectangles(Graphics g)
{
foreach (CssBox b in Rectangles.Keys)
{
if (float.IsInfinity(Rectangles[b].Width))
continue;
g.FillRectangle(new SolidBrush(Color.FromArgb(50, Color.Black)),
Rectangle.Round(Rectangles[b]));
g.DrawRectangle(Pens.Red, Rectangle.Round(Rectangles[b]));
}
}
/// <summary>
/// Gets the baseline Height of the rectangle
/// </summary>
/// <param name="g"></param>
/// <returns></returns>
public float GetBaseLineHeight(CssBox b, Graphics g)
{
Font f = b.ActualFont;
FontFamily ff = f.FontFamily;
FontStyle s = f.Style;
return f.GetHeight(g) * ff.GetCellAscent(s) / ff.GetLineSpacing(s);
}
/// <summary>
/// Sets the baseline of the words of the specified box to certain height
/// </summary>
/// <param name="g">Device info</param>
/// <param name="b">box to check words</param>
/// <param name="baseline">baseline</param>
internal void SetBaseLine(Graphics g,CssBox b, float baseline)
{
//TODO: Aqui me quede, checar poniendo "by the" con un font-size de 3em
List<CssBoxWord> ws = WordsOf(b);
if (!Rectangles.ContainsKey(b)) return;
RectangleF r = Rectangles[b];
//Save top of words related to the top of rectangle
float gap = 0f;
if (ws.Count > 0)
{
gap = ws[0].Top - r.Top;
}
else
{
CssBoxWord firstw = b.FirstWordOccourence(b, this);
if (firstw != null)
{
gap = firstw.Top - r.Top;
}
}
//New top that words will have
//float newtop = baseline - (Height - OwnerBox.FontDescent - 3); //OLD
float newtop = baseline - GetBaseLineHeight(b, g); //OLD
if (b.ParentBox != null &&
b.ParentBox.Rectangles.ContainsKey(this) &&
r.Height < b.ParentBox.Rectangles[this].Height)
{
//Do this only if rectangle is shorter than parent's
float recttop = newtop - gap;
RectangleF newr = new RectangleF(r.X, recttop, r.Width, r.Height);
Rectangles[b] = newr;
b.OffsetRectangle(this, gap);
}
foreach (CssBoxWord w in ws)
if (!w.IsImage)
w.Top = newtop;
}
/// <summary>
/// Returns the words of the linebox
/// </summary>
/// <returns></returns>
public override string ToString()
{
string[] ws = new string[Words.Count];
for (int i = 0; i < ws.Length; i++)
{
ws[i] = Words[i].Text;
}
return string.Join(" ", ws);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
namespace NuGet
{
/// <summary>
/// This repository implementation keeps track of packages that are referenced in a project but
/// it also has a reference to the repository that actually contains the packages. It keeps track
/// of packages in an xml file at the project root (packages.xml).
/// </summary>
public class PackageReferenceRepository : IPackageReferenceRepository, IPackageLookup, IPackageConstraintProvider, ILatestPackageLookup
{
private readonly PackageReferenceFile _packageReferenceFile;
private readonly string _fullPath;
public PackageReferenceRepository(
IFileSystem fileSystem,
string projectName,
ISharedPackageRepository sourceRepository)
{
if (fileSystem == null)
{
throw new ArgumentNullException("fileSystem");
}
if (sourceRepository == null)
{
throw new ArgumentNullException("sourceRepository");
}
_packageReferenceFile = new PackageReferenceFile(
fileSystem, Constants.PackageReferenceFile, projectName);
_fullPath = _packageReferenceFile.FullPath;
SourceRepository = sourceRepository;
}
public PackageReferenceRepository(
string configFilePath,
ISharedPackageRepository sourceRepository)
{
if (String.IsNullOrEmpty(configFilePath))
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "configFilePath");
}
if (sourceRepository == null)
{
throw new ArgumentNullException("sourceRepository");
}
_packageReferenceFile = new PackageReferenceFile(configFilePath);
_fullPath = configFilePath;
SourceRepository = sourceRepository;
}
public string Source
{
get
{
return Constants.PackageReferenceFile;
}
}
public PackageSaveModes PackageSaveMode
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public bool SupportsPrereleasePackages
{
get { return true; }
}
private ISharedPackageRepository SourceRepository
{
get;
set;
}
private string PackageReferenceFileFullPath
{
get
{
return _fullPath;
}
}
public PackageReferenceFile ReferenceFile
{
get
{
return _packageReferenceFile;
}
}
public bool AllowMissingPackages { get; set; }
public IQueryable<IPackage> GetPackages()
{
return GetPackagesCore().AsQueryable();
}
private IEnumerable<IPackage> GetPackagesCore()
{
return _packageReferenceFile.GetPackageReferences()
.Select(GetPackage)
.Where(p => p != null);
}
public void AddPackage(IPackage package)
{
AddPackage(package.Id, package.Version, package.DevelopmentDependency, targetFramework: null);
}
public void RemovePackage(IPackage package)
{
if (_packageReferenceFile.DeleteEntry(package.Id, package.Version))
{
// Remove the repository from the source
SourceRepository.UnregisterRepository(PackageReferenceFileFullPath);
}
}
public IPackage FindPackage(string packageId, SemanticVersion version)
{
if (!_packageReferenceFile.EntryExists(packageId, version))
{
return null;
}
return SourceRepository.FindPackage(packageId, version);
}
public IEnumerable<IPackage> FindPackagesById(string packageId)
{
return GetPackageReferences(packageId).Select(GetPackage)
.Where(p => p != null);
}
public bool Exists(string packageId, SemanticVersion version)
{
return _packageReferenceFile.EntryExists(packageId, version);
}
public void RegisterIfNecessary()
{
if (GetPackages().Any())
{
SourceRepository.RegisterRepository(PackageReferenceFileFullPath);
}
}
public IVersionSpec GetConstraint(string packageId)
{
// Find the reference entry for this package
var reference = GetPackageReference(packageId);
if (reference != null)
{
return reference.VersionConstraint;
}
return null;
}
public bool TryFindLatestPackageById(string id, out SemanticVersion latestVersion)
{
PackageReference reference = GetPackageReferences(id).OrderByDescending(r => r.Version)
.FirstOrDefault();
if (reference == null)
{
latestVersion = null;
return false;
}
else
{
latestVersion = reference.Version;
Debug.Assert(latestVersion != null);
return true;
}
}
public bool TryFindLatestPackageById(string id, bool includePrerelease, out IPackage package)
{
IEnumerable<PackageReference> references = GetPackageReferences(id);
if (!includePrerelease)
{
references = references.Where(r => String.IsNullOrEmpty(r.Version.SpecialVersion));
}
PackageReference reference = references.OrderByDescending(r => r.Version).FirstOrDefault();
if (reference != null)
{
package = GetPackage(reference);
return true;
}
else
{
package = null;
return false;
}
}
public void AddPackage(string packageId, SemanticVersion version, bool developmentDependency, FrameworkName targetFramework)
{
_packageReferenceFile.AddEntry(packageId, version, developmentDependency, targetFramework);
// Notify the source repository every time we add a new package to the repository.
// This doesn't really need to happen on every package add, but this is over agressive
// to combat scenarios where the 2 repositories get out of sync. If this repository is already
// registered in the source then this will be ignored
SourceRepository.RegisterRepository(PackageReferenceFileFullPath);
}
public FrameworkName GetPackageTargetFramework(string packageId)
{
var reference = GetPackageReference(packageId);
if (reference != null)
{
return reference.TargetFramework;
}
return null;
}
private PackageReference GetPackageReference(string packageId)
{
return GetPackageReferences(packageId).FirstOrDefault();
}
/// <summary>
/// Gets all references to a specific package id that are valid.
/// </summary>
/// <param name="packageId"></param>
/// <returns></returns>
private IEnumerable<PackageReference> GetPackageReferences(string packageId)
{
return _packageReferenceFile.GetPackageReferences()
.Where(reference => IsValidReference(reference) &&
reference.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase));
}
private IPackage GetPackage(PackageReference reference)
{
if (IsValidReference(reference))
{
IPackage findPackage = SourceRepository.FindPackage(reference.Id, reference.Version);
if (findPackage == null && AllowMissingPackages)
{
findPackage=new MissingPackage(reference);
}
return findPackage;
}
return null;
}
private static bool IsValidReference(PackageReference reference)
{
return !String.IsNullOrEmpty(reference.Id) && reference.Version != null;
}
public class MissingPackage:IPackage
{
private readonly PackageReference _reference;
public MissingPackage(PackageReference reference)
{
_reference = reference;
}
public string Id { get { return _reference.Id; } }
public SemanticVersion Version { get { return _reference.Version; } }
public string Title { get { return "<missing package>"; } }
public IEnumerable<string> Authors {get { return new String[0]; } }
public IEnumerable<string> Owners { get { return new String[0]; } }
public Uri IconUrl {get { return null; }}
public Uri LicenseUrl { get { return null; } }
public Uri ProjectUrl { get { return null; } }
public bool RequireLicenseAcceptance { get { return false; }}
public bool DevelopmentDependency { get { return _reference.IsDevelopmentDependency; } }
public string Description { get { return "<missing package>"; } }
public string Summary { get { return "<missing package>"; } }
public string ReleaseNotes { get { return "<missing package>"; } }
public string Language { get { return "<missing package>"; } }
public string Tags { get { return "<missing package>"; } }
public string Copyright { get { return "<missing package>"; } }
public IEnumerable<FrameworkAssemblyReference> FrameworkAssemblies { get { return new FrameworkAssemblyReference[0]; } }
public ICollection<PackageReferenceSet> PackageAssemblyReferences { get { return new PackageReferenceSet[0]; } }
public IEnumerable<PackageDependencySet> DependencySets { get { return new PackageDependencySet[0]; } }
public Version MinClientVersion {get {return new Version();} }
public Uri ReportAbuseUrl { get { return null; } }
public int DownloadCount { get { return 0; } }
public bool IsAbsoluteLatestVersion { get { return false; }}
public bool IsLatestVersion { get { return false; } }
public bool Listed { get { return false; } }
public DateTimeOffset? Published { get { return null; } }
public IEnumerable<IPackageAssemblyReference> AssemblyReferences { get { return new IPackageAssemblyReference[0]; } }
public IEnumerable<IPackageFile> GetFiles()
{
return new IPackageFile[0];
}
public IEnumerable<FrameworkName> GetSupportedFrameworks()
{
return new FrameworkName[0];
}
public Stream GetStream()
{
throw new NotSupportedException("Package is missing, can't GetStream");
}
public void ExtractContents(IFileSystem fileSystem, string extractPath)
{
throw new NotSupportedException("Package is missing, can't ExtractContents");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.WebPages;
using Nop.Core;
using Nop.Core.Data;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Directory;
using Nop.Core.Domain.Media;
using Nop.Core.Domain.Messages;
using Nop.Core.Domain.Shipping;
using Nop.Core.Domain.Tax;
using Nop.Core.Domain.Vendors;
using Nop.Services.Catalog;
using Nop.Services.Directory;
using Nop.Services.ExportImport.Help;
using Nop.Services.Localization;
using Nop.Services.Logging;
using Nop.Services.Media;
using Nop.Services.Messages;
using Nop.Services.Security;
using Nop.Services.Seo;
using Nop.Services.Shipping;
using Nop.Services.Shipping.Date;
using Nop.Services.Tax;
using Nop.Services.Vendors;
using OfficeOpenXml;
namespace Nop.Services.ExportImport
{
/// <summary>
/// Import manager
/// </summary>
public partial class ImportManager : IImportManager
{
#region Fields
private readonly IProductService _productService;
private readonly IProductAttributeService _productAttributeService;
private readonly ICategoryService _categoryService;
private readonly IManufacturerService _manufacturerService;
private readonly IPictureService _pictureService;
private readonly IUrlRecordService _urlRecordService;
private readonly IStoreContext _storeContext;
private readonly INewsLetterSubscriptionService _newsLetterSubscriptionService;
private readonly ICountryService _countryService;
private readonly IStateProvinceService _stateProvinceService;
private readonly IEncryptionService _encryptionService;
private readonly IDataProvider _dataProvider;
private readonly MediaSettings _mediaSettings;
private readonly IVendorService _vendorService;
private readonly IProductTemplateService _productTemplateService;
private readonly IShippingService _shippingService;
private readonly IDateRangeService _dateRangeService;
private readonly ITaxCategoryService _taxCategoryService;
private readonly IMeasureService _measureService;
private readonly CatalogSettings _catalogSettings;
private readonly IProductTagService _productTagService;
private readonly IWorkContext _workContext;
private readonly ILocalizationService _localizationService;
private readonly ICustomerActivityService _customerActivityService;
private readonly VendorSettings _vendorSettings;
#endregion
#region Ctor
public ImportManager(IProductService productService,
ICategoryService categoryService,
IManufacturerService manufacturerService,
IPictureService pictureService,
IUrlRecordService urlRecordService,
IStoreContext storeContext,
INewsLetterSubscriptionService newsLetterSubscriptionService,
ICountryService countryService,
IStateProvinceService stateProvinceService,
IEncryptionService encryptionService,
IDataProvider dataProvider,
MediaSettings mediaSettings,
IVendorService vendorService,
IProductTemplateService productTemplateService,
IShippingService shippingService,
IDateRangeService dateRangeService,
ITaxCategoryService taxCategoryService,
IMeasureService measureService,
IProductAttributeService productAttributeService,
CatalogSettings catalogSettings,
IProductTagService productTagService,
IWorkContext workContext,
ILocalizationService localizationService,
ICustomerActivityService customerActivityService,
VendorSettings vendorSettings)
{
this._productService = productService;
this._categoryService = categoryService;
this._manufacturerService = manufacturerService;
this._pictureService = pictureService;
this._urlRecordService = urlRecordService;
this._storeContext = storeContext;
this._newsLetterSubscriptionService = newsLetterSubscriptionService;
this._countryService = countryService;
this._stateProvinceService = stateProvinceService;
this._encryptionService = encryptionService;
this._dataProvider = dataProvider;
this._mediaSettings = mediaSettings;
this._vendorService = vendorService;
this._productTemplateService = productTemplateService;
this._shippingService = shippingService;
this._dateRangeService = dateRangeService;
this._taxCategoryService = taxCategoryService;
this._measureService = measureService;
this._productAttributeService = productAttributeService;
this._catalogSettings = catalogSettings;
this._productTagService = productTagService;
this._workContext = workContext;
this._localizationService = localizationService;
this._customerActivityService = customerActivityService;
this._vendorSettings = vendorSettings;
}
#endregion
#region Utilities
protected virtual int GetColumnIndex(string[] properties, string columnName)
{
if (properties == null)
throw new ArgumentNullException("properties");
if (columnName == null)
throw new ArgumentNullException("columnName");
for (int i = 0; i < properties.Length; i++)
if (properties[i].Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
return i + 1; //excel indexes start from 1
return 0;
}
protected virtual string ConvertColumnToString(object columnValue)
{
if (columnValue == null)
return null;
return Convert.ToString(columnValue);
}
protected virtual string GetMimeTypeFromFilePath(string filePath)
{
var mimeType = MimeMapping.GetMimeMapping(filePath);
//little hack here because MimeMapping does not contain all mappings (e.g. PNG)
if (mimeType == MimeTypes.ApplicationOctetStream)
mimeType = MimeTypes.ImageJpeg;
return mimeType;
}
/// <summary>
/// Creates or loads the image
/// </summary>
/// <param name="picturePath">The path to the image file</param>
/// <param name="name">The name of the object</param>
/// <param name="picId">Image identifier, may be null</param>
/// <returns>The image or null if the image has not changed</returns>
protected virtual Picture LoadPicture(string picturePath, string name, int? picId = null)
{
if (String.IsNullOrEmpty(picturePath) || !File.Exists(picturePath))
return null;
var mimeType = GetMimeTypeFromFilePath(picturePath);
var newPictureBinary = File.ReadAllBytes(picturePath);
var pictureAlreadyExists = false;
if (picId != null)
{
//compare with existing product pictures
var existingPicture = _pictureService.GetPictureById(picId.Value);
var existingBinary = _pictureService.LoadPictureBinary(existingPicture);
//picture binary after validation (like in database)
var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
if (existingBinary.SequenceEqual(validatedPictureBinary) ||
existingBinary.SequenceEqual(newPictureBinary))
{
pictureAlreadyExists = true;
}
}
if (pictureAlreadyExists) return null;
var newPicture = _pictureService.InsertPicture(newPictureBinary, mimeType,
_pictureService.GetPictureSeName(name));
return newPicture;
}
protected virtual void ImportProductImagesUsingServices(IList<ProductPictureMetadata> productPictureMetadata)
{
foreach (var product in productPictureMetadata)
{
foreach (var picturePath in new[] { product.Picture1Path, product.Picture2Path, product.Picture3Path })
{
if (String.IsNullOrEmpty(picturePath))
continue;
var mimeType = GetMimeTypeFromFilePath(picturePath);
var newPictureBinary = File.ReadAllBytes(picturePath);
var pictureAlreadyExists = false;
if (!product.IsNew)
{
//compare with existing product pictures
var existingPictures = _pictureService.GetPicturesByProductId(product.ProductItem.Id);
foreach (var existingPicture in existingPictures)
{
var existingBinary = _pictureService.LoadPictureBinary(existingPicture);
//picture binary after validation (like in database)
var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
if (!existingBinary.SequenceEqual(validatedPictureBinary) &&
!existingBinary.SequenceEqual(newPictureBinary))
continue;
//the same picture content
pictureAlreadyExists = true;
break;
}
}
if (pictureAlreadyExists)
continue;
var newPicture = _pictureService.InsertPicture(newPictureBinary, mimeType, _pictureService.GetPictureSeName(product.ProductItem.Name));
product.ProductItem.ProductPictures.Add(new ProductPicture
{
//EF has some weird issue if we set "Picture = newPicture" instead of "PictureId = newPicture.Id"
//pictures are duplicated
//maybe because entity size is too large
PictureId = newPicture.Id,
DisplayOrder = 1,
});
_productService.UpdateProduct(product.ProductItem);
}
}
}
protected virtual void ImportProductImagesUsingHash(IList<ProductPictureMetadata> productPictureMetadata, IList<Product> allProductsBySku)
{
//performance optimization, load all pictures hashes
//it will only be used if the images are stored in the SQL Server database (not compact)
var takeCount = _dataProvider.SupportedLengthOfBinaryHash() - 1;
var productsImagesIds = _productService.GetProductsImagesIds(allProductsBySku.Select(p => p.Id).ToArray());
var allPicturesHashes = _pictureService.GetPicturesHash(productsImagesIds.SelectMany(p => p.Value).ToArray());
foreach (var product in productPictureMetadata)
{
foreach (var picturePath in new[] { product.Picture1Path, product.Picture2Path, product.Picture3Path })
{
if (String.IsNullOrEmpty(picturePath))
continue;
var mimeType = GetMimeTypeFromFilePath(picturePath);
var newPictureBinary = File.ReadAllBytes(picturePath);
var pictureAlreadyExists = false;
if (!product.IsNew)
{
var newImageHash = _encryptionService.CreateHash(newPictureBinary.Take(takeCount).ToArray());
var newValidatedImageHash = _encryptionService.CreateHash(_pictureService.ValidatePicture(newPictureBinary, mimeType).Take(takeCount).ToArray());
var imagesIds = productsImagesIds.ContainsKey(product.ProductItem.Id)
? productsImagesIds[product.ProductItem.Id]
: new int[0];
pictureAlreadyExists = allPicturesHashes.Where(p => imagesIds.Contains(p.Key)).Select(p => p.Value).Any(p => p == newImageHash || p == newValidatedImageHash);
}
if (pictureAlreadyExists)
continue;
var newPicture = _pictureService.InsertPicture(newPictureBinary, mimeType, _pictureService.GetPictureSeName(product.ProductItem.Name));
product.ProductItem.ProductPictures.Add(new ProductPicture
{
//EF has some weird issue if we set "Picture = newPicture" instead of "PictureId = newPicture.Id"
//pictures are duplicated
//maybe because entity size is too large
PictureId = newPicture.Id,
DisplayOrder = 1,
});
_productService.UpdateProduct(product.ProductItem);
}
}
}
protected virtual IList<PropertyByName<T>> GetPropertiesByExcelCells<T>(ExcelWorksheet worksheet)
{
var properties = new List<PropertyByName<T>>();
var poz = 1;
while (true)
{
try
{
var cell = worksheet.Cells[1, poz];
if (cell == null || cell.Value == null || string.IsNullOrEmpty(cell.Value.ToString()))
break;
poz += 1;
properties.Add(new PropertyByName<T>(cell.Value.ToString()));
}
catch
{
break;
}
}
return properties;
}
#endregion
#region Methods
/// <summary>
/// Import products from XLSX file
/// </summary>
/// <param name="stream">Stream</param>
public virtual void ImportProductsFromXlsx(Stream stream)
{
using (var xlPackage = new ExcelPackage(stream))
{
// get the first worksheet in the workbook
var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault();
if (worksheet == null)
throw new NopException("No worksheet found");
//the columns
var properties = GetPropertiesByExcelCells<Product>(worksheet);
var manager = new PropertyManager<Product>(properties);
var attributProperties = new[]
{
new PropertyByName<ExportProductAttribute>("AttributeId"),
new PropertyByName<ExportProductAttribute>("AttributeName"),
new PropertyByName<ExportProductAttribute>("AttributeTextPrompt"),
new PropertyByName<ExportProductAttribute>("AttributeIsRequired"),
new PropertyByName<ExportProductAttribute>("AttributeControlType")
{
DropDownElements = AttributeControlType.TextBox.ToSelectList(useLocalization: false)
},
new PropertyByName<ExportProductAttribute>("AttributeDisplayOrder"),
new PropertyByName<ExportProductAttribute>("ProductAttributeValueId"),
new PropertyByName<ExportProductAttribute>("ValueName"),
new PropertyByName<ExportProductAttribute>("AttributeValueType")
{
DropDownElements = AttributeValueType.Simple.ToSelectList(useLocalization: false)
},
new PropertyByName<ExportProductAttribute>("AssociatedProductId"),
new PropertyByName<ExportProductAttribute>("ColorSquaresRgb"),
new PropertyByName<ExportProductAttribute>("ImageSquaresPictureId"),
new PropertyByName<ExportProductAttribute>("PriceAdjustment"),
new PropertyByName<ExportProductAttribute>("WeightAdjustment"),
new PropertyByName<ExportProductAttribute>("Cost"),
new PropertyByName<ExportProductAttribute>("CustomerEntersQty"),
new PropertyByName<ExportProductAttribute>("Quantity"),
new PropertyByName<ExportProductAttribute>("IsPreSelected"),
new PropertyByName<ExportProductAttribute>("DisplayOrder"),
new PropertyByName<ExportProductAttribute>("PictureId")
};
var managerProductAttribute = new PropertyManager<ExportProductAttribute>(attributProperties);
var endRow = 2;
var allCategoriesNames = new List<string>();
var allSku = new List<string>();
var tempProperty = manager.GetProperty("Categories");
var categoryCellNum = tempProperty.Return(p => p.PropertyOrderPosition, -1);
tempProperty = manager.GetProperty("SKU");
var skuCellNum = tempProperty.Return(p => p.PropertyOrderPosition, -1);
var allManufacturersNames = new List<string>();
tempProperty = manager.GetProperty("Manufacturers");
var manufacturerCellNum = tempProperty.Return(p => p.PropertyOrderPosition, -1);
manager.SetSelectList("ProductType", ProductType.SimpleProduct.ToSelectList(useLocalization: false));
manager.SetSelectList("GiftCardType", GiftCardType.Virtual.ToSelectList(useLocalization: false));
manager.SetSelectList("DownloadActivationType", DownloadActivationType.Manually.ToSelectList(useLocalization: false));
manager.SetSelectList("ManageInventoryMethod", ManageInventoryMethod.DontManageStock.ToSelectList(useLocalization: false));
manager.SetSelectList("LowStockActivity", LowStockActivity.Nothing.ToSelectList(useLocalization: false));
manager.SetSelectList("BackorderMode", BackorderMode.NoBackorders.ToSelectList(useLocalization: false));
manager.SetSelectList("RecurringCyclePeriod", RecurringProductCyclePeriod.Days.ToSelectList(useLocalization: false));
manager.SetSelectList("RentalPricePeriod", RentalPricePeriod.Days.ToSelectList(useLocalization: false));
manager.SetSelectList("Vendor", _vendorService.GetAllVendors(showHidden: true).Select(v => v as BaseEntity).ToSelectList(p => (p as Vendor).Return(v => v.Name, String.Empty)));
manager.SetSelectList("ProductTemplate", _productTemplateService.GetAllProductTemplates().Select(pt => pt as BaseEntity).ToSelectList(p => (p as ProductTemplate).Return(pt => pt.Name, String.Empty)));
manager.SetSelectList("DeliveryDate", _dateRangeService.GetAllDeliveryDates().Select(dd => dd as BaseEntity).ToSelectList(p => (p as DeliveryDate).Return(dd => dd.Name, String.Empty)));
manager.SetSelectList("ProductAvailabilityRange", _dateRangeService.GetAllProductAvailabilityRanges().Select(range => range as BaseEntity).ToSelectList(p => (p as ProductAvailabilityRange).Return(range => range.Name, String.Empty)));
manager.SetSelectList("TaxCategory", _taxCategoryService.GetAllTaxCategories().Select(tc => tc as BaseEntity).ToSelectList(p => (p as TaxCategory).Return(tc => tc.Name, String.Empty)));
manager.SetSelectList("BasepriceUnit", _measureService.GetAllMeasureWeights().Select(mw => mw as BaseEntity).ToSelectList(p =>(p as MeasureWeight).Return(mw => mw.Name, String.Empty)));
manager.SetSelectList("BasepriceBaseUnit", _measureService.GetAllMeasureWeights().Select(mw => mw as BaseEntity).ToSelectList(p => (p as MeasureWeight).Return(mw => mw.Name, String.Empty)));
var allAttributeIds = new List<int>();
var attributeIdCellNum = managerProductAttribute.GetProperty("AttributeId").PropertyOrderPosition + ExportProductAttribute.ProducAttributeCellOffset;
var countProductsInFile = 0;
//find end of data
while (true)
{
var allColumnsAreEmpty = manager.GetProperties
.Select(property => worksheet.Cells[endRow, property.PropertyOrderPosition])
.All(cell => cell == null || cell.Value == null || String.IsNullOrEmpty(cell.Value.ToString()));
if (allColumnsAreEmpty)
break;
if (new[] { 1, 2 }.Select(cellNum => worksheet.Cells[endRow, cellNum]).All(cell => cell == null || cell.Value == null || String.IsNullOrEmpty(cell.Value.ToString())) && worksheet.Row(endRow).OutlineLevel == 0)
{
var cellValue = worksheet.Cells[endRow, attributeIdCellNum].Value;
try
{
var aid = cellValue.Return(Convert.ToInt32, -1);
var productAttribute = _productAttributeService.GetProductAttributeById(aid);
if (productAttribute != null)
worksheet.Row(endRow).OutlineLevel = 1;
}
catch (FormatException)
{
if (cellValue.Return(cv => cv.ToString(), String.Empty) == "AttributeId")
worksheet.Row(endRow).OutlineLevel = 1;
}
}
if (worksheet.Row(endRow).OutlineLevel != 0)
{
managerProductAttribute.ReadFromXlsx(worksheet, endRow, ExportProductAttribute.ProducAttributeCellOffset);
if (!managerProductAttribute.IsCaption)
{
var aid = worksheet.Cells[endRow, attributeIdCellNum].Value.Return(Convert.ToInt32, -1);
allAttributeIds.Add(aid);
}
endRow++;
continue;
}
if (categoryCellNum > 0)
{
var categoryIds = worksheet.Cells[endRow, categoryCellNum].Value.Return(p => p.ToString(), string.Empty);
if (!categoryIds.IsEmpty())
allCategoriesNames.AddRange(categoryIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()));
}
if (skuCellNum > 0)
{
var sku = worksheet.Cells[endRow, skuCellNum].Value.Return(p => p.ToString(), string.Empty);
if (!sku.IsEmpty())
allSku.Add(sku);
}
if (manufacturerCellNum > 0)
{
var manufacturerIds = worksheet.Cells[endRow, manufacturerCellNum].Value.Return(p => p.ToString(), string.Empty);
if (!manufacturerIds.IsEmpty())
allManufacturersNames.AddRange(manufacturerIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()));
}
//counting the number of products
countProductsInFile += 1;
endRow++;
}
//performance optimization, the check for the existence of the categories in one SQL request
var notExistingCategories = _categoryService.GetNotExistingCategories(allCategoriesNames.ToArray());
if (notExistingCategories.Any())
{
throw new ArgumentException(string.Format("The following category name(s) don't exist - {0}", string.Join(", ", notExistingCategories)));
}
//performance optimization, the check for the existence of the manufacturers in one SQL request
var notExistingManufacturers = _manufacturerService.GetNotExistingManufacturers(allManufacturersNames.ToArray());
if (notExistingManufacturers.Any())
{
throw new ArgumentException(string.Format("The following manufacturer name(s) don't exist - {0}", string.Join(", ", notExistingManufacturers)));
}
//performance optimization, the check for the existence of the product attributes in one SQL request
var notExistingProductAttributes = _productAttributeService.GetNotExistingAttributes(allAttributeIds.ToArray());
if (notExistingProductAttributes.Any())
{
throw new ArgumentException(string.Format("The following product attribute ID(s) don't exist - {0}", string.Join(", ", notExistingProductAttributes)));
}
//performance optimization, load all products by SKU in one SQL request
var allProductsBySku = _productService.GetProductsBySku(allSku.ToArray(), _workContext.CurrentVendor.Return(v=>v.Id, 0));
//validate maximum number of products per vendor
if (_vendorSettings.MaximumProductNumber > 0 &&
_workContext.CurrentVendor != null)
{
var newProductsCount = countProductsInFile - allProductsBySku.Count;
if(_productService.GetNumberOfProductsByVendorId(_workContext.CurrentVendor.Id) + newProductsCount > _vendorSettings.MaximumProductNumber)
throw new ArgumentException(string.Format(_localizationService.GetResource("Admin.Catalog.Products.ExceededMaximumNumber"), _vendorSettings.MaximumProductNumber));
}
//performance optimization, load all categories IDs for products in one SQL request
var allProductsCategoryIds = _categoryService.GetProductCategoryIds(allProductsBySku.Select(p => p.Id).ToArray());
//performance optimization, load all categories in one SQL request
var allCategories = _categoryService.GetAllCategories(showHidden: true);
//performance optimization, load all manufacturers IDs for products in one SQL request
var allProductsManufacturerIds = _manufacturerService.GetProductManufacturerIds(allProductsBySku.Select(p => p.Id).ToArray());
//performance optimization, load all manufacturers in one SQL request
var allManufacturers = _manufacturerService.GetAllManufacturers(showHidden: true);
//product to import images
var productPictureMetadata = new List<ProductPictureMetadata>();
Product lastLoadedProduct = null;
for (var iRow = 2; iRow < endRow; iRow++)
{
//imports product attributes
if (worksheet.Row(iRow).OutlineLevel != 0)
{
if (_catalogSettings.ExportImportProductAttributes)
{
managerProductAttribute.ReadFromXlsx(worksheet, iRow,
ExportProductAttribute.ProducAttributeCellOffset);
if (lastLoadedProduct == null || managerProductAttribute.IsCaption)
continue;
var productAttributeId = managerProductAttribute.GetProperty("AttributeId").IntValue;
var attributeControlTypeId = managerProductAttribute.GetProperty("AttributeControlType").IntValue;
var productAttributeValueId = managerProductAttribute.GetProperty("ProductAttributeValueId").IntValue;
var associatedProductId = managerProductAttribute.GetProperty("AssociatedProductId").IntValue;
var valueName = managerProductAttribute.GetProperty("ValueName").StringValue;
var attributeValueTypeId = managerProductAttribute.GetProperty("AttributeValueType").IntValue;
var colorSquaresRgb = managerProductAttribute.GetProperty("ColorSquaresRgb").StringValue;
var imageSquaresPictureId = managerProductAttribute.GetProperty("ImageSquaresPictureId").IntValue;
var priceAdjustment = managerProductAttribute.GetProperty("PriceAdjustment").DecimalValue;
var weightAdjustment = managerProductAttribute.GetProperty("WeightAdjustment").DecimalValue;
var cost = managerProductAttribute.GetProperty("Cost").DecimalValue;
var customerEntersQty = managerProductAttribute.GetProperty("CustomerEntersQty").BooleanValue;
var quantity = managerProductAttribute.GetProperty("Quantity").IntValue;
var isPreSelected = managerProductAttribute.GetProperty("IsPreSelected").BooleanValue;
var displayOrder = managerProductAttribute.GetProperty("DisplayOrder").IntValue;
var pictureId = managerProductAttribute.GetProperty("PictureId").IntValue;
var textPrompt = managerProductAttribute.GetProperty("AttributeTextPrompt").StringValue;
var isRequired = managerProductAttribute.GetProperty("AttributeIsRequired").BooleanValue;
var attributeDisplayOrder = managerProductAttribute.GetProperty("AttributeDisplayOrder").IntValue;
var productAttributeMapping = lastLoadedProduct.ProductAttributeMappings.FirstOrDefault(pam => pam.ProductAttributeId == productAttributeId);
if (productAttributeMapping == null)
{
//insert mapping
productAttributeMapping = new ProductAttributeMapping
{
ProductId = lastLoadedProduct.Id,
ProductAttributeId = productAttributeId,
TextPrompt = textPrompt,
IsRequired = isRequired,
AttributeControlTypeId = attributeControlTypeId,
DisplayOrder = attributeDisplayOrder
};
_productAttributeService.InsertProductAttributeMapping(productAttributeMapping);
}
else
{
productAttributeMapping.AttributeControlTypeId = attributeControlTypeId;
productAttributeMapping.TextPrompt = textPrompt;
productAttributeMapping.IsRequired = isRequired;
productAttributeMapping.DisplayOrder = attributeDisplayOrder;
_productAttributeService.UpdateProductAttributeMapping(productAttributeMapping);
}
var pav = _productAttributeService.GetProductAttributeValueById(productAttributeValueId);
var attributeControlType = (AttributeControlType) attributeControlTypeId;
if (pav == null)
{
switch (attributeControlType)
{
case AttributeControlType.Datepicker:
case AttributeControlType.FileUpload:
case AttributeControlType.MultilineTextbox:
case AttributeControlType.TextBox:
continue;
}
pav = new ProductAttributeValue
{
ProductAttributeMappingId = productAttributeMapping.Id,
AttributeValueType = (AttributeValueType) attributeValueTypeId,
AssociatedProductId = associatedProductId,
Name = valueName,
PriceAdjustment = priceAdjustment,
WeightAdjustment = weightAdjustment,
Cost = cost,
IsPreSelected = isPreSelected,
DisplayOrder = displayOrder,
ColorSquaresRgb = colorSquaresRgb,
ImageSquaresPictureId = imageSquaresPictureId,
CustomerEntersQty = customerEntersQty,
Quantity = quantity,
PictureId = pictureId
};
_productAttributeService.InsertProductAttributeValue(pav);
}
else
{
pav.AttributeValueTypeId = attributeValueTypeId;
pav.AssociatedProductId = associatedProductId;
pav.Name = valueName;
pav.ColorSquaresRgb = colorSquaresRgb;
pav.ImageSquaresPictureId = imageSquaresPictureId;
pav.PriceAdjustment = priceAdjustment;
pav.WeightAdjustment = weightAdjustment;
pav.Cost = cost;
pav.CustomerEntersQty = customerEntersQty;
pav.Quantity = quantity;
pav.IsPreSelected = isPreSelected;
pav.DisplayOrder = displayOrder;
pav.PictureId = pictureId;
_productAttributeService.UpdateProductAttributeValue(pav);
}
}
continue;
}
manager.ReadFromXlsx(worksheet, iRow);
var product = skuCellNum > 0 ? allProductsBySku.FirstOrDefault(p => p.Sku == manager.GetProperty("SKU").StringValue) : null;
var isNew = product == null;
product = product ?? new Product();
//some of previous values
var previousStockQuantity = product.StockQuantity;
var previousWarehouseId = product.WarehouseId;
if (isNew)
product.CreatedOnUtc = DateTime.UtcNow;
foreach (var property in manager.GetProperties)
{
switch (property.PropertyName)
{
case "ProductType":
product.ProductTypeId = property.IntValue;
break;
case "ParentGroupedProductId":
product.ParentGroupedProductId = property.IntValue;
break;
case "VisibleIndividually":
product.VisibleIndividually = property.BooleanValue;
break;
case "Name":
product.Name = property.StringValue;
break;
case "ShortDescription":
product.ShortDescription = property.StringValue;
break;
case "FullDescription":
product.FullDescription = property.StringValue;
break;
case "Vendor":
//vendor can't change this field
if (_workContext.CurrentVendor == null)
product.VendorId = property.IntValue;
break;
case "ProductTemplate":
product.ProductTemplateId = property.IntValue;
break;
case "ShowOnHomePage":
//vendor can't change this field
if (_workContext.CurrentVendor == null)
product.ShowOnHomePage = property.BooleanValue;
break;
case "MetaKeywords":
product.MetaKeywords = property.StringValue;
break;
case "MetaDescription":
product.MetaDescription = property.StringValue;
break;
case "MetaTitle":
product.MetaTitle = property.StringValue;
break;
case "AllowCustomerReviews":
product.AllowCustomerReviews = property.BooleanValue;
break;
case "Published":
product.Published = property.BooleanValue;
break;
case "SKU":
product.Sku = property.StringValue;
break;
case "ManufacturerPartNumber":
product.ManufacturerPartNumber = property.StringValue;
break;
case "Gtin":
product.Gtin = property.StringValue;
break;
case "IsGiftCard":
product.IsGiftCard = property.BooleanValue;
break;
case "GiftCardType":
product.GiftCardTypeId = property.IntValue;
break;
case "OverriddenGiftCardAmount":
product.OverriddenGiftCardAmount = property.DecimalValue;
break;
case "RequireOtherProducts":
product.RequireOtherProducts = property.BooleanValue;
break;
case "RequiredProductIds":
product.RequiredProductIds = property.StringValue;
break;
case "AutomaticallyAddRequiredProducts":
product.AutomaticallyAddRequiredProducts = property.BooleanValue;
break;
case "IsDownload":
product.IsDownload = property.BooleanValue;
break;
case "DownloadId":
product.DownloadId = property.IntValue;
break;
case "UnlimitedDownloads":
product.UnlimitedDownloads = property.BooleanValue;
break;
case "MaxNumberOfDownloads":
product.MaxNumberOfDownloads = property.IntValue;
break;
case "DownloadActivationType":
product.DownloadActivationTypeId = property.IntValue;
break;
case "HasSampleDownload":
product.HasSampleDownload = property.BooleanValue;
break;
case "SampleDownloadId":
product.SampleDownloadId = property.IntValue;
break;
case "HasUserAgreement":
product.HasUserAgreement = property.BooleanValue;
break;
case "UserAgreementText":
product.UserAgreementText = property.StringValue;
break;
case "IsRecurring":
product.IsRecurring = property.BooleanValue;
break;
case "RecurringCycleLength":
product.RecurringCycleLength = property.IntValue;
break;
case "RecurringCyclePeriod":
product.RecurringCyclePeriodId = property.IntValue;
break;
case "RecurringTotalCycles":
product.RecurringTotalCycles = property.IntValue;
break;
case "IsRental":
product.IsRental = property.BooleanValue;
break;
case "RentalPriceLength":
product.RentalPriceLength = property.IntValue;
break;
case "RentalPricePeriod":
product.RentalPricePeriodId = property.IntValue;
break;
case "IsShipEnabled":
product.IsShipEnabled = property.BooleanValue;
break;
case "IsFreeShipping":
product.IsFreeShipping = property.BooleanValue;
break;
case "ShipSeparately":
product.ShipSeparately = property.BooleanValue;
break;
case "AdditionalShippingCharge":
product.AdditionalShippingCharge = property.DecimalValue;
break;
case "DeliveryDate":
product.DeliveryDateId = property.IntValue;
break;
case "IsTaxExempt":
product.IsTaxExempt = property.BooleanValue;
break;
case "TaxCategory":
product.TaxCategoryId = property.IntValue;
break;
case "IsTelecommunicationsOrBroadcastingOrElectronicServices":
product.IsTelecommunicationsOrBroadcastingOrElectronicServices = property.BooleanValue;
break;
case "ManageInventoryMethod":
product.ManageInventoryMethodId = property.IntValue;
break;
case "ProductAvailabilityRange":
product.ProductAvailabilityRangeId = property.IntValue;
break;
case "UseMultipleWarehouses":
product.UseMultipleWarehouses = property.BooleanValue;
break;
case "WarehouseId":
product.WarehouseId = property.IntValue;
break;
case "StockQuantity":
product.StockQuantity = property.IntValue;
break;
case "DisplayStockAvailability":
product.DisplayStockAvailability = property.BooleanValue;
break;
case "DisplayStockQuantity":
product.DisplayStockQuantity = property.BooleanValue;
break;
case "MinStockQuantity":
product.MinStockQuantity = property.IntValue;
break;
case "LowStockActivity":
product.LowStockActivityId = property.IntValue;
break;
case "NotifyAdminForQuantityBelow":
product.NotifyAdminForQuantityBelow = property.IntValue;
break;
case "BackorderMode":
product.BackorderModeId = property.IntValue;
break;
case "AllowBackInStockSubscriptions":
product.AllowBackInStockSubscriptions = property.BooleanValue;
break;
case "OrderMinimumQuantity":
product.OrderMinimumQuantity = property.IntValue;
break;
case "OrderMaximumQuantity":
product.OrderMaximumQuantity = property.IntValue;
break;
case "AllowedQuantities":
product.AllowedQuantities = property.StringValue;
break;
case "AllowAddingOnlyExistingAttributeCombinations":
product.AllowAddingOnlyExistingAttributeCombinations = property.BooleanValue;
break;
case "NotReturnable":
product.NotReturnable = property.BooleanValue;
break;
case "DisableBuyButton":
product.DisableBuyButton = property.BooleanValue;
break;
case "DisableWishlistButton":
product.DisableWishlistButton = property.BooleanValue;
break;
case "AvailableForPreOrder":
product.AvailableForPreOrder = property.BooleanValue;
break;
case "PreOrderAvailabilityStartDateTimeUtc":
product.PreOrderAvailabilityStartDateTimeUtc = property.DateTimeNullable;
break;
case "CallForPrice":
product.CallForPrice = property.BooleanValue;
break;
case "Price":
product.Price = property.DecimalValue;
break;
case "OldPrice":
product.OldPrice = property.DecimalValue;
break;
case "ProductCost":
product.ProductCost = property.DecimalValue;
break;
case "CustomerEntersPrice":
product.CustomerEntersPrice = property.BooleanValue;
break;
case "MinimumCustomerEnteredPrice":
product.MinimumCustomerEnteredPrice = property.DecimalValue;
break;
case "MaximumCustomerEnteredPrice":
product.MaximumCustomerEnteredPrice = property.DecimalValue;
break;
case "BasepriceEnabled":
product.BasepriceEnabled = property.BooleanValue;
break;
case "BasepriceAmount":
product.BasepriceAmount = property.DecimalValue;
break;
case "BasepriceUnit":
product.BasepriceUnitId = property.IntValue;
break;
case "BasepriceBaseAmount":
product.BasepriceBaseAmount = property.DecimalValue;
break;
case "BasepriceBaseUnit":
product.BasepriceBaseUnitId = property.IntValue;
break;
case "MarkAsNew":
product.MarkAsNew = property.BooleanValue;
break;
case "MarkAsNewStartDateTimeUtc":
product.MarkAsNewStartDateTimeUtc = property.DateTimeNullable;
break;
case "MarkAsNewEndDateTimeUtc":
product.MarkAsNewEndDateTimeUtc = property.DateTimeNullable;
break;
case "Weight":
product.Weight = property.DecimalValue;
break;
case "Length":
product.Length = property.DecimalValue;
break;
case "Width":
product.Width = property.DecimalValue;
break;
case "Height":
product.Height = property.DecimalValue;
break;
}
}
//set some default default values if not specified
if (isNew && properties.All(p => p.PropertyName != "ProductType"))
product.ProductType = ProductType.SimpleProduct;
if (isNew && properties.All(p => p.PropertyName != "VisibleIndividually"))
product.VisibleIndividually = true;
if (isNew && properties.All(p => p.PropertyName != "Published"))
product.Published = true;
//sets the current vendor for the new product
if (isNew && _workContext.CurrentVendor != null)
product.VendorId = _workContext.CurrentVendor.Id;
product.UpdatedOnUtc = DateTime.UtcNow;
if (isNew)
{
_productService.InsertProduct(product);
}
else
{
_productService.UpdateProduct(product);
}
//quantity change history
if (isNew || previousWarehouseId == product.WarehouseId)
{
_productService.AddStockQuantityHistoryEntry(product, product.StockQuantity - previousStockQuantity, product.StockQuantity,
product.WarehouseId, _localizationService.GetResource("Admin.StockQuantityHistory.Messages.ImportProduct.Edit"));
}
//warehouse is changed
else
{
//compose a message
var oldWarehouseMessage = string.Empty;
if (previousWarehouseId > 0)
{
var oldWarehouse = _shippingService.GetWarehouseById(previousWarehouseId);
if (oldWarehouse != null)
oldWarehouseMessage = string.Format(_localizationService.GetResource("Admin.StockQuantityHistory.Messages.EditWarehouse.Old"), oldWarehouse.Name);
}
var newWarehouseMessage = string.Empty;
if (product.WarehouseId > 0)
{
var newWarehouse = _shippingService.GetWarehouseById(product.WarehouseId);
if (newWarehouse != null)
newWarehouseMessage = string.Format(_localizationService.GetResource("Admin.StockQuantityHistory.Messages.EditWarehouse.New"), newWarehouse.Name);
}
var message = string.Format(_localizationService.GetResource("Admin.StockQuantityHistory.Messages.ImportProduct.EditWarehouse"), oldWarehouseMessage, newWarehouseMessage);
//record history
_productService.AddStockQuantityHistoryEntry(product, -previousStockQuantity, 0, previousWarehouseId, message);
_productService.AddStockQuantityHistoryEntry(product, product.StockQuantity, product.StockQuantity, product.WarehouseId, message);
}
tempProperty = manager.GetProperty("SeName");
if (tempProperty != null)
{
var seName = tempProperty.StringValue;
//search engine name
_urlRecordService.SaveSlug(product, product.ValidateSeName(seName, product.Name, true), 0);
}
tempProperty = manager.GetProperty("Categories");
if (tempProperty != null)
{
var categoryNames = tempProperty.StringValue;
//category mappings
var categories = isNew || !allProductsCategoryIds.ContainsKey(product.Id) ? new int[0] : allProductsCategoryIds[product.Id];
var importedCategories = categoryNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => allCategories.First(c => c.Name == x.Trim()).Id).ToList();
foreach (var categoryId in importedCategories)
{
if (categories.Any(c => c == categoryId))
continue;
var productCategory = new ProductCategory
{
ProductId = product.Id,
CategoryId = categoryId,
IsFeaturedProduct = false,
DisplayOrder = 1
};
_categoryService.InsertProductCategory(productCategory);
}
//delete product categories
var deletedProductCategories = categories.Where(categoryId => !importedCategories.Contains(categoryId))
.Select(categoryId => product.ProductCategories.First(pc => pc.CategoryId == categoryId));
foreach (var deletedProductCategory in deletedProductCategories)
{
_categoryService.DeleteProductCategory(deletedProductCategory);
}
}
tempProperty = manager.GetProperty("Manufacturers");
if (tempProperty != null)
{
var manufacturerNames = tempProperty.StringValue;
//manufacturer mappings
var manufacturers = isNew || !allProductsManufacturerIds.ContainsKey(product.Id) ? new int[0] : allProductsManufacturerIds[product.Id];
var importedManufacturers = manufacturerNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => allManufacturers.First(m => m.Name == x.Trim()).Id).ToList();
foreach (var manufacturerId in importedManufacturers)
{
if (manufacturers.Any(c => c == manufacturerId))
continue;
var productManufacturer = new ProductManufacturer
{
ProductId = product.Id,
ManufacturerId = manufacturerId,
IsFeaturedProduct = false,
DisplayOrder = 1
};
_manufacturerService.InsertProductManufacturer(productManufacturer);
}
//delete product manufacturers
var deletedProductsManufacturers = manufacturers.Where(manufacturerId => !importedManufacturers.Contains(manufacturerId))
.Select(manufacturerId => product.ProductManufacturers.First(pc => pc.ManufacturerId == manufacturerId));
foreach (var deletedProductManufacturer in deletedProductsManufacturers)
{
_manufacturerService.DeleteProductManufacturer(deletedProductManufacturer);
}
}
tempProperty = manager.GetProperty("ProductTags");
if (tempProperty != null)
{
var productTags = tempProperty.StringValue.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray();
//product tag mappings
_productTagService.UpdateProductTags(product, productTags);
}
var picture1 = manager.GetProperty("Picture1").Return(p => p.StringValue, String.Empty);
var picture2 = manager.GetProperty("Picture2").Return(p => p.StringValue, String.Empty);
var picture3 = manager.GetProperty("Picture3").Return(p => p.StringValue, String.Empty);
productPictureMetadata.Add(new ProductPictureMetadata
{
ProductItem = product,
Picture1Path = picture1,
Picture2Path = picture2,
Picture3Path = picture3,
IsNew = isNew
});
lastLoadedProduct = product;
//update "HasTierPrices" and "HasDiscountsApplied" properties
//_productService.UpdateHasTierPricesProperty(product);
//_productService.UpdateHasDiscountsApplied(product);
}
if (_mediaSettings.ImportProductImagesUsingHash && _pictureService.StoreInDb && _dataProvider.SupportedLengthOfBinaryHash() > 0)
ImportProductImagesUsingHash(productPictureMetadata, allProductsBySku);
else
ImportProductImagesUsingServices(productPictureMetadata);
//activity log
_customerActivityService.InsertActivity("ImportProducts", _localizationService.GetResource("ActivityLog.ImportProducts"), countProductsInFile);
}
}
/// <summary>
/// Import newsletter subscribers from TXT file
/// </summary>
/// <param name="stream">Stream</param>
/// <returns>Number of imported subscribers</returns>
public virtual int ImportNewsletterSubscribersFromTxt(Stream stream)
{
int count = 0;
using (var reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (String.IsNullOrWhiteSpace(line))
continue;
string[] tmp = line.Split(',');
string email;
bool isActive = true;
int storeId = _storeContext.CurrentStore.Id;
//parse
if (tmp.Length == 1)
{
//"email" only
email = tmp[0].Trim();
}
else if (tmp.Length == 2)
{
//"email" and "active" fields specified
email = tmp[0].Trim();
isActive = Boolean.Parse(tmp[1].Trim());
}
else if (tmp.Length == 3)
{
//"email" and "active" and "storeId" fields specified
email = tmp[0].Trim();
isActive = Boolean.Parse(tmp[1].Trim());
storeId = Int32.Parse(tmp[2].Trim());
}
else
throw new NopException("Wrong file format");
//import
var subscription = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(email, storeId);
if (subscription != null)
{
subscription.Email = email;
subscription.Active = isActive;
_newsLetterSubscriptionService.UpdateNewsLetterSubscription(subscription);
}
else
{
subscription = new NewsLetterSubscription
{
Active = isActive,
CreatedOnUtc = DateTime.UtcNow,
Email = email,
StoreId = storeId,
NewsLetterSubscriptionGuid = Guid.NewGuid()
};
_newsLetterSubscriptionService.InsertNewsLetterSubscription(subscription);
}
count++;
}
}
return count;
}
/// <summary>
/// Import states from TXT file
/// </summary>
/// <param name="stream">Stream</param>
/// <returns>Number of imported states</returns>
public virtual int ImportStatesFromTxt(Stream stream)
{
int count = 0;
using (var reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (String.IsNullOrWhiteSpace(line))
continue;
string[] tmp = line.Split(',');
if (tmp.Length != 5)
throw new NopException("Wrong file format");
//parse
var countryTwoLetterIsoCode = tmp[0].Trim();
var name = tmp[1].Trim();
var abbreviation = tmp[2].Trim();
bool published = Boolean.Parse(tmp[3].Trim());
int displayOrder = Int32.Parse(tmp[4].Trim());
var country = _countryService.GetCountryByTwoLetterIsoCode(countryTwoLetterIsoCode);
if (country == null)
{
//country cannot be loaded. skip
continue;
}
//import
var states = _stateProvinceService.GetStateProvincesByCountryId(country.Id, showHidden: true);
var state = states.FirstOrDefault(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));
if (state != null)
{
state.Abbreviation = abbreviation;
state.Published = published;
state.DisplayOrder = displayOrder;
_stateProvinceService.UpdateStateProvince(state);
}
else
{
state = new StateProvince
{
CountryId = country.Id,
Name = name,
Abbreviation = abbreviation,
Published = published,
DisplayOrder = displayOrder,
};
_stateProvinceService.InsertStateProvince(state);
}
count++;
}
}
//activity log
_customerActivityService.InsertActivity("ImportStates", _localizationService.GetResource("ActivityLog.ImportStates"), count);
return count;
}
/// <summary>
/// Import manufacturers from XLSX file
/// </summary>
/// <param name="stream">Stream</param>
public virtual void ImportManufacturersFromXlsx(Stream stream)
{
using (var xlPackage = new ExcelPackage(stream))
{
// get the first worksheet in the workbook
var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault();
if (worksheet == null)
throw new NopException("No worksheet found");
//the columns
var properties = GetPropertiesByExcelCells<Manufacturer>(worksheet);
var manager = new PropertyManager<Manufacturer>(properties);
var iRow = 2;
var setSeName = properties.Any(p => p.PropertyName == "SeName");
while (true)
{
var allColumnsAreEmpty = manager.GetProperties
.Select(property => worksheet.Cells[iRow, property.PropertyOrderPosition])
.All(cell => cell == null || cell.Value == null || String.IsNullOrEmpty(cell.Value.ToString()));
if (allColumnsAreEmpty)
break;
manager.ReadFromXlsx(worksheet, iRow);
var manufacturer = _manufacturerService.GetManufacturerById(manager.GetProperty("Id").IntValue);
var isNew = manufacturer == null;
manufacturer = manufacturer ?? new Manufacturer();
if (isNew)
{
manufacturer.CreatedOnUtc = DateTime.UtcNow;
//default values
manufacturer.PageSize = _catalogSettings.DefaultManufacturerPageSize;
manufacturer.PageSizeOptions = _catalogSettings.DefaultManufacturerPageSizeOptions;
manufacturer.Published = true;
manufacturer.AllowCustomersToSelectPageSize = true;
}
var seName = string.Empty;
foreach (var property in manager.GetProperties)
{
switch (property.PropertyName)
{
case "Name":
manufacturer.Name = property.StringValue;
break;
case "Description":
manufacturer.Description = property.StringValue;
break;
case "ManufacturerTemplateId":
manufacturer.ManufacturerTemplateId = property.IntValue;
break;
case "MetaKeywords":
manufacturer.MetaKeywords = property.StringValue;
break;
case "MetaDescription":
manufacturer.MetaDescription = property.StringValue;
break;
case "MetaTitle":
manufacturer.MetaTitle = property.StringValue;
break;
case "Picture":
var picture = LoadPicture(manager.GetProperty("Picture").StringValue, manufacturer.Name,
isNew ? null : (int?) manufacturer.PictureId);
if (picture != null)
manufacturer.PictureId = picture.Id;
break;
case "PageSize":
manufacturer.PageSize = property.IntValue;
break;
case "AllowCustomersToSelectPageSize":
manufacturer.AllowCustomersToSelectPageSize = property.BooleanValue;
break;
case "PageSizeOptions":
manufacturer.PageSizeOptions = property.StringValue;
break;
case "PriceRanges":
manufacturer.PriceRanges = property.StringValue;
break;
case "Published":
manufacturer.Published = property.BooleanValue;
break;
case "DisplayOrder":
manufacturer.DisplayOrder = property.IntValue;
break;
case "SeName":
seName = property.StringValue;
break;
}
}
manufacturer.UpdatedOnUtc = DateTime.UtcNow;
if (isNew)
_manufacturerService.InsertManufacturer(manufacturer);
else
_manufacturerService.UpdateManufacturer(manufacturer);
//search engine name
if (setSeName)
_urlRecordService.SaveSlug(manufacturer, manufacturer.ValidateSeName(seName, manufacturer.Name, true), 0);
iRow++;
}
//activity log
_customerActivityService.InsertActivity("ImportManufacturers", _localizationService.GetResource("ActivityLog.ImportManufacturers"), iRow - 2);
}
}
/// <summary>
/// Import categories from XLSX file
/// </summary>
/// <param name="stream">Stream</param>
public virtual void ImportCategoriesFromXlsx(Stream stream)
{
using (var xlPackage = new ExcelPackage(stream))
{
// get the first worksheet in the workbook
var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault();
if (worksheet == null)
throw new NopException("No worksheet found");
//the columns
var properties = GetPropertiesByExcelCells<Category>(worksheet);
var manager = new PropertyManager<Category>(properties);
var iRow = 2;
var setSeName = properties.Any(p => p.PropertyName == "SeName");
while (true)
{
var allColumnsAreEmpty = manager.GetProperties
.Select(property => worksheet.Cells[iRow, property.PropertyOrderPosition])
.All(cell => cell == null || cell.Value == null || String.IsNullOrEmpty(cell.Value.ToString()));
if (allColumnsAreEmpty)
break;
manager.ReadFromXlsx(worksheet, iRow);
var category = _categoryService.GetCategoryById(manager.GetProperty("Id").IntValue);
var isNew = category == null;
category = category ?? new Category();
if (isNew)
{
category.CreatedOnUtc = DateTime.UtcNow;
//default values
category.PageSize = _catalogSettings.DefaultCategoryPageSize;
category.PageSizeOptions = _catalogSettings.DefaultCategoryPageSizeOptions;
category.Published = true;
category.IncludeInTopMenu = true;
category.AllowCustomersToSelectPageSize = true;
}
var seName = string.Empty;
foreach (var property in manager.GetProperties)
{
switch (property.PropertyName)
{
case "Name":
category.Name = property.StringValue;
break;
case "Description":
category.Description = property.StringValue;
break;
case "CategoryTemplateId":
category.CategoryTemplateId = property.IntValue;
break;
case "MetaKeywords":
category.MetaKeywords = property.StringValue;
break;
case "MetaDescription":
category.MetaDescription = property.StringValue;
break;
case "MetaTitle":
category.MetaTitle = property.StringValue;
break;
case "ParentCategoryId":
category.ParentCategoryId = property.IntValue;
break;
case "Picture":
var picture = LoadPicture(manager.GetProperty("Picture").StringValue, category.Name, isNew ? null : (int?)category.PictureId);
if (picture != null)
category.PictureId = picture.Id;
break;
case "PageSize":
category.PageSize = property.IntValue;
break;
case "AllowCustomersToSelectPageSize":
category.AllowCustomersToSelectPageSize = property.BooleanValue;
break;
case "PageSizeOptions":
category.PageSizeOptions = property.StringValue;
break;
case "PriceRanges":
category.PriceRanges = property.StringValue;
break;
case "ShowOnHomePage":
category.ShowOnHomePage = property.BooleanValue;
break;
case "IncludeInTopMenu":
category.IncludeInTopMenu = property.BooleanValue;
break;
case "Published":
category.Published = property.BooleanValue;
break;
case "DisplayOrder":
category.DisplayOrder = property.IntValue;
break;
case "SeName":
seName = property.StringValue;
break;
}
}
category.UpdatedOnUtc = DateTime.UtcNow;
if (isNew)
_categoryService.InsertCategory(category);
else
_categoryService.UpdateCategory(category);
//search engine name
if (setSeName)
_urlRecordService.SaveSlug(category, category.ValidateSeName(seName, category.Name, true), 0);
iRow++;
}
//activity log
_customerActivityService.InsertActivity("ImportCategories", _localizationService.GetResource("ActivityLog.ImportCategories"), iRow - 2);
}
}
#endregion
#region Nested classes
protected class ProductPictureMetadata
{
public Product ProductItem { get; set; }
public string Picture1Path { get; set; }
public string Picture2Path { get; set; }
public string Picture3Path { get; set; }
public bool IsNew { get; set; }
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Tasks.Hosting;
using Microsoft.Build.Utilities;
using Microsoft.CodeAnalysis.CommandLine;
using Microsoft.CodeAnalysis.CSharp;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// This class defines the "Csc" XMake task, which enables building assemblies from C#
/// source files by invoking the C# compiler. This is the new Roslyn XMake task,
/// meaning that the code is compiled by using the Roslyn compiler server, rather
/// than csc.exe. The two should be functionally identical, but the compiler server
/// should be significantly faster with larger projects and have a smaller memory
/// footprint.
/// </summary>
public class Csc : ManagedCompiler
{
#region Properties
// Please keep these alphabetized. These are the parameters specific to Csc. The
// ones shared between Vbc and Csc are defined in ManagedCompiler.cs, which is
// the base class.
public bool AllowUnsafeBlocks
{
set { _store[nameof(AllowUnsafeBlocks)] = value; }
get { return _store.GetOrDefault(nameof(AllowUnsafeBlocks), false); }
}
public string ApplicationConfiguration
{
set { _store[nameof(ApplicationConfiguration)] = value; }
get { return (string)_store[nameof(ApplicationConfiguration)]; }
}
public string BaseAddress
{
set { _store[nameof(BaseAddress)] = value; }
get { return (string)_store[nameof(BaseAddress)]; }
}
public bool CheckForOverflowUnderflow
{
set { _store[nameof(CheckForOverflowUnderflow)] = value; }
get { return _store.GetOrDefault(nameof(CheckForOverflowUnderflow), false); }
}
public string DocumentationFile
{
set { _store[nameof(DocumentationFile)] = value; }
get { return (string)_store[nameof(DocumentationFile)]; }
}
public string DisabledWarnings
{
set { _store[nameof(DisabledWarnings)] = value; }
get { return (string)_store[nameof(DisabledWarnings)]; }
}
public bool ErrorEndLocation
{
set { _store[nameof(ErrorEndLocation)] = value; }
get { return _store.GetOrDefault(nameof(ErrorEndLocation), false); }
}
public string ErrorReport
{
set { _store[nameof(ErrorReport)] = value; }
get { return (string)_store[nameof(ErrorReport)]; }
}
public bool GenerateFullPaths
{
set { _store[nameof(GenerateFullPaths)] = value; }
get { return _store.GetOrDefault(nameof(GenerateFullPaths), false); }
}
public string LangVersion
{
set { _store[nameof(LangVersion)] = value; }
get { return (string)_store[nameof(LangVersion)]; }
}
public string ModuleAssemblyName
{
set { _store[nameof(ModuleAssemblyName)] = value; }
get { return (string)_store[nameof(ModuleAssemblyName)]; }
}
public bool NoStandardLib
{
set { _store[nameof(NoStandardLib)] = value; }
get { return _store.GetOrDefault(nameof(NoStandardLib), false); }
}
public string PdbFile
{
set { _store[nameof(PdbFile)] = value; }
get { return (string)_store[nameof(PdbFile)]; }
}
/// <summary>
/// Name of the language passed to "/preferreduilang" compiler option.
/// </summary>
/// <remarks>
/// If set to null, "/preferreduilang" option is omitted, and csc.exe uses its default setting.
/// Otherwise, the value is passed to "/preferreduilang" as is.
/// </remarks>
public string PreferredUILang
{
set { _store[nameof(PreferredUILang)] = value; }
get { return (string)_store[nameof(PreferredUILang)]; }
}
public string VsSessionGuid
{
set { _store[nameof(VsSessionGuid)] = value; }
get { return (string)_store[nameof(VsSessionGuid)]; }
}
public bool UseHostCompilerIfAvailable
{
set { _store[nameof(UseHostCompilerIfAvailable)] = value; }
get { return _store.GetOrDefault(nameof(UseHostCompilerIfAvailable), false); }
}
public int WarningLevel
{
set { _store[nameof(WarningLevel)] = value; }
get { return _store.GetOrDefault(nameof(WarningLevel), 4); }
}
public string WarningsAsErrors
{
set { _store[nameof(WarningsAsErrors)] = value; }
get { return (string)_store[nameof(WarningsAsErrors)]; }
}
public string WarningsNotAsErrors
{
set { _store[nameof(WarningsNotAsErrors)] = value; }
get { return (string)_store[nameof(WarningsNotAsErrors)]; }
}
#endregion
#region Tool Members
internal override RequestLanguage Language => RequestLanguage.CSharpCompile;
private static readonly string[] s_separators = { "\r\n" };
internal override void LogMessages(string output, MessageImportance messageImportance)
{
var lines = output.Split(s_separators, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
string trimmedMessage = line.Trim();
if (trimmedMessage != "")
{
Log.LogMessageFromText(trimmedMessage, messageImportance);
}
}
}
/// <summary>
/// Return the name of the tool to execute.
/// </summary>
override protected string ToolName
{
get
{
return "csc.exe";
}
}
/// <summary>
/// Return the path to the tool to execute.
/// </summary>
protected override string GenerateFullPathToTool()
{
string pathToTool = ToolLocationHelper.GetPathToBuildToolsFile(ToolName, ToolLocationHelper.CurrentToolsVersion);
if (null == pathToTool)
{
pathToTool = ToolLocationHelper.GetPathToDotNetFrameworkFile(ToolName, TargetDotNetFrameworkVersion.VersionLatest);
if (null == pathToTool)
{
Log.LogErrorWithCodeFromResources("General_FrameworksFileNotFound", ToolName, ToolLocationHelper.GetDotNetFrameworkVersionFolderPrefix(TargetDotNetFrameworkVersion.VersionLatest));
}
}
return pathToTool;
}
/// <summary>
/// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file.
/// </summary>
protected internal override void AddResponseFileCommands(CommandLineBuilderExtension commandLine)
{
commandLine.AppendSwitchIfNotNull("/lib:", AdditionalLibPaths, ",");
commandLine.AppendPlusOrMinusSwitch("/unsafe", _store, nameof(AllowUnsafeBlocks));
commandLine.AppendPlusOrMinusSwitch("/checked", _store, nameof(CheckForOverflowUnderflow));
commandLine.AppendSwitchWithSplitting("/nowarn:", DisabledWarnings, ",", ';', ',');
commandLine.AppendWhenTrue("/fullpaths", _store, nameof(GenerateFullPaths));
commandLine.AppendSwitchIfNotNull("/langversion:", LangVersion);
commandLine.AppendSwitchIfNotNull("/moduleassemblyname:", ModuleAssemblyName);
commandLine.AppendSwitchIfNotNull("/pdb:", PdbFile);
commandLine.AppendPlusOrMinusSwitch("/nostdlib", _store, nameof(NoStandardLib));
commandLine.AppendSwitchIfNotNull("/platform:", PlatformWith32BitPreference);
commandLine.AppendSwitchIfNotNull("/errorreport:", ErrorReport);
commandLine.AppendSwitchWithInteger("/warn:", _store, nameof(WarningLevel));
commandLine.AppendSwitchIfNotNull("/doc:", DocumentationFile);
commandLine.AppendSwitchIfNotNull("/baseaddress:", BaseAddress);
commandLine.AppendSwitchUnquotedIfNotNull("/define:", GetDefineConstantsSwitch(DefineConstants, Log));
commandLine.AppendSwitchIfNotNull("/win32res:", Win32Resource);
commandLine.AppendSwitchIfNotNull("/main:", MainEntryPoint);
commandLine.AppendSwitchIfNotNull("/appconfig:", ApplicationConfiguration);
commandLine.AppendWhenTrue("/errorendlocation", _store, nameof(ErrorEndLocation));
commandLine.AppendSwitchIfNotNull("/preferreduilang:", PreferredUILang);
commandLine.AppendPlusOrMinusSwitch("/highentropyva", _store, nameof(HighEntropyVA));
// If not design time build and the globalSessionGuid property was set then add a -globalsessionguid:<guid>
bool designTime = false;
if (HostObject != null)
{
var csHost = HostObject as ICscHostObject;
designTime = csHost.IsDesignTime();
}
if (!designTime)
{
if (!string.IsNullOrWhiteSpace(VsSessionGuid))
{
commandLine.AppendSwitchIfNotNull("/sqmsessionguid:", VsSessionGuid);
}
}
AddReferencesToCommandLine(commandLine, References);
base.AddResponseFileCommands(commandLine);
// This should come after the "TreatWarningsAsErrors" flag is processed (in managedcompiler.cs).
// Because if TreatWarningsAsErrors=false, then we'll have a /warnaserror- on the command-line,
// and then any specific warnings that should be treated as errors should be specified with
// /warnaserror+:<list> after the /warnaserror- switch. The order of the switches on the command-line
// does matter.
//
// Note that
// /warnaserror+
// is just shorthand for:
// /warnaserror+:<all possible warnings>
//
// Similarly,
// /warnaserror-
// is just shorthand for:
// /warnaserror-:<all possible warnings>
commandLine.AppendSwitchWithSplitting("/warnaserror+:", WarningsAsErrors, ",", ';', ',');
commandLine.AppendSwitchWithSplitting("/warnaserror-:", WarningsNotAsErrors, ",", ';', ',');
// It's a good idea for the response file to be the very last switch passed, just
// from a predictability perspective. It also solves the problem that a dogfooder
// ran into, which is described in an email thread attached to bug VSWhidbey 146883.
// See also bugs 177762 and 118307 for additional bugs related to response file position.
if (ResponseFiles != null)
{
foreach (ITaskItem response in ResponseFiles)
{
commandLine.AppendSwitchIfNotNull("@", response.ItemSpec);
}
}
}
#endregion
/// <summary>
/// The C# compiler (starting with Whidbey) supports assembly aliasing for references.
/// See spec at http://devdiv/spectool/Documents/Whidbey/VCSharp/Design%20Time/M3%20DCRs/DCR%20Assembly%20aliases.doc.
/// This method handles the necessary work of looking at the "Aliases" attribute on
/// the incoming "References" items, and making sure to generate the correct
/// command-line on csc.exe. The syntax for aliasing a reference is:
/// csc.exe /reference:Foo=System.Xml.dll
///
/// The "Aliases" attribute on the "References" items is actually a comma-separated
/// list of aliases, and if any of the aliases specified is the string "global",
/// then we add that reference to the command-line without an alias.
/// </summary>
internal static void AddReferencesToCommandLine(
CommandLineBuilderExtension commandLine,
ITaskItem[] references,
bool isInteractive = false)
{
// If there were no references passed in, don't add any /reference: switches
// on the command-line.
if (references == null)
{
return;
}
// Loop through all the references passed in. We'll be adding separate
// /reference: switches for each reference, and in some cases even multiple
// /reference: switches per reference.
foreach (ITaskItem reference in references)
{
// See if there was an "Alias" attribute on the reference.
string aliasString = reference.GetMetadata("Aliases");
string switchName = "/reference:";
if (!isInteractive)
{
bool embed = Utilities.TryConvertItemMetadataToBool(reference,
"EmbedInteropTypes");
if (embed)
{
switchName = "/link:";
}
}
if (string.IsNullOrEmpty(aliasString))
{
// If there was no "Alias" attribute, just add this as a global reference.
commandLine.AppendSwitchIfNotNull(switchName, reference.ItemSpec);
}
else
{
// If there was an "Alias" attribute, it contains a comma-separated list
// of aliases to use for this reference. For each one of those aliases,
// we're going to add a separate /reference: switch to the csc.exe
// command-line
string[] aliases = aliasString.Split(',');
foreach (string alias in aliases)
{
// Trim whitespace.
string trimmedAlias = alias.Trim();
if (alias.Length == 0)
{
continue;
}
// The alias should be a valid C# identifier. Therefore it cannot
// contain comma, space, semicolon, or double-quote. Let's check for
// the existence of those characters right here, and bail immediately
// if any are present. There are a whole bunch of other characters
// that are not allowed in a C# identifier, but we'll just let csc.exe
// error out on those. The ones we're checking for here are the ones
// that could seriously screw up the command-line parsing or could
// allow parameter injection.
if (trimmedAlias.IndexOfAny(new char[] { ',', ' ', ';', '"' }) != -1)
{
throw Utilities.GetLocalizedArgumentException(
ErrorString.Csc_AssemblyAliasContainsIllegalCharacters,
reference.ItemSpec,
trimmedAlias);
}
// The alias called "global" is special. It means that we don't
// give it an alias on the command-line.
if (string.Compare("global", trimmedAlias, StringComparison.OrdinalIgnoreCase) == 0)
{
commandLine.AppendSwitchIfNotNull(switchName, reference.ItemSpec);
}
else
{
// We have a valid (and explicit) alias for this reference. Add
// it to the command-line using the syntax:
// /reference:Foo=System.Xml.dll
commandLine.AppendSwitchAliased(switchName, trimmedAlias, reference.ItemSpec);
}
}
}
}
}
/// <summary>
/// Old VS projects had some pretty messed-up looking values for the
/// "DefineConstants" property. It worked fine in the IDE, because it
/// effectively munged up the string so that it ended up being valid for
/// the compiler. We do the equivalent munging here now.
///
/// Basically, we take the incoming string, and split it on comma/semicolon/space.
/// Then we look at the resulting list of strings, and remove any that are
/// illegal identifiers, and pass the remaining ones through to the compiler.
///
/// Note that CSharp does support assigning a value to the constants ... in
/// other words, a constant is either defined or not defined ... it can't have
/// an actual value.
/// </summary>
internal static string GetDefineConstantsSwitch(string originalDefineConstants, TaskLoggingHelper log)
{
if (originalDefineConstants == null)
{
return null;
}
StringBuilder finalDefineConstants = new StringBuilder();
// Split the incoming string on comma/semicolon/space.
string[] allIdentifiers = originalDefineConstants.Split(new char[] { ',', ';', ' ' });
// Loop through all the parts, and for the ones that are legal C# identifiers,
// add them to the outgoing string.
foreach (string singleIdentifier in allIdentifiers)
{
if (SyntaxFacts.IsValidIdentifier(singleIdentifier))
{
// Separate them with a semicolon if there's something already in
// the outgoing string.
if (finalDefineConstants.Length > 0)
{
finalDefineConstants.Append(";");
}
finalDefineConstants.Append(singleIdentifier);
}
else if (singleIdentifier.Length > 0)
{
log.LogWarningWithCodeFromResources("Csc_InvalidParameterWarning", "/define:", singleIdentifier);
}
}
if (finalDefineConstants.Length > 0)
{
return finalDefineConstants.ToString();
}
else
{
// We wouldn't want to pass in an empty /define: switch on the csc.exe command-line.
return null;
}
}
/// <summary>
/// This method will initialize the host compiler object with all the switches,
/// parameters, resources, references, sources, etc.
///
/// It returns true if everything went according to plan. It returns false if the
/// host compiler had a problem with one of the parameters that was passed in.
///
/// This method also sets the "this.HostCompilerSupportsAllParameters" property
/// accordingly.
///
/// Example:
/// If we attempted to pass in WarningLevel="9876", then this method would
/// set HostCompilerSupportsAllParameters=true, but it would give a
/// return value of "false". This is because the host compiler fully supports
/// the WarningLevel parameter, but 9876 happens to be an illegal value.
///
/// Example:
/// If we attempted to pass in NoConfig=false, then this method would set
/// HostCompilerSupportsAllParameters=false, because while this is a legal
/// thing for csc.exe, the IDE compiler cannot support it. In this situation
/// the return value will also be false.
/// </summary>
/// <owner>RGoel</owner>
private bool InitializeHostCompiler(ICscHostObject cscHostObject)
{
bool success;
HostCompilerSupportsAllParameters = UseHostCompilerIfAvailable;
string param = "Unknown";
try
{
// Need to set these separately, because they don't require a CommitChanges to the C# compiler in the IDE.
CheckHostObjectSupport(param = nameof(LinkResources), cscHostObject.SetLinkResources(LinkResources));
CheckHostObjectSupport(param = nameof(References), cscHostObject.SetReferences(References));
CheckHostObjectSupport(param = nameof(Resources), cscHostObject.SetResources(Resources));
CheckHostObjectSupport(param = nameof(Sources), cscHostObject.SetSources(Sources));
// For host objects which support it, pass the list of analyzers.
IAnalyzerHostObject analyzerHostObject = cscHostObject as IAnalyzerHostObject;
if (analyzerHostObject != null)
{
CheckHostObjectSupport(param = nameof(Analyzers), analyzerHostObject.SetAnalyzers(Analyzers));
}
}
catch (Exception e)
{
Log.LogErrorWithCodeFromResources("General_CouldNotSetHostObjectParameter", param, e.Message);
return false;
}
try
{
param = nameof(cscHostObject.BeginInitialization);
cscHostObject.BeginInitialization();
CheckHostObjectSupport(param = nameof(AdditionalLibPaths), cscHostObject.SetAdditionalLibPaths(AdditionalLibPaths));
CheckHostObjectSupport(param = nameof(AddModules), cscHostObject.SetAddModules(AddModules));
CheckHostObjectSupport(param = nameof(AllowUnsafeBlocks), cscHostObject.SetAllowUnsafeBlocks(AllowUnsafeBlocks));
CheckHostObjectSupport(param = nameof(BaseAddress), cscHostObject.SetBaseAddress(BaseAddress));
CheckHostObjectSupport(param = nameof(CheckForOverflowUnderflow), cscHostObject.SetCheckForOverflowUnderflow(CheckForOverflowUnderflow));
CheckHostObjectSupport(param = nameof(CodePage), cscHostObject.SetCodePage(CodePage));
// These two -- EmitDebugInformation and DebugType -- must go together, with DebugType
// getting set last, because it is more specific.
CheckHostObjectSupport(param = nameof(EmitDebugInformation), cscHostObject.SetEmitDebugInformation(EmitDebugInformation));
CheckHostObjectSupport(param = nameof(DebugType), cscHostObject.SetDebugType(DebugType));
CheckHostObjectSupport(param = nameof(DefineConstants), cscHostObject.SetDefineConstants(GetDefineConstantsSwitch(DefineConstants, Log)));
CheckHostObjectSupport(param = nameof(DelaySign), cscHostObject.SetDelaySign((_store["DelaySign"] != null), DelaySign));
CheckHostObjectSupport(param = nameof(DisabledWarnings), cscHostObject.SetDisabledWarnings(DisabledWarnings));
CheckHostObjectSupport(param = nameof(DocumentationFile), cscHostObject.SetDocumentationFile(DocumentationFile));
CheckHostObjectSupport(param = nameof(ErrorReport), cscHostObject.SetErrorReport(ErrorReport));
CheckHostObjectSupport(param = nameof(FileAlignment), cscHostObject.SetFileAlignment(FileAlignment));
CheckHostObjectSupport(param = nameof(GenerateFullPaths), cscHostObject.SetGenerateFullPaths(GenerateFullPaths));
CheckHostObjectSupport(param = nameof(KeyContainer), cscHostObject.SetKeyContainer(KeyContainer));
CheckHostObjectSupport(param = nameof(KeyFile), cscHostObject.SetKeyFile(KeyFile));
CheckHostObjectSupport(param = nameof(LangVersion), cscHostObject.SetLangVersion(LangVersion));
CheckHostObjectSupport(param = nameof(MainEntryPoint), cscHostObject.SetMainEntryPoint(TargetType, MainEntryPoint));
CheckHostObjectSupport(param = nameof(ModuleAssemblyName), cscHostObject.SetModuleAssemblyName(ModuleAssemblyName));
CheckHostObjectSupport(param = nameof(NoConfig), cscHostObject.SetNoConfig(NoConfig));
CheckHostObjectSupport(param = nameof(NoStandardLib), cscHostObject.SetNoStandardLib(NoStandardLib));
CheckHostObjectSupport(param = nameof(Optimize), cscHostObject.SetOptimize(Optimize));
CheckHostObjectSupport(param = nameof(OutputAssembly), cscHostObject.SetOutputAssembly(OutputAssembly?.ItemSpec));
CheckHostObjectSupport(param = nameof(PdbFile), cscHostObject.SetPdbFile(PdbFile));
// For host objects which support it, set platform with 32BitPreference, HighEntropyVA, and SubsystemVersion
ICscHostObject4 cscHostObject4 = cscHostObject as ICscHostObject4;
if (cscHostObject4 != null)
{
CheckHostObjectSupport(param = nameof(PlatformWith32BitPreference), cscHostObject4.SetPlatformWith32BitPreference(PlatformWith32BitPreference));
CheckHostObjectSupport(param = nameof(HighEntropyVA), cscHostObject4.SetHighEntropyVA(HighEntropyVA));
CheckHostObjectSupport(param = nameof(SubsystemVersion), cscHostObject4.SetSubsystemVersion(SubsystemVersion));
}
else
{
CheckHostObjectSupport(param = nameof(Platform), cscHostObject.SetPlatform(Platform));
}
// For host objects which support it, set the analyzer ruleset and additional files.
IAnalyzerHostObject analyzerHostObject = cscHostObject as IAnalyzerHostObject;
if (analyzerHostObject != null)
{
CheckHostObjectSupport(param = nameof(CodeAnalysisRuleSet), analyzerHostObject.SetRuleSet(CodeAnalysisRuleSet));
CheckHostObjectSupport(param = nameof(AdditionalFiles), analyzerHostObject.SetAdditionalFiles(AdditionalFiles));
}
ICscHostObject5 cscHostObject5 = cscHostObject as ICscHostObject5;
if (cscHostObject5 != null)
{
CheckHostObjectSupport(param = nameof(ErrorLog), cscHostObject5.SetErrorLog(ErrorLog));
CheckHostObjectSupport(param = nameof(ReportAnalyzer), cscHostObject5.SetReportAnalyzer(ReportAnalyzer));
}
CheckHostObjectSupport(param = nameof(ResponseFiles), cscHostObject.SetResponseFiles(ResponseFiles));
CheckHostObjectSupport(param = nameof(TargetType), cscHostObject.SetTargetType(TargetType));
CheckHostObjectSupport(param = nameof(TreatWarningsAsErrors), cscHostObject.SetTreatWarningsAsErrors(TreatWarningsAsErrors));
CheckHostObjectSupport(param = nameof(WarningLevel), cscHostObject.SetWarningLevel(WarningLevel));
// This must come after TreatWarningsAsErrors.
CheckHostObjectSupport(param = nameof(WarningsAsErrors), cscHostObject.SetWarningsAsErrors(WarningsAsErrors));
// This must come after TreatWarningsAsErrors.
CheckHostObjectSupport(param = nameof(WarningsNotAsErrors), cscHostObject.SetWarningsNotAsErrors(WarningsNotAsErrors));
CheckHostObjectSupport(param = nameof(Win32Icon), cscHostObject.SetWin32Icon(Win32Icon));
// In order to maintain compatibility with previous host compilers, we must
// light-up for ICscHostObject2/ICscHostObject3
if (cscHostObject is ICscHostObject2)
{
ICscHostObject2 cscHostObject2 = (ICscHostObject2)cscHostObject;
CheckHostObjectSupport(param = nameof(Win32Manifest), cscHostObject2.SetWin32Manifest(GetWin32ManifestSwitch(NoWin32Manifest, Win32Manifest)));
}
else
{
// If we have been given a property that the host compiler doesn't support
// then we need to state that we are falling back to the command line compiler
if (!string.IsNullOrEmpty(Win32Manifest))
{
CheckHostObjectSupport(param = nameof(Win32Manifest), resultFromHostObjectSetOperation: false);
}
}
// This must come after Win32Manifest
CheckHostObjectSupport(param = nameof(Win32Resource), cscHostObject.SetWin32Resource(Win32Resource));
if (cscHostObject is ICscHostObject3)
{
ICscHostObject3 cscHostObject3 = (ICscHostObject3)cscHostObject;
CheckHostObjectSupport(param = nameof(ApplicationConfiguration), cscHostObject3.SetApplicationConfiguration(ApplicationConfiguration));
}
else
{
// If we have been given a property that the host compiler doesn't support
// then we need to state that we are falling back to the command line compiler
if (!string.IsNullOrEmpty(ApplicationConfiguration))
{
CheckHostObjectSupport(nameof(ApplicationConfiguration), resultFromHostObjectSetOperation: false);
}
}
InitializeHostObjectSupportForNewSwitches(cscHostObject, ref param);
// If we have been given a property value that the host compiler doesn't support
// then we need to state that we are falling back to the command line compiler.
// Null is supported because it means that option should be omitted, and compiler default used - obviously always valid.
// Explicitly specified name of current locale is also supported, since it is effectively a no-op.
// Other options are not supported since in-proc compiler always uses current locale.
if (!string.IsNullOrEmpty(PreferredUILang) && !string.Equals(PreferredUILang, System.Globalization.CultureInfo.CurrentUICulture.Name, StringComparison.OrdinalIgnoreCase))
{
CheckHostObjectSupport(nameof(PreferredUILang), resultFromHostObjectSetOperation: false);
}
}
catch (Exception e)
{
Log.LogErrorWithCodeFromResources("General_CouldNotSetHostObjectParameter", param, e.Message);
return false;
}
finally
{
int errorCode;
string errorMessage;
success = cscHostObject.EndInitialization(out errorMessage, out errorCode);
if (HostCompilerSupportsAllParameters)
{
// If the host compiler doesn't support everything we need, we're going to end up
// shelling out to the command-line compiler anyway. That means the command-line
// compiler will log the error. So here, we only log the error if we would've
// tried to use the host compiler.
// If EndInitialization returns false, then there was an error. If EndInitialization was
// successful, but there is a valid 'errorMessage,' interpret it as a warning.
if (!success)
{
Log.LogError(null, "CS" + errorCode.ToString("D4", CultureInfo.InvariantCulture), null, null, 0, 0, 0, 0, errorMessage);
}
else if (errorMessage != null && errorMessage.Length > 0)
{
Log.LogWarning(null, "CS" + errorCode.ToString("D4", CultureInfo.InvariantCulture), null, null, 0, 0, 0, 0, errorMessage);
}
}
}
return (success);
}
/// <summary>
/// This method will get called during Execute() if a host object has been passed into the Csc
/// task. Returns one of the following values to indicate what the next action should be:
/// UseHostObjectToExecute Host compiler exists and was initialized.
/// UseAlternateToolToExecute Host compiler doesn't exist or was not appropriate.
/// NoActionReturnSuccess Host compiler was already up-to-date, and we're done.
/// NoActionReturnFailure Bad parameters were passed into the task.
/// </summary>
/// <owner>RGoel</owner>
protected override HostObjectInitializationStatus InitializeHostObject()
{
if (HostObject != null)
{
// When the host object was passed into the task, it was passed in as a generic
// "Object" (because ITask interface obviously can't have any Csc-specific stuff
// in it, and each task is going to want to communicate with its host in a unique
// way). Now we cast it to the specific type that the Csc task expects. If the
// host object does not match this type, the host passed in an invalid host object
// to Csc, and we error out.
// NOTE: For compat reasons this must remain ICscHostObject
// we can dynamically test for smarter interfaces later..
using (RCWForCurrentContext<ICscHostObject> hostObject = new RCWForCurrentContext<ICscHostObject>(HostObject as ICscHostObject))
{
ICscHostObject cscHostObject = hostObject.RCW;
if (cscHostObject != null)
{
bool hostObjectSuccessfullyInitialized = InitializeHostCompiler(cscHostObject);
// If we're currently only in design-time (as opposed to build-time),
// then we're done. We've initialized the host compiler as best we
// can, and we certainly don't want to actually do the final compile.
// So return true, saying we're done and successful.
if (cscHostObject.IsDesignTime())
{
// If we are design-time then we do not want to continue the build at
// this time.
return hostObjectSuccessfullyInitialized ?
HostObjectInitializationStatus.NoActionReturnSuccess :
HostObjectInitializationStatus.NoActionReturnFailure;
}
if (!this.HostCompilerSupportsAllParameters)
{
// Since the host compiler has refused to take on the responsibility for this compilation,
// we're about to shell out to the command-line compiler to handle it. If some of the
// references don't exist on disk, we know the command-line compiler will fail, so save
// the trouble, and just throw a consistent error ourselves. This allows us to give
// more information than the compiler would, and also make things consistent across
// Vbc / Csc / etc. Actually, the real reason is bug 275726 (ddsuites\src\vs\env\vsproject\refs\ptp3).
// This suite behaves differently in localized builds than on English builds because
// VBC.EXE doesn't localize the word "error" when they emit errors and so we can't scan for it.
if (!CheckAllReferencesExistOnDisk())
{
return HostObjectInitializationStatus.NoActionReturnFailure;
}
// The host compiler doesn't support some of the switches/parameters
// being passed to it. Therefore, we resort to using the command-line compiler
// in this case.
UsedCommandLineTool = true;
return HostObjectInitializationStatus.UseAlternateToolToExecute;
}
// Ok, by now we validated that the host object supports the necessary switches
// and parameters. Last thing to check is whether the host object is up to date,
// and in that case, we will inform the caller that no further action is necessary.
if (hostObjectSuccessfullyInitialized)
{
return cscHostObject.IsUpToDate() ?
HostObjectInitializationStatus.NoActionReturnSuccess :
HostObjectInitializationStatus.UseHostObjectToExecute;
}
else
{
return HostObjectInitializationStatus.NoActionReturnFailure;
}
}
else
{
Log.LogErrorWithCodeFromResources("General_IncorrectHostObject", "Csc", "ICscHostObject");
}
}
}
// No appropriate host object was found.
UsedCommandLineTool = true;
return HostObjectInitializationStatus.UseAlternateToolToExecute;
}
/// <summary>
/// This method will get called during Execute() if a host object has been passed into the Csc
/// task. Returns true if the compilation succeeded, otherwise false.
/// </summary>
/// <owner>RGoel</owner>
protected override bool CallHostObjectToExecute()
{
Debug.Assert(HostObject != null, "We should not be here if the host object has not been set.");
ICscHostObject cscHostObject = HostObject as ICscHostObject;
Debug.Assert(cscHostObject != null, "Wrong kind of host object passed in!");
return cscHostObject.Compile();
}
}
}
| |
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using System.Collections.Generic;
using System.Globalization;
using NodaTime.Calendars;
using NodaTime.Text;
using NodaTime.TimeZones;
using NodaTime.Utility;
using NUnit.Framework;
namespace NodaTime.Test
{
/// <summary>
/// Tests for <see cref="LocalDateTime" />.
/// </summary>
[TestFixture]
public partial class LocalDateTimeTest
{
private static readonly DateTimeZone Pacific = DateTimeZoneProviders.Tzdb["America/Los_Angeles"];
[Test]
public void ToDateTimeUnspecified()
{
LocalDateTime zoned = new LocalDateTime(2011, 3, 5, 1, 0, 0);
DateTime expected = new DateTime(2011, 3, 5, 1, 0, 0, DateTimeKind.Unspecified);
DateTime actual = zoned.ToDateTimeUnspecified();
Assert.AreEqual(expected, actual);
// Kind isn't checked by Equals...
Assert.AreEqual(DateTimeKind.Unspecified, actual.Kind);
}
[Test]
public void FromDateTime()
{
LocalDateTime expected = new LocalDateTime(2011, 08, 18, 20, 53);
foreach (DateTimeKind kind in Enum.GetValues(typeof(DateTimeKind)))
{
DateTime x = new DateTime(2011, 08, 18, 20, 53, 0, kind);
LocalDateTime actual = LocalDateTime.FromDateTime(x);
Assert.AreEqual(expected, actual);
}
}
[Test]
public void FromDateTime_WithCalendar()
{
// Julian calendar is 13 days behind Gregorian calendar in the 21st century
LocalDateTime expected = new LocalDateTime(2011, 08, 05, 20, 53, CalendarSystem.Julian);
foreach (DateTimeKind kind in Enum.GetValues(typeof(DateTimeKind)))
{
DateTime x = new DateTime(2011, 08, 18, 20, 53, 0, kind);
LocalDateTime actual = LocalDateTime.FromDateTime(x, CalendarSystem.Julian);
Assert.AreEqual(expected, actual);
}
}
[Test]
public void TimeProperties_AfterEpoch()
{
// Use the largest valid year as part of validating against overflow
LocalDateTime ldt = new LocalDateTime(GregorianYearMonthDayCalculator.MaxGregorianYear, 1, 2, 15, 48, 25, 456, 3456);
Assert.AreEqual(15, ldt.Hour);
Assert.AreEqual(3, ldt.ClockHourOfHalfDay);
Assert.AreEqual(48, ldt.Minute);
Assert.AreEqual(25, ldt.Second);
Assert.AreEqual(456, ldt.Millisecond);
Assert.AreEqual(4563456, ldt.TickOfSecond);
Assert.AreEqual(15 * NodaConstants.TicksPerHour +
48 * NodaConstants.TicksPerMinute +
25 * NodaConstants.TicksPerSecond +
4563456, ldt.TickOfDay);
}
[Test]
public void TimeProperties_BeforeEpoch()
{
// Use the smallest valid year number as part of validating against overflow
LocalDateTime ldt = new LocalDateTime(GregorianYearMonthDayCalculator.MinGregorianYear, 1, 2, 15, 48, 25, 456, 3456);
Assert.AreEqual(15, ldt.Hour);
Assert.AreEqual(3, ldt.ClockHourOfHalfDay);
Assert.AreEqual(48, ldt.Minute);
Assert.AreEqual(25, ldt.Second);
Assert.AreEqual(456, ldt.Millisecond);
Assert.AreEqual(4563456, ldt.TickOfSecond);
Assert.AreEqual(15 * NodaConstants.TicksPerHour +
48 * NodaConstants.TicksPerMinute +
25 * NodaConstants.TicksPerSecond +
4563456, ldt.TickOfDay);
}
[Test]
public void DateTime_Roundtrip_OtherCalendarInBcl()
{
DateTime original = new DateTime(1376, 6, 19, new HijriCalendar());
LocalDateTime noda = LocalDateTime.FromDateTime(original);
// The DateTime only knows about the ISO version...
Assert.AreNotEqual(1376, noda.Year);
Assert.AreEqual(CalendarSystem.Iso, noda.Calendar);
DateTime final = noda.ToDateTimeUnspecified();
Assert.AreEqual(original, final);
}
[Test]
public void WithCalendar()
{
LocalDateTime isoEpoch = new LocalDateTime(1970, 1, 1, 0, 0, 0);
LocalDateTime julianEpoch = isoEpoch.WithCalendar(CalendarSystem.Julian);
Assert.AreEqual(1969, julianEpoch.Year);
Assert.AreEqual(12, julianEpoch.Month);
Assert.AreEqual(19, julianEpoch.Day);
Assert.AreEqual(isoEpoch.TimeOfDay, julianEpoch.TimeOfDay);
}
// Verifies that negative local instant ticks don't cause a problem with the date
[Test]
public void TimeOfDay_Before1970()
{
LocalDateTime dateTime = new LocalDateTime(1965, 11, 8, 12, 5, 23);
LocalTime expected = new LocalTime(12, 5, 23);
Assert.AreEqual(expected, dateTime.TimeOfDay);
}
// Verifies that positive local instant ticks don't cause a problem with the date
[Test]
public void TimeOfDay_After1970()
{
LocalDateTime dateTime = new LocalDateTime(1975, 11, 8, 12, 5, 23);
LocalTime expected = new LocalTime(12, 5, 23);
Assert.AreEqual(expected, dateTime.TimeOfDay);
}
// Verifies that negative local instant ticks don't cause a problem with the date
[Test]
public void Date_Before1970()
{
LocalDateTime dateTime = new LocalDateTime(1965, 11, 8, 12, 5, 23);
LocalDate expected = new LocalDate(1965, 11, 8);
Assert.AreEqual(expected, dateTime.Date);
}
// Verifies that positive local instant ticks don't cause a problem with the date
[Test]
public void Date_After1970()
{
LocalDateTime dateTime = new LocalDateTime(1975, 11, 8, 12, 5, 23);
LocalDate expected = new LocalDate(1975, 11, 8);
Assert.AreEqual(expected, dateTime.Date);
}
[Test]
public void IsoDayOfWeek_AroundEpoch()
{
// Test about couple of months around the Unix epoch. If that works, I'm confident the rest will.
LocalDateTime dateTime = new LocalDateTime(1969, 12, 1, 0, 0);
for (int i = 0; i < 60; i++)
{
// Check once per hour of the day, just in case something's messed up based on the time of day.
for (int hour = 0; hour < 24; hour++)
{
Assert.AreEqual(BclConversions.ToIsoDayOfWeek(dateTime.ToDateTimeUnspecified().DayOfWeek),
dateTime.IsoDayOfWeek);
dateTime = dateTime.PlusHours(1);
}
}
}
[Test]
public void ClockHourOfHalfDay()
{
Assert.AreEqual(12, new LocalDateTime(1975, 11, 8, 0, 0, 0).ClockHourOfHalfDay);
Assert.AreEqual(1, new LocalDateTime(1975, 11, 8, 1, 0, 0).ClockHourOfHalfDay);
Assert.AreEqual(12, new LocalDateTime(1975, 11, 8, 12, 0, 0).ClockHourOfHalfDay);
Assert.AreEqual(1, new LocalDateTime(1975, 11, 8, 13, 0, 0).ClockHourOfHalfDay);
Assert.AreEqual(11, new LocalDateTime(1975, 11, 8, 23, 0, 0).ClockHourOfHalfDay);
}
[Test]
public void ComparisonOperators_SameCalendar()
{
LocalDateTime value1 = new LocalDateTime(2011, 1, 2, 10, 30, 0);
LocalDateTime value2 = new LocalDateTime(2011, 1, 2, 10, 30, 0);
LocalDateTime value3 = new LocalDateTime(2011, 1, 2, 10, 45, 0);
Assert.IsFalse(value1 < value2);
Assert.IsTrue(value1 < value3);
Assert.IsFalse(value2 < value1);
Assert.IsFalse(value3 < value1);
Assert.IsTrue(value1 <= value2);
Assert.IsTrue(value1 <= value3);
Assert.IsTrue(value2 <= value1);
Assert.IsFalse(value3 <= value1);
Assert.IsFalse(value1 > value2);
Assert.IsFalse(value1 > value3);
Assert.IsFalse(value2 > value1);
Assert.IsTrue(value3 > value1);
Assert.IsTrue(value1 >= value2);
Assert.IsFalse(value1 >= value3);
Assert.IsTrue(value2 >= value1);
Assert.IsTrue(value3 >= value1);
}
[Test]
public void ComparisonOperators_DifferentCalendars_Throws()
{
LocalDateTime value1 = new LocalDateTime(2011, 1, 2, 10, 30);
LocalDateTime value2 = new LocalDateTime(2011, 1, 3, 10, 30, CalendarSystem.Julian);
Assert.Throws<ArgumentException>(() => (value1 < value2).ToString());
Assert.Throws<ArgumentException>(() => (value1 <= value2).ToString());
Assert.Throws<ArgumentException>(() => (value1 > value2).ToString());
Assert.Throws<ArgumentException>(() => (value1 >= value2).ToString());
}
[Test]
public void CompareTo_SameCalendar()
{
LocalDateTime value1 = new LocalDateTime(2011, 1, 2, 10, 30);
LocalDateTime value2 = new LocalDateTime(2011, 1, 2, 10, 30);
LocalDateTime value3 = new LocalDateTime(2011, 1, 2, 10, 45);
Assert.That(value1.CompareTo(value2), Is.EqualTo(0));
Assert.That(value1.CompareTo(value3), Is.LessThan(0));
Assert.That(value3.CompareTo(value2), Is.GreaterThan(0));
}
[Test]
public void CompareTo_DifferentCalendars_Throws()
{
CalendarSystem islamic = CalendarSystem.GetIslamicCalendar(IslamicLeapYearPattern.Base15, IslamicEpoch.Astronomical);
LocalDateTime value1 = new LocalDateTime(2011, 1, 2, 10, 30);
LocalDateTime value2 = new LocalDateTime(1500, 1, 1, 10, 30, islamic);
Assert.Throws<ArgumentException>(() => value1.CompareTo(value2));
Assert.Throws<ArgumentException>(() => ((IComparable)value1).CompareTo(value2));
}
/// <summary>
/// IComparable.CompareTo works properly for LocalDateTime inputs with different calendars.
/// </summary>
[Test]
public void IComparableCompareTo_SameCalendar()
{
LocalDateTime value1 = new LocalDateTime(2011, 1, 2, 10, 30);
LocalDateTime value2 = new LocalDateTime(2011, 1, 2, 10, 30);
LocalDateTime value3 = new LocalDateTime(2011, 1, 2, 10, 45);
IComparable i_value1 = (IComparable)value1;
IComparable i_value3 = (IComparable)value3;
Assert.That(i_value1.CompareTo(value2), Is.EqualTo(0));
Assert.That(i_value1.CompareTo(value3), Is.LessThan(0));
Assert.That(i_value3.CompareTo(value2), Is.GreaterThan(0));
}
/// <summary>
/// IComparable.CompareTo returns a positive number for a null input.
/// </summary>
[Test]
public void IComparableCompareTo_Null_Positive()
{
var instance = new LocalDateTime(2012, 3, 5, 10, 45);
var i_instance = (IComparable)instance;
object arg = null;
var result = i_instance.CompareTo(arg);
Assert.That(result, Is.GreaterThan(0));
}
/// <summary>
/// IComparable.CompareTo throws an ArgumentException for non-null arguments
/// that are not a LocalDateTime.
/// </summary>
[Test]
public void IComparableCompareTo_WrongType_ArgumentException()
{
var instance = new LocalDateTime(2012, 3, 5, 10, 45);
var i_instance = (IComparable)instance;
var arg = new LocalDate(2012, 3, 6);
Assert.Throws<ArgumentException>(() => i_instance.CompareTo(arg));
}
[Test]
public void WithOffset()
{
var offset = Offset.FromHoursAndMinutes(5, 10);
var localDateTime = new LocalDateTime(2009, 12, 22, 21, 39, 30);
var offsetDateTime = localDateTime.WithOffset(offset);
Assert.AreEqual(localDateTime, offsetDateTime.LocalDateTime);
Assert.AreEqual(offset, offsetDateTime.Offset);
}
[Test]
public void InUtc()
{
var local = new LocalDateTime(2009, 12, 22, 21, 39, 30);
var zoned = local.InUtc();
Assert.AreEqual(local, zoned.LocalDateTime);
Assert.AreEqual(Offset.Zero, zoned.Offset);
Assert.AreSame(DateTimeZone.Utc, zoned.Zone);
}
[Test]
public void InZoneStrictly_InWinter()
{
var local = new LocalDateTime(2009, 12, 22, 21, 39, 30);
var zoned = local.InZoneStrictly(Pacific);
Assert.AreEqual(local, zoned.LocalDateTime);
Assert.AreEqual(Offset.FromHours(-8), zoned.Offset);
}
[Test]
public void InZoneStrictly_InSummer()
{
var local = new LocalDateTime(2009, 6, 22, 21, 39, 30);
var zoned = local.InZoneStrictly(Pacific);
Assert.AreEqual(local, zoned.LocalDateTime);
Assert.AreEqual(Offset.FromHours(-7), zoned.Offset);
}
/// <summary>
/// Pacific time changed from -7 to -8 at 2am wall time on November 2nd 2009,
/// so 2am became 1am.
/// </summary>
[Test]
public void InZoneStrictly_ThrowsWhenAmbiguous()
{
var local = new LocalDateTime(2009, 11, 1, 1, 30, 0);
Assert.Throws<AmbiguousTimeException>(() => local.InZoneStrictly(Pacific));
}
/// <summary>
/// Pacific time changed from -8 to -7 at 2am wall time on March 8th 2009,
/// so 2am became 3am. This means that 2.30am doesn't exist on that day.
/// </summary>
[Test]
public void InZoneStrictly_ThrowsWhenSkipped()
{
var local = new LocalDateTime(2009, 3, 8, 2, 30, 0);
Assert.Throws<SkippedTimeException>(() => local.InZoneStrictly(Pacific));
}
/// <summary>
/// Pacific time changed from -7 to -8 at 2am wall time on November 2nd 2009,
/// so 2am became 1am. We'll return the earlier result, i.e. with the offset of -7
/// </summary>
[Test]
public void InZoneLeniently_AmbiguousTime_ReturnsEarlierMapping()
{
var local = new LocalDateTime(2009, 11, 1, 1, 30, 0);
var zoned = local.InZoneLeniently(Pacific);
Assert.AreEqual(local, zoned.LocalDateTime);
Assert.AreEqual(Offset.FromHours(-7), zoned.Offset);
}
/// <summary>
/// Pacific time changed from -8 to -7 at 2am wall time on March 8th 2009,
/// so 2am became 3am. This means that 2:30am doesn't exist on that day.
/// We'll return 3:30am, the forward-shifted value.
/// </summary>
[Test]
public void InZoneLeniently_ReturnsStartOfSecondInterval()
{
var local = new LocalDateTime(2009, 3, 8, 2, 30, 0);
var zoned = local.InZoneLeniently(Pacific);
Assert.AreEqual(new LocalDateTime(2009, 3, 8, 3, 30, 0), zoned.LocalDateTime);
Assert.AreEqual(Offset.FromHours(-7), zoned.Offset);
}
[Test]
public void InZone()
{
// Don't need much for this - it only delegates.
var ambiguous = new LocalDateTime(2009, 11, 1, 1, 30, 0);
var skipped = new LocalDateTime(2009, 3, 8, 2, 30, 0);
Assert.AreEqual(Pacific.AtLeniently(ambiguous), ambiguous.InZone(Pacific, Resolvers.LenientResolver));
Assert.AreEqual(Pacific.AtLeniently(skipped), skipped.InZone(Pacific, Resolvers.LenientResolver));
}
/// <summary>
/// Using the default constructor is equivalent to January 1st 1970, midnight, UTC, ISO calendar
/// </summary>
[Test]
public void DefaultConstructor()
{
var actual = new LocalDateTime();
Assert.AreEqual(new LocalDateTime(1, 1, 1, 0, 0), actual);
}
[Test]
public void XmlSerialization_Iso()
{
var value = new LocalDateTime(2013, 4, 12, 17, 53, 23, 123, 4567);
TestHelper.AssertXmlRoundtrip(value, "<value>2013-04-12T17:53:23.1234567</value>");
}
[Test]
public void BinarySerialization()
{
TestHelper.AssertBinaryRoundtrip(new LocalDateTime(2013, 4, 12, 17, 53, 23, CalendarSystem.Julian));
TestHelper.AssertBinaryRoundtrip(new LocalDateTime(2013, 4, 12, 17, 53, 23, 123, 4567));
}
[Test]
public void XmlSerialization_NonIso()
{
var value = new LocalDateTime(2013, 4, 12, 17, 53, 23, CalendarSystem.Julian);
TestHelper.AssertXmlRoundtrip(value, "<value calendar=\"Julian\">2013-04-12T17:53:23</value>");
}
[Test]
[TestCase("<value calendar=\"Rubbish\">2013-06-12T17:53:23</value>", typeof(KeyNotFoundException), Description = "Unknown calendar system")]
[TestCase("<value>2013-15-12T17:53:23</value>", typeof(UnparsableValueException), Description = "Invalid month")]
public void XmlSerialization_Invalid(string xml, Type expectedExceptionType)
{
TestHelper.AssertXmlInvalid<LocalDateTime>(xml, expectedExceptionType);
}
}
}
| |
// Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Hazelcast.Client.Connection;
using Hazelcast.Client.Protocol.Codec;
using Hazelcast.Core;
using Hazelcast.IO;
using Hazelcast.Logging;
using Hazelcast.Util;
#pragma warning disable CS1591
namespace Hazelcast.Client.Spi
{
internal class ClientMembershipListener
{
public const int InitialMembersTimeoutSeconds = 5;
private static readonly ILogger Logger = Logging.Logger.GetLogger(typeof (ClientMembershipListener));
private readonly HazelcastClient _client;
private readonly ClientClusterService _clusterService;
private readonly ClientConnectionManager _connectionManager;
private readonly IList<IMember> _members = new List<IMember>();
private readonly ClientPartitionService _partitionService;
private ManualResetEventSlim _initialListFetched;
public ClientMembershipListener(HazelcastClient client)
{
_client = client;
_connectionManager = (ClientConnectionManager) client.GetConnectionManager();
_partitionService = (ClientPartitionService) client.GetClientPartitionService();
_clusterService = (ClientClusterService) client.GetClientClusterService();
}
public virtual void BeforeListenerRegister()
{
}
public void HandleMember(IMember member, int eventType)
{
switch (eventType)
{
case MembershipEvent.MemberAdded:
{
MemberAdded(member);
break;
}
case MembershipEvent.MemberRemoved:
{
MemberRemoved(member);
break;
}
default:
{
Logger.Warning("Unknown event type :" + eventType);
break;
}
}
_partitionService.RefreshPartitions();
}
public void HandleMemberAttributeChange(string uuid, string key, int operationType, string value)
{
var memberMap = _clusterService.GetMembersRef();
if (memberMap == null)
{
return;
}
foreach (var target in memberMap.Values)
{
if (target.GetUuid().Equals(uuid))
{
var type = (MemberAttributeOperationType) operationType;
((Member) target).UpdateAttribute(type, key, value);
var memberAttributeEvent = new MemberAttributeEvent(_client.GetCluster(), target, type, key,
value);
_clusterService.FireMemberAttributeEvent(memberAttributeEvent);
break;
}
}
}
public void HandleMemberCollection(ICollection<IMember> initialMembers)
{
var prevMembers = new Dictionary<string, IMember>();
if (_members.Any())
{
prevMembers = new Dictionary<string, IMember>(_members.Count);
foreach (var member in _members)
{
prevMembers[member.GetUuid()] = member;
}
_members.Clear();
}
foreach (var initialMember in initialMembers)
{
_members.Add(initialMember);
}
var events = DetectMembershipEvents(prevMembers);
if (events.Count != 0)
{
ApplyMemberListChanges();
}
FireMembershipEvent(events);
_initialListFetched.Set();
}
public virtual void OnListenerRegister()
{
}
internal virtual void ListenMembershipEvents(Address ownerConnectionAddress)
{
Logger.Finest("Starting to listen for membership events from " + ownerConnectionAddress);
_initialListFetched = new ManualResetEventSlim();
try
{
var clientMessage = ClientAddMembershipListenerCodec.EncodeRequest(false);
DistributedEventHandler handler = m => ClientAddMembershipListenerCodec.EventHandler
.HandleEvent(m, HandleMember, HandleMemberCollection, HandleMemberAttributeChange);
try
{
var connection = _connectionManager.GetConnection(ownerConnectionAddress);
if (connection == null)
{
throw new InvalidOperationException(
"Can not load initial members list because owner connection is null. Address "
+ ownerConnectionAddress);
}
var invocationService = (ClientInvocationService) _client.GetInvocationService();
var future = invocationService.InvokeListenerOnConnection(clientMessage, handler, connection);
var response = ThreadUtil.GetResult(future);
//registraiton id is ignored as this listener will never be removed
var registirationId = ClientAddMembershipListenerCodec.DecodeResponse(response).response;
WaitInitialMemberListFetched();
}
catch (Exception e)
{
throw ExceptionUtil.Rethrow(e);
}
}
catch (Exception e)
{
if (_client.GetLifecycleService().IsRunning())
{
if (Logger.IsFinestEnabled())
{
Logger.Warning("Error while registering to cluster events! -> " + ownerConnectionAddress, e);
}
else
{
Logger.Warning("Error while registering to cluster events! -> " + ownerConnectionAddress +
", Error: " + e);
}
}
}
}
private void ApplyMemberListChanges()
{
UpdateMembersRef();
Logger.Info(_clusterService.MembersString());
}
private IList<MembershipEvent> DetectMembershipEvents(IDictionary<string, IMember> prevMembers)
{
IList<MembershipEvent> events = new List<MembershipEvent>();
var eventMembers = GetMembers();
foreach (var member in _members)
{
IMember former;
prevMembers.TryGetValue(member.GetUuid(), out former);
if (former == null)
{
events.Add(new MembershipEvent(_client.GetCluster(), member, MembershipEvent.MemberAdded,
eventMembers));
}
else
{
prevMembers.Remove(member.GetUuid());
}
}
foreach (var member in prevMembers.Values)
{
events.Add(new MembershipEvent(_client.GetCluster(), member, MembershipEvent.MemberRemoved, eventMembers));
var address = member.GetAddress();
if (_clusterService.GetMember(address) == null)
{
var connection = _connectionManager.GetConnection(address);
if (connection != null)
{
_connectionManager.DestroyConnection(connection, new TargetDisconnectedException(address, "member left the cluster."));
}
}
}
return events;
}
private void FireMembershipEvent(IList<MembershipEvent> events)
{
foreach (var @event in events)
{
_clusterService.FireMembershipEvent(@event);
}
}
private ICollection<IMember> GetMembers()
{
var set = new HashSet<IMember>();
foreach (var member in _members)
{
set.Add(member);
}
return set;
}
private void MemberAdded(IMember member)
{
_members.Add(member);
ApplyMemberListChanges();
var @event = new MembershipEvent(_client.GetCluster(), member, MembershipEvent.MemberAdded, GetMembers());
_clusterService.FireMembershipEvent(@event);
}
private void MemberRemoved(IMember member)
{
_members.Remove(member);
ApplyMemberListChanges();
var connection = _connectionManager.GetConnection(member.GetAddress());
if (connection != null)
{
_connectionManager.DestroyConnection(connection, new TargetDisconnectedException(member.GetAddress(),
"member left the cluster."));
}
var @event = new MembershipEvent(_client.GetCluster(), member, MembershipEvent.MemberRemoved, GetMembers());
_clusterService.FireMembershipEvent(@event);
}
private void UpdateMembersRef()
{
IDictionary<Address, IMember> map = new Dictionary<Address, IMember>(_members.Count);
foreach (var member in _members)
{
map[member.GetAddress()] = member;
}
_clusterService.SetMembersRef(map);
}
/// <exception cref="System.Exception" />
private void WaitInitialMemberListFetched()
{
var timeout = TimeUnit.Seconds.ToMillis(InitialMembersTimeoutSeconds);
var success = _initialListFetched.Wait((int) timeout);
if (!success)
{
Logger.Warning("Error while getting initial member list from cluster!");
}
}
}
}
| |
//
// Copyright (c) 2004-2017 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;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using NLog.Time;
namespace NLog.Fluent
{
/// <summary>
/// A fluent class to build log events for NLog.
/// </summary>
public class LogBuilder
{
private readonly LogEventInfo _logEvent;
private readonly ILogger _logger;
/// <summary>
/// Initializes a new instance of the <see cref="LogBuilder"/> class.
/// </summary>
/// <param name="logger">The <see cref="Logger"/> to send the log event.</param>
[CLSCompliant(false)]
public LogBuilder(ILogger logger)
: this(logger, LogLevel.Debug)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogBuilder"/> class.
/// </summary>
/// <param name="logger">The <see cref="Logger"/> to send the log event.</param>
/// <param name="logLevel">The <see cref="LogLevel"/> for the log event.</param>
[CLSCompliant(false)]
public LogBuilder(ILogger logger, LogLevel logLevel)
{
if (logger == null)
throw new ArgumentNullException("logger");
if (logLevel == null)
throw new ArgumentNullException("logLevel");
_logger = logger;
_logEvent = new LogEventInfo
{
Level = logLevel,
LoggerName = logger.Name,
TimeStamp = TimeSource.Current.Time
};
}
/// <summary>
/// Gets the <see cref="LogEventInfo"/> created by the builder.
/// </summary>
public LogEventInfo LogEventInfo
{
get { return _logEvent; }
}
/// <summary>
/// Sets the <paramref name="exception"/> information of the logging event.
/// </summary>
/// <param name="exception">The exception information of the logging event.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder Exception(Exception exception)
{
_logEvent.Exception = exception;
return this;
}
/// <summary>
/// Sets the level of the logging event.
/// </summary>
/// <param name="logLevel">The level of the logging event.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder Level(LogLevel logLevel)
{
if (logLevel == null)
throw new ArgumentNullException("logLevel");
_logEvent.Level = logLevel;
return this;
}
/// <summary>
/// Sets the logger name of the logging event.
/// </summary>
/// <param name="loggerName">The logger name of the logging event.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder LoggerName(string loggerName)
{
_logEvent.LoggerName = loggerName;
return this;
}
/// <summary>
/// Sets the log message on the logging event.
/// </summary>
/// <param name="message">The log message for the logging event.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder Message(string message)
{
_logEvent.Message = message;
return this;
}
/// <summary>
/// Sets the log message and parameters for formatting on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="arg0">The object to format.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
[StringFormatMethod("format")]
public LogBuilder Message(string format, object arg0)
{
_logEvent.Message = format;
_logEvent.Parameters = new[] { arg0 };
return this;
}
/// <summary>
/// Sets the log message and parameters for formatting on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="arg0">The first object to format.</param>
/// <param name="arg1">The second object to format.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
[StringFormatMethod("format")]
public LogBuilder Message(string format, object arg0, object arg1)
{
_logEvent.Message = format;
_logEvent.Parameters = new[] { arg0, arg1 };
return this;
}
/// <summary>
/// Sets the log message and parameters for formatting on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="arg0">The first object to format.</param>
/// <param name="arg1">The second object to format.</param>
/// <param name="arg2">The third object to format.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
[StringFormatMethod("format")]
public LogBuilder Message(string format, object arg0, object arg1, object arg2)
{
_logEvent.Message = format;
_logEvent.Parameters = new[] { arg0, arg1, arg2 };
return this;
}
/// <summary>
/// Sets the log message and parameters for formatting on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="arg0">The first object to format.</param>
/// <param name="arg1">The second object to format.</param>
/// <param name="arg2">The third object to format.</param>
/// <param name="arg3">The fourth object to format.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
[StringFormatMethod("format")]
public LogBuilder Message(string format, object arg0, object arg1, object arg2, object arg3)
{
_logEvent.Message = format;
_logEvent.Parameters = new[] { arg0, arg1, arg2, arg3 };
return this;
}
/// <summary>
/// Sets the log message and parameters for formatting on the logging event.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
[StringFormatMethod("format")]
public LogBuilder Message(string format, params object[] args)
{
_logEvent.Message = format;
_logEvent.Parameters = args;
return this;
}
/// <summary>
/// Sets the log message and parameters for formatting on the logging event.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="format">A composite format string.</param>
/// <param name="args">An object array that contains zero or more objects to format.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
[StringFormatMethod("format")]
public LogBuilder Message(IFormatProvider provider, string format, params object[] args)
{
_logEvent.FormatProvider = provider;
_logEvent.Message = format;
_logEvent.Parameters = args;
return this;
}
/// <summary>
/// Sets a per-event context property on the logging event.
/// </summary>
/// <param name="name">The name of the context property.</param>
/// <param name="value">The value of the context property.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder Property(object name, object value)
{
if (name == null)
throw new ArgumentNullException("name");
_logEvent.Properties[name] = value;
return this;
}
/// <summary>
/// Sets multiple per-event context properties on the logging event.
/// </summary>
/// <param name="properties">The properties to set.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder Properties(IDictionary properties)
{
if (properties == null)
throw new ArgumentNullException("properties");
foreach (var key in properties.Keys)
{
_logEvent.Properties[key] = properties[key];
}
return this;
}
/// <summary>
/// Sets the timestamp of the logging event.
/// </summary>
/// <param name="timeStamp">The timestamp of the logging event.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder TimeStamp(DateTime timeStamp)
{
_logEvent.TimeStamp = timeStamp;
return this;
}
/// <summary>
/// Sets the stack trace for the event info.
/// </summary>
/// <param name="stackTrace">The stack trace.</param>
/// <param name="userStackFrame">Index of the first user stack frame within the stack trace.</param>
/// <returns>current <see cref="LogBuilder"/> for chaining calls.</returns>
public LogBuilder StackTrace(StackTrace stackTrace, int userStackFrame)
{
_logEvent.SetStackTrace(stackTrace, userStackFrame);
return this;
}
#if NET4_5
/// <summary>
/// Writes the log event to the underlying logger.
/// </summary>
/// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param>
/// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param>
public void Write(
[CallerMemberName]string callerMemberName = null,
[CallerFilePath]string callerFilePath = null,
[CallerLineNumber]int callerLineNumber = 0)
{
if (callerMemberName != null)
Property("CallerMemberName", callerMemberName);
if (callerFilePath != null)
Property("CallerFilePath", callerFilePath);
if (callerLineNumber != 0)
Property("CallerLineNumber", callerLineNumber);
_logger.Log(_logEvent);
}
#else
/// <summary>
/// Writes the log event to the underlying logger.
/// </summary>
public void Write()
{
_logger.Log(_logEvent);
}
#endif
#if NET4_5
/// <summary>
/// Writes the log event to the underlying logger if the condition delegate is true.
/// </summary>
/// <param name="condition">If condition is true, write log event; otherwise ignore event.</param>
/// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param>
/// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param>
public void WriteIf(
Func<bool> condition,
[CallerMemberName]string callerMemberName = null,
[CallerFilePath]string callerFilePath = null,
[CallerLineNumber]int callerLineNumber = 0)
{
if (condition == null || !condition())
return;
if (callerMemberName != null)
Property("CallerMemberName", callerMemberName);
if (callerFilePath != null)
Property("CallerFilePath", callerFilePath);
if (callerLineNumber != 0)
Property("CallerLineNumber", callerLineNumber);
_logger.Log(_logEvent);
}
#else
/// <summary>
/// Writes the log event to the underlying logger.
/// </summary>
/// <param name="condition">If condition is true, write log event; otherwise ignore event.</param>
public void WriteIf(Func<bool> condition)
{
if (condition == null || !condition())
return;
_logger.Log(_logEvent);
}
#endif
#if NET4_5
/// <summary>
/// Writes the log event to the underlying logger if the condition is true.
/// </summary>
/// <param name="condition">If condition is true, write log event; otherwise ignore event.</param>
/// <param name="callerMemberName">The method or property name of the caller to the method. This is set at by the compiler.</param>
/// <param name="callerFilePath">The full path of the source file that contains the caller. This is set at by the compiler.</param>
/// <param name="callerLineNumber">The line number in the source file at which the method is called. This is set at by the compiler.</param>
public void WriteIf(
bool condition,
[CallerMemberName]string callerMemberName = null,
[CallerFilePath]string callerFilePath = null,
[CallerLineNumber]int callerLineNumber = 0)
{
if (!condition)
return;
if (callerMemberName != null)
Property("CallerMemberName", callerMemberName);
if (callerFilePath != null)
Property("CallerFilePath", callerFilePath);
if (callerLineNumber != 0)
Property("CallerLineNumber", callerLineNumber);
_logger.Log(_logEvent);
}
#else
/// <summary>
/// Writes the log event to the underlying logger.
/// </summary>
/// <param name="condition">If condition is true, write log event; otherwise ignore event.</param>
public void WriteIf(bool condition)
{
if (!condition)
return;
_logger.Log(_logEvent);
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
/// <summary>
/// System.Threading.Interlocked.CompareExchange(ref object,object,object)
/// </summary>
// Tests that CompareExchange(object, object, object)
// plays nicely with another thread accessing shared state directly
// Also includes a test for when location = comparand = null (should
// switch).
public class InterlockedCompareExchange5
{
public static object globalValue;
public Thread threadA;
public Thread threadB;
public object state;
public myClass obMyClass;
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: The object is a string");
try
{
// Spin up two new threads
threadA = new Thread(new ThreadStart(TestComChange));
threadB = new Thread(new ThreadStart(changeGlobal));
// Start Thread A
// Thread A runs TestComChange
threadA.Start();
// Block spawning thread until Thread A completes
threadA.Join();
// Once Thread A completes, block spawning thread
// until Thread B completes as well
threadB.Join();
// now, the final values of
// globalValue and state should be "changedValue"
if (globalValue.ToString() != "changedValue" && state != (object)("changedValue"))
{
TestLibrary.TestFramework.LogError("001", "The method did not works, the result is" + globalValue + " " + state);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: The object is a custom class");
obMyClass = new myClass(123456789);
try
{
// Spin up two new threads
threadA = new Thread(new ThreadStart(TestComChange2));
threadB = new Thread(new ThreadStart(changeGlobal2));
// Start Thread A
// Thread A runs TestComChange2
threadA.Start();
// Block spawning thread until Thread A completes
threadA.Join();
// Once Thread A completes, block spawning thread
// until Thread B completes as well
threadB.Join();
// now, the final values of
// globalValue and state should NOT be -100
if (((myClass)globalValue).a != -100 && ((myClass)state).a != -100)
{
TestLibrary.TestFramework.LogError("003", "The method did not works, the result is" + globalValue + " " + state);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: The first argument is a null reference");
try
{
// a non-null object
object value = new myClass(-100);
// a null object
object comparand = null;
// a null initial state
globalValue = null;
// globalValue is null, so it should switch
// and return null
// this is a major difference with
// InterlockedCompareExchange8.cs --
// here we use the object overload
state = Interlocked.CompareExchange(ref globalValue, value, comparand);
// globalValue should equal value now
if (globalValue != value)
{
TestLibrary.TestFramework.LogError("005", "The method did not works, the result is" + globalValue + " " + state);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Negative Test Cases
#endregion
#endregion
public static int Main()
{
InterlockedCompareExchange5 test = new InterlockedCompareExchange5();
TestLibrary.TestFramework.BeginTestCase("InterlockedCompareExchange5");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public void TestComChange()
{
// set a value
object value = "changedValue";
// set a different value
object comparand = "comparand";
int i = 0;
// loop 20 times
while (i < 20)
{
// first ten times, we just skip this
// then on the tenth time, fire Thread B,
// setting globalValue to "Comparand"
if (i == 10)
{
threadB.Start();
}
// first ten iterations, globalValue does not
// equal comparand, so it keeps returning
// the contents of globalValue without
// poking value into it
// after ten, Thread B kicks in, and
// it matches, subsequently, globalValue
// gets set to "changedValue"
// this is a major difference with
// InterlockedCompareExchange8.cs --
// here we use the object overload
state = Interlocked.CompareExchange(ref globalValue, value, comparand);
i++;
Thread.Sleep(10);
}
}
public void changeGlobal()
{
// set when B runs
globalValue = "comparand";
}
public void TestComChange2()
{
// set a value
object value = new myClass(-100);
// set a different value
object comparand = obMyClass;
int i = 0;
// loop 20 times
while (i < 20)
{
// first ten times, we just skip this
// then on the tenth time, fire Thread B,
// setting globalValue to obMyClass
if (i == 10)
{
threadB.Start();
}
// first ten iterations, globalValue does not
// equal comparand, so it keeps returning
// the contents of globalValue without
// poking value into it
// after ten, Thread B kicks in, and
// it matches, subsequently, globalValue
// gets set to point to where value does
// this is a major difference with
// InterlockedCompareExchange8.cs --
// here we use the object overload
state = Interlocked.CompareExchange(ref globalValue, value, comparand);
i++;
Thread.Sleep(10);
}
}
public void changeGlobal2()
{
globalValue = obMyClass;
}
}
public class myClass
{
public int a;
public myClass(int value)
{
a = value;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ExpressRouteCircuitPeeringsOperations operations.
/// </summary>
internal partial class ExpressRouteCircuitPeeringsOperations : IServiceOperations<NetworkManagementClient>, IExpressRouteCircuitPeeringsOperations
{
/// <summary>
/// Initializes a new instance of the ExpressRouteCircuitPeeringsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ExpressRouteCircuitPeeringsOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Deletes the specified peering from the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified authorization from the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ExpressRouteCircuitPeering>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (peeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "peeringName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("peeringName", peeringName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{peeringName}", System.Uri.EscapeDataString(peeringName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ExpressRouteCircuitPeering>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitPeering>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a peering in the specified express route circuits.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='peeringParameters'>
/// Parameters supplied to the create or update express route circuit peering
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ExpressRouteCircuitPeering>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<ExpressRouteCircuitPeering> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, peeringName, peeringParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all peerings in a specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>> ListWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteCircuitPeering>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified peering from the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (peeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "peeringName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("peeringName", peeringName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{peeringName}", System.Uri.EscapeDataString(peeringName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a peering in the specified express route circuits.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='peeringParameters'>
/// Parameters supplied to the create or update express route circuit peering
/// operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ExpressRouteCircuitPeering>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (circuitName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "circuitName");
}
if (peeringName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "peeringName");
}
if (peeringParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "peeringParameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-09-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("circuitName", circuitName);
tracingParameters.Add("peeringName", peeringName);
tracingParameters.Add("peeringParameters", peeringParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName));
_url = _url.Replace("{peeringName}", System.Uri.EscapeDataString(peeringName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(peeringParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(peeringParameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ExpressRouteCircuitPeering>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitPeering>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitPeering>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all peerings in a specified express route circuit.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteCircuitPeering>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) MarinAtanasov. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the project root for license information.
using AppBrix.Tests;
using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace AppBrix.Random.Tests;
public sealed class RandomServiceTests : TestsBase
{
#region Setup and cleanup
public RandomServiceTests() : base(TestUtils.CreateTestApp<RandomModule>()) => this.app.Start();
#endregion
#region Tests
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestGenerateRandomItemsNullItems()
{
var service = this.app.GetRandomService();
Action action = () => service.GetRandomItems<object>(null);
action.Should().Throw<ArgumentNullException>("items should not be null.");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestGenerateRandomItemsEmptyItems()
{
var service = this.app.GetRandomService();
var generated = service.GetRandomItems(Array.Empty<object>());
generated.Should().NotBeNull($"{nameof(service.GetRandomItems)} should never return null.");
generated.Should().BeSameAs(Array.Empty<object>(), $"{nameof(service.GetRandomItems)} should return an empty array.");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestGenerateRandomItemsRepeated()
{
var service = this.app.GetRandomService();
var original = Enumerable.Range(0, 1000).ToList();
var items = original.ToList();
var generated = service.GetRandomItems(items);
items.Count.Should().Be(original.Count, "The collection size should not be modified.");
Enumerable.Range(0, original.Count).All(x => items[x] == original[x]).Should().BeTrue("All items should be in their original position.");
var visited = new int[original.Count];
var moved = false;
var repeated = false;
var total = 0;
foreach (var item in generated)
{
if (total < original.Count)
moved |= item != original[total];
repeated |= visited[item] > 1;
visited[item]++;
total++;
if (moved && repeated && total > original.Count || total > original.Count * 2)
break;
}
moved.Should().BeTrue("Some items should have been shuffled.");
repeated.Should().BeTrue("Some items should be seen more than once.");
total.Should().BeGreaterThan(original.Count, "Item generation should continue after exhausting the collection.");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestGenerateRandomItemsDifferentSeeds()
{
var service = this.app.GetRandomService();
var original = Enumerable.Range(0, 1000).ToList();
var items1 = service.GetRandomItems(original, 23).Take(original.Count).ToList();
var items2 = service.GetRandomItems(original, 42).Take(original.Count).ToList();
Enumerable.Range(0, items1.Count).Any(x => items1[x] != items2[x]).Should().BeTrue("Generated items should be different.");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestGenerateRandomItemsEqualSeeds()
{
var service = this.app.GetRandomService();
var original = Enumerable.Range(0, 1000).ToList();
var items1 = service.GetRandomItems(original, 42).Take(original.Count).ToList();
var items2 = service.GetRandomItems(original, 42).Take(original.Count).ToList();
Enumerable.Range(0, items1.Count).All(x => items1[x] == items2[x]).Should().BeTrue("Generated items should be the same.");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestGenerateUniqueItemsNullItems()
{
var service = this.app.GetRandomService();
Action action = () => service.GetUniqueItems<object>(null);
action.Should().Throw<ArgumentNullException>("items should not be null.");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestGenerateUniqueItemsEmptyItems()
{
var service = this.app.GetRandomService();
var generated = service.GetUniqueItems(Array.Empty<object>());
generated.Should().NotBeNull($"{nameof(service.GetUniqueItems)} should never return null.");
generated.Should().BeSameAs(Array.Empty<object>(), $"{nameof(service.GetUniqueItems)} should return an empty array.");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestGenerateUniqueItems()
{
var service = this.app.GetRandomService();
var original = Enumerable.Range(0, 1000).ToList();
var items = original.ToList();
var generated = service.GetUniqueItems(items).ToList();
items.Count.Should().Be(original.Count, "The collection size should not be modified.");
Enumerable.Range(0, original.Count).All(x => items[x] == original[x]).Should().BeTrue("All items should be in their original position.");
generated.Count.Should().Be(original.Count, "Maximum unique generated items should be the same as original count.");
Enumerable.Range(0, original.Count).Any(x => generated[x] != original[x]).Should().BeTrue("Some items should have been shuffled.");
generated.Sort();
items.Sort();
Enumerable.Range(0, original.Count).All(x => generated[x] == items[x]).Should().BeTrue("Generated collection should contain the original items.");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestGenerateUniqueItemsDifferentSeeds()
{
var service = this.app.GetRandomService();
var original = Enumerable.Range(0, 1000).ToList();
var items1 = service.GetUniqueItems(original, 23).ToList();
var items2 = service.GetUniqueItems(original, 42).ToList();
Enumerable.Range(0, items1.Count).Any(x => items1[x] != items2[x]).Should().BeTrue("Generated items should be different.");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestGenerateUniqueItemsEqualSeeds()
{
var service = this.app.GetRandomService();
var original = Enumerable.Range(0, 1000).ToList();
var items1 = service.GetUniqueItems(original, 42).ToList();
var items2 = service.GetUniqueItems(original, 42).ToList();
Enumerable.Range(0, items1.Count).All(x => items1[x] == items2[x]).Should().BeTrue("Generated items should be the same.");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestMultiThreadRandom()
{
var service = this.app.GetRandomService();
var lists = new List<List<int>>(Enumerable.Range(0, 32).Select(_ => new List<int>()));
Enumerable.Range(0, lists.Count)
.Select(x => lists[x])
.AsParallel()
.ForAll(x =>
{
var random = service.GetRandom();
for (var i = 0; i < 1000; i++)
{
x.Add(random.Next(0, int.MaxValue / 2));
}
});
for (var i = 0; i < lists.Count; i++)
{
var list = lists[i];
var last = list[^1];
var ok = false;
for (var j = 1; j <= 10; j++)
{
if (list[list.Count - 1 - j] != last)
{
ok = true;
break;
}
}
ok.Should().BeTrue($"{nameof(System.Random)} generation should be thread safe.");
}
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestShuffleNullItems()
{
var service = this.app.GetRandomService();
Action action = () => service.Shuffle<object>(null);
action.Should().Throw<ArgumentNullException>("items should not be null.");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestShuffleEmptyItems() => this.app.GetRandomService().Shuffle(Array.Empty<object>());
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestShuffle()
{
var service = this.app.GetRandomService();
var items = Enumerable.Range(0, 1000).ToList();
service.Shuffle(items);
Enumerable.Range(0, items.Count).Any(x => items[x] != x).Should().BeTrue("Some items should have been shuffled.");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestShuffleDifferentSeeds()
{
var service = this.app.GetRandomService();
var items1 = Enumerable.Range(0, 1000).ToList();
var items2 = Enumerable.Range(0, 1000).ToList();
service.Shuffle(items1, 23);
service.Shuffle(items2, 42);
Enumerable.Range(0, items1.Count).Any(x => items1[x] != items2[x]).Should().BeTrue("Shuffles should be different.");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestShuffleEqualSeeds()
{
var service = this.app.GetRandomService();
var items1 = Enumerable.Range(0, 1000).ToList();
var items2 = Enumerable.Range(0, 1000).ToList();
service.Shuffle(items1, 42);
service.Shuffle(items2, 42);
Enumerable.Range(0, items1.Count).All(x => items1[x] == items2[x]).Should().BeTrue("Both shuffles should be the same.");
}
[Fact, Trait(TestCategories.Category, TestCategories.Performance)]
public void TestPerformanceGetRandom() => TestUtils.TestPerformance(this.TestPerformanceGetRandomInternal);
[Fact, Trait(TestCategories.Category, TestCategories.Performance)]
public void TestPerformanceGetUniqueItems() => TestUtils.TestPerformance(this.TestPerformanceGetUniqueItemsInternal);
[Fact, Trait(TestCategories.Category, TestCategories.Performance)]
public void TestPerformanceShuffle() => TestUtils.TestPerformance(this.TestPerformanceShuffleInternal);
#endregion
#region Private methods
private void TestPerformanceGetRandomInternal()
{
var service = this.app.GetRandomService();
for (var i = 0; i < 1000000; i++)
{
service.GetRandom();
}
}
private void TestPerformanceGetUniqueItemsInternal()
{
var service = this.app.GetRandomService();
var items = Enumerable.Range(0, 100).ToList();
var sum = 0;
for (var i = 0; i < 30000; i++)
{
sum += service.GetUniqueItems(items).Take(10).Sum();
}
sum.Should().BePositive();
}
private void TestPerformanceShuffleInternal()
{
var service = this.app.GetRandomService();
var items = Enumerable.Range(0, 100).ToList();
for (var i = 0; i < 8000; i++)
{
service.Shuffle(items);
}
}
#endregion
}
| |
/*
* 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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenSim.Framework;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework.Monitoring
{
/// <summary>
/// Static class used to register/deregister/fetch statistics
/// </summary>
public static class StatsManager
{
// Subcommand used to list other stats.
public const string AllSubCommand = "all";
// Subcommand used to list other stats.
public const string ListSubCommand = "list";
// All subcommands
public static HashSet<string> SubCommands = new HashSet<string> { AllSubCommand, ListSubCommand };
/// <summary>
/// Registered stats categorized by category/container/shortname
/// </summary>
/// <remarks>
/// Do not add or remove directly from this dictionary.
/// </remarks>
public static SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Stat>>> RegisteredStats
= new SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Stat>>>();
// private static AssetStatsCollector assetStats;
// private static UserStatsCollector userStats;
// private static SimExtraStatsCollector simExtraStats = new SimExtraStatsCollector();
// public static AssetStatsCollector AssetStats { get { return assetStats; } }
// public static UserStatsCollector UserStats { get { return userStats; } }
public static SimExtraStatsCollector SimExtraStats { get; set; }
public static void RegisterConsoleCommands(ICommandConsole console)
{
console.Commands.AddCommand(
"General",
false,
"stats show",
"stats show [list|all|(<category>[.<container>])+",
"Show statistical information for this server",
"If no final argument is specified then legacy statistics information is currently shown.\n"
+ "'list' argument will show statistic categories.\n"
+ "'all' will show all statistics.\n"
+ "A <category> name will show statistics from that category.\n"
+ "A <category>.<container> name will show statistics from that category in that container.\n"
+ "More than one name can be given separated by spaces.\n"
+ "THIS STATS FACILITY IS EXPERIMENTAL AND DOES NOT YET CONTAIN ALL STATS",
HandleShowStatsCommand);
console.Commands.AddCommand(
"General",
false,
"show stats",
"show stats [list|all|(<category>[.<container>])+",
"Alias for 'stats show' command",
HandleShowStatsCommand);
StatsLogger.RegisterConsoleCommands(console);
}
public static void HandleShowStatsCommand(string module, string[] cmd)
{
ICommandConsole con = MainConsole.Instance;
if (cmd.Length > 2)
{
foreach (string name in cmd.Skip(2))
{
string[] components = name.Split('.');
string categoryName = components[0];
string containerName = components.Length > 1 ? components[1] : null;
string statName = components.Length > 2 ? components[2] : null;
if (categoryName == AllSubCommand)
{
OutputAllStatsToConsole(con);
}
else if (categoryName == ListSubCommand)
{
con.Output("Statistic categories available are:");
foreach (string category in RegisteredStats.Keys)
con.OutputFormat(" {0}", category);
}
else
{
SortedDictionary<string, SortedDictionary<string, Stat>> category;
if (!RegisteredStats.TryGetValue(categoryName, out category))
{
con.OutputFormat("No such category as {0}", categoryName);
}
else
{
if (String.IsNullOrEmpty(containerName))
{
OutputCategoryStatsToConsole(con, category);
}
else
{
SortedDictionary<string, Stat> container;
if (category.TryGetValue(containerName, out container))
{
if (String.IsNullOrEmpty(statName))
{
OutputContainerStatsToConsole(con, container);
}
else
{
Stat stat;
if (container.TryGetValue(statName, out stat))
{
OutputStatToConsole(con, stat);
}
else
{
con.OutputFormat(
"No such stat {0} in {1}.{2}", statName, categoryName, containerName);
}
}
}
else
{
con.OutputFormat("No such container {0} in category {1}", containerName, categoryName);
}
}
}
}
}
}
else
{
// Legacy
if (SimExtraStats != null)
con.Output(SimExtraStats.Report());
else
OutputAllStatsToConsole(con);
}
}
public static List<string> GetAllStatsReports()
{
List<string> reports = new List<string>();
foreach (var category in RegisteredStats.Values)
reports.AddRange(GetCategoryStatsReports(category));
return reports;
}
private static void OutputAllStatsToConsole(ICommandConsole con)
{
foreach (string report in GetAllStatsReports())
con.Output(report);
}
private static List<string> GetCategoryStatsReports(
SortedDictionary<string, SortedDictionary<string, Stat>> category)
{
List<string> reports = new List<string>();
foreach (var container in category.Values)
reports.AddRange(GetContainerStatsReports(container));
return reports;
}
private static void OutputCategoryStatsToConsole(
ICommandConsole con, SortedDictionary<string, SortedDictionary<string, Stat>> category)
{
foreach (string report in GetCategoryStatsReports(category))
con.Output(report);
}
private static List<string> GetContainerStatsReports(SortedDictionary<string, Stat> container)
{
List<string> reports = new List<string>();
foreach (Stat stat in container.Values)
reports.Add(stat.ToConsoleString());
return reports;
}
private static void OutputContainerStatsToConsole(
ICommandConsole con, SortedDictionary<string, Stat> container)
{
foreach (string report in GetContainerStatsReports(container))
con.Output(report);
}
private static void OutputStatToConsole(ICommandConsole con, Stat stat)
{
con.Output(stat.ToConsoleString());
}
// Creates an OSDMap of the format:
// { categoryName: {
// containerName: {
// statName: {
// "Name": name,
// "ShortName": shortName,
// ...
// },
// statName: {
// "Name": name,
// "ShortName": shortName,
// ...
// },
// ...
// },
// containerName: {
// ...
// },
// ...
// },
// categoryName: {
// ...
// },
// ...
// }
// The passed in parameters will filter the categories, containers and stats returned. If any of the
// parameters are either EmptyOrNull or the AllSubCommand value, all of that type will be returned.
// Case matters.
public static OSDMap GetStatsAsOSDMap(string pCategoryName, string pContainerName, string pStatName)
{
OSDMap map = new OSDMap();
foreach (string catName in RegisteredStats.Keys)
{
// Do this category if null spec, "all" subcommand or category name matches passed parameter.
// Skip category if none of the above.
if (!(String.IsNullOrEmpty(pCategoryName) || pCategoryName == AllSubCommand || pCategoryName == catName))
continue;
OSDMap contMap = new OSDMap();
foreach (string contName in RegisteredStats[catName].Keys)
{
if (!(string.IsNullOrEmpty(pContainerName) || pContainerName == AllSubCommand || pContainerName == contName))
continue;
OSDMap statMap = new OSDMap();
SortedDictionary<string, Stat> theStats = RegisteredStats[catName][contName];
foreach (string statName in theStats.Keys)
{
if (!(String.IsNullOrEmpty(pStatName) || pStatName == AllSubCommand || pStatName == statName))
continue;
statMap.Add(statName, theStats[statName].ToOSDMap());
}
contMap.Add(contName, statMap);
}
map.Add(catName, contMap);
}
return map;
}
public static Hashtable HandleStatsRequest(Hashtable request)
{
Hashtable responsedata = new Hashtable();
// string regpath = request["uri"].ToString();
int response_code = 200;
string contenttype = "text/json";
string pCategoryName = StatsManager.AllSubCommand;
string pContainerName = StatsManager.AllSubCommand;
string pStatName = StatsManager.AllSubCommand;
if (request.ContainsKey("cat")) pCategoryName = request["cat"].ToString();
if (request.ContainsKey("cont")) pContainerName = request["cat"].ToString();
if (request.ContainsKey("stat")) pStatName = request["cat"].ToString();
string strOut = StatsManager.GetStatsAsOSDMap(pCategoryName, pContainerName, pStatName).ToString();
// If requestor wants it as a callback function, build response as a function rather than just the JSON string.
if (request.ContainsKey("callback"))
{
strOut = request["callback"].ToString() + "(" + strOut + ");";
}
// m_log.DebugFormat("{0} StatFetch: uri={1}, cat={2}, cont={3}, stat={4}, resp={5}",
// LogHeader, regpath, pCategoryName, pContainerName, pStatName, strOut);
responsedata["int_response_code"] = response_code;
responsedata["content_type"] = contenttype;
responsedata["keepalive"] = false;
responsedata["str_response_string"] = strOut;
responsedata["access_control_allow_origin"] = "*";
return responsedata;
}
// /// <summary>
// /// Start collecting statistics related to assets.
// /// Should only be called once.
// /// </summary>
// public static AssetStatsCollector StartCollectingAssetStats()
// {
// assetStats = new AssetStatsCollector();
//
// return assetStats;
// }
//
// /// <summary>
// /// Start collecting statistics related to users.
// /// Should only be called once.
// /// </summary>
// public static UserStatsCollector StartCollectingUserStats()
// {
// userStats = new UserStatsCollector();
//
// return userStats;
// }
/// <summary>
/// Register a statistic.
/// </summary>
/// <param name='stat'></param>
/// <returns></returns>
public static bool RegisterStat(Stat stat)
{
SortedDictionary<string, SortedDictionary<string, Stat>> category = null, newCategory;
SortedDictionary<string, Stat> container = null, newContainer;
lock (RegisteredStats)
{
// Stat name is not unique across category/container/shortname key.
// XXX: For now just return false. This is to avoid problems in regression tests where all tests
// in a class are run in the same instance of the VM.
if (TryGetStatParents(stat, out category, out container))
return false;
// We take a copy-on-write approach here of replacing dictionaries when keys are added or removed.
// This means that we don't need to lock or copy them on iteration, which will be a much more
// common operation after startup.
if (container != null)
newContainer = new SortedDictionary<string, Stat>(container);
else
newContainer = new SortedDictionary<string, Stat>();
if (category != null)
newCategory = new SortedDictionary<string, SortedDictionary<string, Stat>>(category);
else
newCategory = new SortedDictionary<string, SortedDictionary<string, Stat>>();
newContainer[stat.ShortName] = stat;
newCategory[stat.Container] = newContainer;
RegisteredStats[stat.Category] = newCategory;
}
return true;
}
/// <summary>
/// Deregister a statistic
/// </summary>>
/// <param name='stat'></param>
/// <returns></returns>
public static bool DeregisterStat(Stat stat)
{
SortedDictionary<string, SortedDictionary<string, Stat>> category = null, newCategory;
SortedDictionary<string, Stat> container = null, newContainer;
lock (RegisteredStats)
{
if (!TryGetStatParents(stat, out category, out container))
return false;
newContainer = new SortedDictionary<string, Stat>(container);
newContainer.Remove(stat.ShortName);
newCategory = new SortedDictionary<string, SortedDictionary<string, Stat>>(category);
newCategory.Remove(stat.Container);
newCategory[stat.Container] = newContainer;
RegisteredStats[stat.Category] = newCategory;
return true;
}
}
public static bool TryGetStat(string category, string container, string statShortName, out Stat stat)
{
stat = null;
SortedDictionary<string, SortedDictionary<string, Stat>> categoryStats;
lock (RegisteredStats)
{
if (!TryGetStatsForCategory(category, out categoryStats))
return false;
SortedDictionary<string, Stat> containerStats;
if (!categoryStats.TryGetValue(container, out containerStats))
return false;
return containerStats.TryGetValue(statShortName, out stat);
}
}
public static bool TryGetStatsForCategory(
string category, out SortedDictionary<string, SortedDictionary<string, Stat>> stats)
{
lock (RegisteredStats)
return RegisteredStats.TryGetValue(category, out stats);
}
/// <summary>
/// Get the same stat for each container in a given category.
/// </summary>
/// <returns>
/// The stats if there were any to fetch. Otherwise null.
/// </returns>
/// <param name='category'></param>
/// <param name='statShortName'></param>
public static List<Stat> GetStatsFromEachContainer(string category, string statShortName)
{
SortedDictionary<string, SortedDictionary<string, Stat>> categoryStats;
lock (RegisteredStats)
{
if (!RegisteredStats.TryGetValue(category, out categoryStats))
return null;
List<Stat> stats = null;
foreach (SortedDictionary<string, Stat> containerStats in categoryStats.Values)
{
if (containerStats.ContainsKey(statShortName))
{
if (stats == null)
stats = new List<Stat>();
stats.Add(containerStats[statShortName]);
}
}
return stats;
}
}
public static bool TryGetStatParents(
Stat stat,
out SortedDictionary<string, SortedDictionary<string, Stat>> category,
out SortedDictionary<string, Stat> container)
{
category = null;
container = null;
lock (RegisteredStats)
{
if (RegisteredStats.TryGetValue(stat.Category, out category))
{
if (category.TryGetValue(stat.Container, out container))
{
if (container.ContainsKey(stat.ShortName))
return true;
}
}
}
return false;
}
public static void RecordStats()
{
lock (RegisteredStats)
{
foreach (SortedDictionary<string, SortedDictionary<string, Stat>> category in RegisteredStats.Values)
{
foreach (SortedDictionary<string, Stat> container in category.Values)
{
foreach (Stat stat in container.Values)
{
if (stat.MeasuresOfInterest != MeasuresOfInterest.None)
stat.RecordValue();
}
}
}
}
}
}
/// <summary>
/// Stat type.
/// </summary>
/// <remarks>
/// A push stat is one which is continually updated and so it's value can simply by read.
/// A pull stat is one where reading the value triggers a collection method - the stat is not continually updated.
/// </remarks>
public enum StatType
{
Push,
Pull
}
/// <summary>
/// Measures of interest for this stat.
/// </summary>
[Flags]
public enum MeasuresOfInterest
{
None,
AverageChangeOverTime
}
/// <summary>
/// Verbosity of stat.
/// </summary>
/// <remarks>
/// Info will always be displayed.
/// </remarks>
public enum StatVerbosity
{
Debug,
Info
}
}
| |
using System;
using MonoTouch.Foundation;
namespace AmazonInsights {
[Model, BaseType (typeof (NSObject))]
public partial interface AIVariation {
[Export ("projectName")]
string ProjectName { get; }
[Export ("name")]
string Name { get; }
[Export ("variableAsInt:withDefault:")]
int VariableAsInt (string variableName, int defaultValue);
[Export ("variableAsLongLong:withDefault:")]
long VariableAsLongLong (string variableName, long defaultValue);
[Export ("variableAsFloat:withDefault:")]
float VariableAsFloat (string variableName, float defaultValue);
[Export ("variableAsDouble:withDefault:")]
double VariableAsDouble (string variableName, double defaultValue);
[Export ("variableAsBool:withDefault:")]
bool VariableAsBool (string variableName, bool defaultValue);
[Export ("variableAsString:withDefault:")]
string VariableAsString (string variableName, string defaultValue);
[Export ("containsVariable:")]
bool ContainsVariable (string variableName);
}
[Model, BaseType (typeof (NSObject))]
public partial interface AIVariationSet { // : NSFastEnumeration {
[Export ("variationForProjectName:")]
AIVariation VariationForProjectName (string projectName);
[Export ("containsVariation:")]
bool ContainsVariation (string projectName);
[Export ("count")]
uint Count { get; }
[Field ("AIABTestClientErrorDomain")]
NSString AIABTestClientErrorDomain { get; }
}
public enum AIABTestClientErrorCodes {
NoProjectNamesProvided = 0,
ProjectNamesNil
}
public enum ABTestClientErrorCode {
NoProjectNamesProvided = 0,
ProjectNamesNil
}
public delegate void AICompletionHandler(AIVariationSet variationSet, NSError error);
[Model, BaseType (typeof (NSObject))]
public partial interface AIABTestClient {
[Export ("variationsByProjectNames:withCompletionHandler:")]
void VariationsByProjectNames (string[] theProjectNames, AICompletionHandler completionHandler);
}
[Model, BaseType (typeof (NSObject))]
public partial interface AIInsightsCredentials {
[Export ("applicationKey")]
string ApplicationKey { get; }
[Export ("privateKey")]
string PrivateKey { get; }
}
[Model, BaseType (typeof (NSObject))]
public partial interface AIInsightsOptions {
[Export ("allowEventCollection")]
bool AllowEventCollection { get; }
[Export ("allowWANDelivery")]
bool AllowWANDelivery { get; }
}
[Model, BaseType (typeof (NSObject))]
public partial interface AIEvent {
[Export ("eventType")]
string EventType { get; }
[Export ("addAttribute:forKey:")]
void AddAttribute (string theValue, string theKey);
[Export ("addMetric:forKey:")]
void AddMetric (NSNumber theValue, string theKey);
[Export ("attributeForKey:")]
string AttributeForKey (string theKey);
[Export ("metricForKey:")]
NSNumber MetricForKey (string theKey);
[Export ("hasAttributeForKey:")]
bool HasAttributeForKey (string theKey);
[Export ("hasMetricForKey:")]
bool HasMetricForKey (string theKey);
[Export ("allAttributes")]
NSDictionary AllAttributes { get; }
[Export ("allMetrics")]
NSDictionary AllMetrics { get; }
}
[Model, BaseType (typeof (NSObject))]
public partial interface AIEventClient {
[Export ("addGlobalAttribute:forKey:")]
void AddGlobalAttribute (string theValue, string theKey);
[Export ("addGlobalAttribute:forKey:forEventType:")]
void AddGlobalAttribute (string theValue, string theKey, string theEventType);
[Export ("addGlobalMetric:forKey:")]
void AddGlobalMetric (NSNumber theValue, string theKey);
[Export ("addGlobalMetric:forKey:forEventType:")]
void AddGlobalMetric (NSNumber theValue, string theKey, string theEventType);
[Export ("removeGlobalAttributeForKey:")]
void RemoveGlobalAttributeForKey (string theKey);
[Export ("removeGlobalAttributeForKey:forEventType:")]
void RemoveGlobalAttributeForKey (string theKey, string theEventType);
[Export ("removeGlobalMetricForKey:")]
void RemoveGlobalMetricForKey (string theKey);
[Export ("removeGlobalMetricForKey:forEventType:")]
void RemoveGlobalMetricForKey (string theKey, string theEventType);
[Export ("recordEvent:")]
void RecordEvent (AIEvent theEvent);
[Export ("createEventWithEventType:")]
AIEvent CreateEventWithEventType (string theEventType);
[Export ("submitEvents")]
void SubmitEvents ();
}
[Model, BaseType (typeof (NSObject))]
public partial interface AIUserProfile {
[Export ("dimensions")]
NSDictionary Dimensions { get; }
[Export ("addDimensionAsNumber:forName:")]
AIUserProfile AddDimensionAsNumber (NSNumber theValue, string theName);
[Export ("addDimensionAsString:forName:")]
AIUserProfile AddDimensionAsString (string theValue, string theName);
}
public delegate void AIInitializationCompletionBlock (AIAmazonInsights insights);
[BaseType (typeof (NSObject))]
public partial interface AIAmazonInsights {
[Export ("abTestClient")]
AIABTestClient AbTestClient { get; }
[Export ("eventClient")]
AIEventClient EventClient { get; }
[Export ("userProfile")]
AIUserProfile UserProfile { get; }
[Static, Export ("credentialsWithApplicationKey:withPrivateKey:")]
AIInsightsCredentials CredentialsWithApplicationKey (string theApplicationKey, string thePrivateKey);
[Static, Export ("defaultOptions")]
AIInsightsOptions DefaultOptions { get; }
[Static, Export ("optionsWithAllowEventCollection:withAllowWANDelivery:")]
AIInsightsOptions OptionsWithAllowEventCollection (bool allowEventCollection, bool allowWANDelivery);
[Static, Export ("insightsWithCredentials:")]
AIAmazonInsights InsightsWithCredentials (AIInsightsCredentials theCredentials);
[Static, Export ("insightsWithCredentials:withOptions:")]
AIAmazonInsights InsightsWithCredentials (AIInsightsCredentials theCredentials, AIInsightsOptions theOptions);
[Static, Export ("insightsWithCredentials:withOptions:withCompletionBlock:")]
AIAmazonInsights InsightsWithCredentials (AIInsightsCredentials theCredentials, AIInsightsOptions theOptions, AIInitializationCompletionBlock completionBlock);
}
[BaseType (typeof (NSObject))]
public partial interface AIMonetizationEventBuilder {
[Export ("build")]
AIEvent Build { get; }
[Export ("isValid")]
bool IsValid { get; }
[Export ("initWithEventClient:")]
IntPtr Constructor (AIEventClient theEventClient);
[Export ("productId")]
string ProductId { get; set; }
[Export ("quantity")]
int Quantity { get; set; }
[Export ("itemPrice")]
double ItemPrice { get; set; }
[Export ("formattedItemPrice")]
string FormattedItemPrice { get; set; }
[Export ("transactionId")]
string TransactionId { get; set; }
[Export ("currency")]
string Currency { get; set; }
[Export ("store")]
string Store { get; set; }
}
[BaseType (typeof (AIMonetizationEventBuilder))]
public partial interface AIAppleMonetizationEventBuilder {
[Static, Export ("builderWithEventClient:")]
AIAppleMonetizationEventBuilder BuilderWithEventClient (AIEventClient theEventClient);
[Export ("withProductId:")]
void WithProductId (string theProductId);
[Export ("withItemPrice:andPriceLocale:")]
void WithItemPrice (double theItemPrice, NSLocale thePriceLocale);
[Export ("withQuantity:")]
void WithQuantity (int theQuantity);
[Export ("withTransactionId:")]
void WithTransactionId (string theTransactionId);
}
[BaseType (typeof (AIMonetizationEventBuilder))]
public partial interface AIVirtualMonetizationEventBuilder {
[Static, Export ("builderWithEventClient:")]
AIVirtualMonetizationEventBuilder BuilderWithEventClient (AIEventClient theEventClient);
[Export ("withProductId:")]
void WithProductId (string theProductId);
[Export ("withItemPrice:")]
void WithItemPrice (double theItemPrice);
[Export ("withQuantity:")]
void WithQuantity (int theQuantity);
[Export ("withCurrency:")]
void WithCurrency (string theCurrency);
}
}
| |
/* 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:
*
* * 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.
*
* 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.Drawing;
using System.Windows.Forms;
using XenAPI;
using XenAdmin.Actions;
using XenAdmin.Network;
using XenAdmin.Core;
namespace XenAdmin.Dialogs
{
public partial class RoleElevationDialog : XenDialogBase
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public Session elevatedSession = null;
public string elevatedPassword;
public string elevatedUsername;
public string originalUsername;
public string originalPassword;
private List<Role> authorizedRoles;
/// <summary>
/// Displays a dialog informing the user they need a different role to complete the task, and offers the chance to switch user. Optionally logs
/// out the elevated session. If successful exposes the elevated session, password and username as fields.
/// </summary>
/// <param name="connection">The current server connection with the role information</param>
/// <param name="session">The session on which we have been denied access</param>
/// <param name="authorizedRoles">A list of roles that are able to complete the task</param>
/// <param name="actionTitle">A description of the current action, if null or empty will not be displayed</param>
public RoleElevationDialog(IXenConnection connection, Session session, List<Role> authorizedRoles, string actionTitle)
{
InitializeComponent();
Image icon = SystemIcons.Exclamation.ToBitmap();
pictureBox1.Image = icon;
pictureBox1.Width = icon.Width;
pictureBox1.Height = icon.Height;
this.connection = connection;
UserDetails ud = session.CurrentUserDetails;
labelCurrentUserValue.Text = ud.UserDisplayName ?? ud.UserName ?? Messages.UNKNOWN_AD_USER;
labelCurrentRoleValue.Text = Role.FriendlyCSVRoleList(session.Roles);
authorizedRoles.Sort((r1, r2) => r2.CompareTo(r1));
labelRequiredRoleValue.Text = Role.FriendlyCSVRoleList(authorizedRoles);
labelServerValue.Text = Helpers.GetName(connection);
labelServer.Text = Helpers.IsPool(connection) ? Messages.POOL_COLON : Messages.SERVER_COLON;
originalUsername = session.Connection.Username;
originalPassword = session.Connection.Password;
if (string.IsNullOrEmpty(actionTitle))
{
labelCurrentAction.Visible = false;
labelCurrentActionValue.Visible = false;
}
else
{
labelCurrentActionValue.Text = actionTitle;
}
this.authorizedRoles = authorizedRoles;
}
private void buttonAuthorize_Click(object sender, EventArgs e)
{
try
{
Exception delegateException = null;
log.Debug("Testing logging in with the new credentials");
DelegatedAsyncAction loginAction = new DelegatedAsyncAction(connection,
Messages.AUTHORIZING_USER,
Messages.CREDENTIALS_CHECKING,
Messages.CREDENTIALS_CHECK_COMPLETE,
delegate
{
try
{
elevatedSession = connection.ElevatedSession(TextBoxUsername.Text.Trim(), TextBoxPassword.Text);
}
catch (Exception ex)
{
delegateException = ex;
}
});
new ActionProgressDialog(loginAction, ProgressBarStyle.Marquee, false).ShowDialog(this);
// The exception would have been handled by the action progress dialog, just return the user to the sudo dialog
if (loginAction.Exception != null)
return;
if(HandledAnyDelegateException(delegateException))
return;
if (elevatedSession.IsLocalSuperuser || SessionAuthorized(elevatedSession))
{
elevatedUsername = TextBoxUsername.Text.Trim();
elevatedPassword = TextBoxPassword.Text;
DialogResult = DialogResult.OK;
Close();
return;
}
ShowNotAuthorisedDialog();
return;
}
catch (Exception ex)
{
log.DebugFormat("Exception when attempting to sudo action: {0} ", ex);
new ThreeButtonDialog(
new ThreeButtonDialog.Details(
SystemIcons.Error,
String.Format(Messages.USER_AUTHORIZATION_FAILED, TextBoxUsername.Text),
Messages.XENCENTER)).ShowDialog(Parent);
}
finally
{
// Check whether we have a successful elevated session and whether we have been asked to log it out
// If non successful (most likely the new subject is not authorized) then log it out anyway.
if (elevatedSession != null && DialogResult != DialogResult.OK)
{
elevatedSession.Connection.Logout(elevatedSession);
elevatedSession = null;
}
}
}
private bool HandledAnyDelegateException(Exception delegateException)
{
if (delegateException != null)
{
Failure f = delegateException as Failure;
if (f != null && f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED)
{
ShowNotAuthorisedDialog();
return true;
}
throw delegateException;
}
return false;
}
private void ShowNotAuthorisedDialog()
{
new ThreeButtonDialog(
new ThreeButtonDialog.Details(
SystemIcons.Error,
Messages.USER_NOT_AUTHORIZED,
Messages.PERMISSION_DENIED)).ShowDialog(this);
}
private bool SessionAuthorized(Session s)
{
UserDetails ud = s.CurrentUserDetails;
foreach (Role r in s.Roles)
{
if (authorizedRoles.Contains(r))
{
log.DebugFormat("Subject '{0}' is authorized to complete the action", ud.UserDisplayName ?? ud.UserName ?? ud.UserSid);
return true;
}
}
log.DebugFormat("Subject '{0}' is not authorized to complete the action", ud.UserDisplayName ?? ud.UserName ?? ud.UserSid);
return false;
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void UpdateButtons()
{
buttonAuthorize.Enabled = TextBoxUsername.Text.Trim() != "" && TextBoxPassword.Text != "";
}
private void TextBoxUsername_TextChanged(object sender, EventArgs e)
{
UpdateButtons();
}
private void TextBoxPassword_TextChanged(object sender, EventArgs e)
{
UpdateButtons();
}
}
}
| |
// 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 Internal.Interop;
using Internal.Threading.Tasks;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
using System.Runtime.WindowsRuntime.Internal;
using System.Threading;
using Windows.Foundation;
namespace System.Threading.Tasks
{
/// <summary>Provides a bridge between IAsyncOperation* and Task.</summary>
/// <typeparam name="TResult">Specifies the type of the result of the asynchronous operation.</typeparam>
/// <typeparam name="TProgress">Specifies the type of progress notification data.</typeparam>
internal sealed class AsyncInfoToTaskBridge<TResult> : TaskCompletionSource<TResult>
{
/// <summary>The CancellationToken associated with this operation.</summary>
private readonly CancellationToken _ct;
/// <summary>A registration for cancellation that needs to be disposed of when the operation completes.</summary>
private CancellationTokenRegistration _ctr;
/// <summary>A flag set to true as soon as the completion callback begins to execute.</summary>
private bool _completing;
internal AsyncInfoToTaskBridge(CancellationToken cancellationToken)
{
if (AsyncCausalitySupport.LoggingOn)
AsyncCausalitySupport.TraceOperationCreation(this.Task, "WinRT Operation as Task");
AsyncCausalitySupport.AddToActiveTasks(this.Task);
_ct = cancellationToken;
}
/// <summary>The synchronization object to use for protecting the state of this bridge.</summary>
private object StateLock
{
get { return this; } // "this" isn't available publicly, so we can safely use it as a syncobj
}
/// <summary>Registers the async operation for cancellation.</summary>
/// <param name="asyncInfo">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
internal void RegisterForCancellation(IAsyncInfo asyncInfo)
{
Contract.Requires(asyncInfo != null);
try
{
if (_ct.CanBeCanceled && !_completing)
{ // benign race on m_completing... it's ok if it's not up-to-date.
var ctr = _ct.Register(ai => ((IAsyncInfo)ai).Cancel(), asyncInfo); // delegate cached by compiler
// The operation may already be completing by this time, in which case
// we might need to dispose of our new cancellation registration here.
bool disposeOfCtr = false;
lock (StateLock)
{
if (_completing) disposeOfCtr = true;
else _ctr = ctr; // under lock to avoid torn writes
}
if (disposeOfCtr)
ctr.TryDeregister();
}
}
catch (Exception ex)
{
// We do not want exceptions propagating out of the AsTask / GetAwaiter calls, as the
// Completed handler will instead store the exception into the returned Task.
// Such exceptions should cause the Completed handler to be invoked synchronously and thus the Task should already be completed.
if (!base.Task.IsFaulted)
{
Debug.Assert(false, String.Format("Expected base task to already be faulted but found it in state {0}", base.Task.Status));
base.TrySetException(ex);
}
}
}
/// <summary>Bridge to Completed handler on IAsyncAction.</summary>
internal void CompleteFromAsyncAction(IAsyncAction asyncInfo, AsyncStatus asyncStatus)
{
Complete(asyncInfo, null, asyncStatus);
}
/// <summary>Bridge to Completed handler on IAsyncActionWithProgress{TProgress}.</summary>
internal void CompleteFromAsyncActionWithProgress<TProgress>(IAsyncActionWithProgress<TProgress> asyncInfo, AsyncStatus asyncStatus)
{
Complete(asyncInfo, null, asyncStatus);
}
/// <summary>Bridge to Completed handler on IAsyncOperation{TResult}.</summary>
internal void CompleteFromAsyncOperation(IAsyncOperation<TResult> asyncInfo, AsyncStatus asyncStatus)
{
Complete(asyncInfo, ai => ((IAsyncOperation<TResult>)ai).GetResults(), asyncStatus); // delegate cached by compiler
}
/// <summary>Bridge to Completed handler on IAsyncOperationWithProgress{TResult,TProgress}.</summary>
internal void CompleteFromAsyncOperationWithProgress<TProgress>(IAsyncOperationWithProgress<TResult, TProgress> asyncInfo, AsyncStatus asyncStatus)
{
// delegate cached by compiler:
Complete(asyncInfo, ai => ((IAsyncOperationWithProgress<TResult, TProgress>)ai).GetResults(), asyncStatus);
}
/// <summary>Completes the task from the completed asynchronous operation.</summary>
/// <param name="asyncInfo">The asynchronous operation.</param>
/// <param name="getResultsFunction">A function used to retrieve the TResult from the async operation; may be null.</param>
/// <param name="asyncStatus">The status of the asynchronous operation.</param>
private void Complete(IAsyncInfo asyncInfo, Func<IAsyncInfo, TResult> getResultsFunction, AsyncStatus asyncStatus)
{
if (asyncInfo == null)
throw new ArgumentNullException(nameof(asyncInfo));
Contract.EndContractBlock();
AsyncCausalitySupport.RemoveFromActiveTasks(this.Task);
try
{
Debug.Assert(asyncInfo.Status == asyncStatus,
"asyncInfo.Status does not match asyncStatus; are we dealing with a faulty IAsyncInfo implementation?");
// Assuming a correct underlying implementation, the task should not have been
// completed yet. If it is completed, we shouldn't try to do any further work
// with the operation or the task, as something is horked.
bool taskAlreadyCompleted = Task.IsCompleted;
Debug.Assert(!taskAlreadyCompleted, "Expected the task to not yet be completed.");
if (taskAlreadyCompleted)
throw new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion);
// Clean up our registration with the cancellation token, noting that we're now in the process of cleaning up.
CancellationTokenRegistration ctr;
lock (StateLock)
{
_completing = true;
ctr = _ctr; // under lock to avoid torn reads
_ctr = default(CancellationTokenRegistration);
}
ctr.TryDeregister(); // It's ok if we end up unregistering a not-initialized registration; it'll just be a nop.
try
{
// Find out how the async operation completed. It must be in a terminal state.
bool terminalState = asyncStatus == AsyncStatus.Completed
|| asyncStatus == AsyncStatus.Canceled
|| asyncStatus == AsyncStatus.Error;
Debug.Assert(terminalState, "The async operation should be in a terminal state.");
if (!terminalState)
throw new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion);
// Retrieve the completion data from the IAsyncInfo.
TResult result = default(TResult);
Exception error = null;
if (asyncStatus == AsyncStatus.Error)
{
error = asyncInfo.ErrorCode;
// Defend against a faulty IAsyncInfo implementation:
if (error == null)
{
Debug.Assert(false, "IAsyncInfo.Status == Error, but ErrorCode returns a null Exception (implying S_OK).");
error = new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion);
}
else
{
error = asyncInfo.ErrorCode.AttachRestrictedErrorInfo();
}
}
else if (asyncStatus == AsyncStatus.Completed && getResultsFunction != null)
{
try
{
result = getResultsFunction(asyncInfo);
}
catch (Exception resultsEx)
{
// According to the WinRT team, this can happen in some egde cases, such as marshalling errors in GetResults.
error = resultsEx;
asyncStatus = AsyncStatus.Error;
}
}
// Nothing to retrieve for a canceled operation or for a completed operation with no result.
// Complete the task based on the previously retrieved results:
bool success = false;
switch (asyncStatus)
{
case AsyncStatus.Completed:
if (AsyncCausalitySupport.LoggingOn)
AsyncCausalitySupport.TraceOperationCompletedSuccess(this.Task);
success = base.TrySetResult(result);
break;
case AsyncStatus.Error:
Debug.Assert(error != null, "The error should have been retrieved previously.");
success = base.TrySetException(error);
break;
case AsyncStatus.Canceled:
success = base.TrySetCanceled(_ct.IsCancellationRequested ? _ct : new CancellationToken(true));
break;
}
Debug.Assert(success, "Expected the outcome to be successfully transfered to the task.");
}
catch (Exception exc)
{
// This really shouldn't happen, but could in a variety of misuse cases
// such as a faulty underlying IAsyncInfo implementation.
Debug.Assert(false, string.Format("Unexpected exception in Complete: {0}", exc.ToString()));
if (AsyncCausalitySupport.LoggingOn)
AsyncCausalitySupport.TraceOperationCompletedError(this.Task);
// For these cases, store the exception into the task so that it makes its way
// back to the caller. Only if something went horribly wrong and we can't store the exception
// do we allow it to be propagated out to the invoker of the Completed handler.
if (!base.TrySetException(exc))
{
Debug.Assert(false, "The task was already completed and thus the exception couldn't be stored.");
throw;
}
}
}
finally
{
// We may be called on an STA thread which we don't own, so make sure that the RCW is released right
// away. Otherwise, if we leave it up to the finalizer, the apartment may already be gone.
if (Marshal.IsComObject(asyncInfo))
Marshal.ReleaseComObject(asyncInfo);
}
} // private void Complete(..)
} // class AsyncInfoToTaskBridge<TResult, TProgress>
} // namespace
| |
//-----------------------------------------------------------------------------
//Cortex
//Copyright (c) 2010-2015, Joshua Scoggins
//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 Cortex 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 Joshua Scoggins 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.Reflection;
using System.Text;
using System.Runtime;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Cortex;
using Cortex.LexicalAnalysis;
using Cortex.Parsing;
using Cortex.Grammar;
using Cortex.Symbolic;
using System.Diagnostics;
using System.Windows.Forms;
using System.Drawing;
namespace Cortex.Filter
{
public class FormConstructionLanguage
{
private static object[] EmptyArray = new object[0];
private Stack<object> dataStack;
private object Push(object input)
{
dataStack.Push(input);
return EmptyArray;
}
private EnhancedLR1ParsableLanguage language;
public FormConstructionLanguage()
{
dataStack = new Stack<object>();
EnhancedGrammar grammar = new EnhancedGrammar
{
new Rule("S'")
{
new Production { "Block" },
},
new Rule("Block")
{
new Production { "Rest", "return" },
},
new Rule("Rest")
{
new Production { "BlockStatements", },
},
new Rule("BlockStatements" )
{
new Production{ "BlockStatements", "BlockStatement" },
new Production{ "BlockStatement" },
},
new Rule("BlockStatement")
{
new Production { "Word" },
},
new Rule("Word")
{
new Production { "Action" },
new Production { "Type" },
},
new Rule("Type")
{
new Production((x) => { Push(int.Parse(x[0].ToString())); return EmptyArray; }) { "int" },
new Production((x) => { Push(long.Parse(x[0].ToString())); return EmptyArray; }) { "long" },
new Production((x) => { Push(float.Parse(x[0].ToString())); return EmptyArray; }) { "float" },
new Production((x) => { Push(double.Parse(x[0].ToString())); return EmptyArray; }) { "double" },
new Production((x) => { Push(x[0].ToString().Replace("\"",string.Empty)); return EmptyArray; }) { "string-literal" },
new Production((x) => { Push(x[0].ToString().Replace("\"",string.Empty)); return EmptyArray; }) { "id" },
new Production((x) => { Push(true); return EmptyArray; }) { "true" },
new Production((x) => { Push(false); return EmptyArray; }) { "false" },
},
new Rule("Action")
{
new Production(NewItem) { "new" },
new Production(ImbueItem) { "imbue" },
new Production(NewPoint) { "point" },
new Production(NewSize) { "size" },
},
};
language = new EnhancedLR1ParsableLanguage(
"Dynamic Form Constructor Language",
"1.0.0.0",
IdSymbol.DEFAULT_IDENTIFIER,
new Comment[]
{
new Comment("single-line-comment", "--", "\n", "\""),
},
new Symbol[]
{
new Symbol('\n', "Newline", "<new-line>"),
new Symbol(' ', "Space", "<space>" ),
new Symbol('\t', "Tab", "<tab>"),
new Symbol('\r', "Carriage Return", "<cr>"),
},
new RegexSymbol[]
{
new StringLiteral(),
new CharacterSymbol(),
new GenericFloatingPointNumber("Single Precision Floating Point Number", "[fF]", "single"),
new GenericFloatingPointNumber("Double Precision Floating Point Number", "double"),
new GenericInteger("Long", "[Ll]", "long"),
new GenericInteger("Int", "int"),
},
new Keyword[]
{
new Keyword("new"),
new Keyword("imbue"),
new Keyword("point"),
new Keyword("size"),
new Keyword("extract"),
new Keyword("true"),
new Keyword("false"),
new Keyword("return"),
},
LexicalExtensions.DefaultTypedStringSelector,
grammar,
"$",
(x) =>
{
object result = dataStack.Pop();
if(result is DynamicForm)
{
DynamicForm d = (DynamicForm)result;
d.ResumeLayout(false);
return d;
}
else
{
throw new ArgumentException("A form should always be returned from any of these scripts!");
}
},
true,
IsValid);
}
public DynamicForm ConstructForm(string input)
{
dataStack = new Stack<object>();
return (DynamicForm)language.Parse(input);
}
private object NewPoint(object[] input)
{
int y = (int)dataStack.Pop();
int x = (int)dataStack.Pop();
dataStack.Push(new Point(x,y));
return EmptyArray;
}
private object NewSize(object[] input)
{
int y = (int)dataStack.Pop();
int x = (int)dataStack.Pop();
dataStack.Push(new Size(x,y));
return EmptyArray;
}
private object ImbueItem(object[] input)
{
//takes in an object and a corresponding item to imbue it into
string name = (string)dataStack.Pop();
object data = dataStack.Pop();
Control target = (Control)dataStack.Pop();
switch(name.Replace("\"",string.Empty))
{
case "Location":
target.Location = (Point)data;
break;
case "Size":
target.Size = (Size)data;
break;
case "Name":
target.Name = (string)data;
break;
case "Visible":
target.Visible = (bool)data;
break;
case "Text":
target.Text = (string)data;
break;
case "Controls.Add":
Control c = (Control)data;
if(c is Button)
{
DynamicForm t = (DynamicForm)target;
t.ButtonOpensFileDialog((Button)c, true);
}
else
{
target.Controls.Add(c);
}
if(!(c is Label) && target is DynamicForm)
((DynamicForm)target).StorageCells[c.Name] = null;
break;
case "Items.Add":
ComboBox cmbo = (ComboBox)target;
cmbo.Items.Add(data.ToString());
break;
default:
throw new ArgumentException(
string.Format("Unknown Data Element: {0}", name));
}
dataStack.Push(target);
return EmptyArray;
}
private object NewItem(object[] input)
{
//ignore the contents
//this should be an id or string
string str = dataStack.Pop().ToString();
switch(str)
{
case "form":
DynamicForm d = new DynamicForm();
d.SuspendLayout();
dataStack.Push(d);
break;
case "label":
dataStack.Push(new Label());
break;
case "combobox":
dataStack.Push(new ComboBox());
break;
case "textbox":
dataStack.Push(new TextBox());
break;
case "button":
dataStack.Push(new Button());
break;
case "checkbox":
dataStack.Push(new CheckBox());
break;
default:
throw new ArgumentException("Unknown type given");
}
return EmptyArray;
}
public bool IsValid(Token<string> input)
{
switch(input.TokenType)
{
case "<cr>":
case "<space>":
case "<new-line>":
case "<tab>":
case "multi-line-comment":
case "single-line-comment":
return false;
default:
return true;
}
}
public static bool Equals(Dictionary<string, LR1ParsingTableCell> a,
Dictionary<string, LR1ParsingTableCell> b)
{
bool result = true;
foreach(var pairA in a)
{
var aCell = pairA.Value;
var bCell = b[pairA.Key];
result = result && (aCell.Equals(bCell));
}
return result;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Dialogflow.V2
{
/// <summary>Settings for <see cref="EnvironmentsClient"/> instances.</summary>
public sealed partial class EnvironmentsSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="EnvironmentsSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="EnvironmentsSettings"/>.</returns>
public static EnvironmentsSettings GetDefault() => new EnvironmentsSettings();
/// <summary>Constructs a new <see cref="EnvironmentsSettings"/> object with default settings.</summary>
public EnvironmentsSettings()
{
}
private EnvironmentsSettings(EnvironmentsSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
ListEnvironmentsSettings = existing.ListEnvironmentsSettings;
GetEnvironmentSettings = existing.GetEnvironmentSettings;
CreateEnvironmentSettings = existing.CreateEnvironmentSettings;
UpdateEnvironmentSettings = existing.UpdateEnvironmentSettings;
DeleteEnvironmentSettings = existing.DeleteEnvironmentSettings;
GetEnvironmentHistorySettings = existing.GetEnvironmentHistorySettings;
OnCopy(existing);
}
partial void OnCopy(EnvironmentsSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>EnvironmentsClient.ListEnvironments</c> and <c>EnvironmentsClient.ListEnvironmentsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>.</description>
/// </item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListEnvironmentsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>EnvironmentsClient.GetEnvironment</c> and <c>EnvironmentsClient.GetEnvironmentAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>.</description>
/// </item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetEnvironmentSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>EnvironmentsClient.CreateEnvironment</c> and <c>EnvironmentsClient.CreateEnvironmentAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>.</description>
/// </item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings CreateEnvironmentSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>EnvironmentsClient.UpdateEnvironment</c> and <c>EnvironmentsClient.UpdateEnvironmentAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>.</description>
/// </item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings UpdateEnvironmentSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>EnvironmentsClient.DeleteEnvironment</c> and <c>EnvironmentsClient.DeleteEnvironmentAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>.</description>
/// </item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings DeleteEnvironmentSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>EnvironmentsClient.GetEnvironmentHistory</c> and <c>EnvironmentsClient.GetEnvironmentHistoryAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>.</description>
/// </item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetEnvironmentHistorySettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="EnvironmentsSettings"/> object.</returns>
public EnvironmentsSettings Clone() => new EnvironmentsSettings(this);
}
/// <summary>
/// Builder class for <see cref="EnvironmentsClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class EnvironmentsClientBuilder : gaxgrpc::ClientBuilderBase<EnvironmentsClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public EnvironmentsSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public EnvironmentsClientBuilder()
{
UseJwtAccessWithScopes = EnvironmentsClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref EnvironmentsClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<EnvironmentsClient> task);
/// <summary>Builds the resulting client.</summary>
public override EnvironmentsClient Build()
{
EnvironmentsClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<EnvironmentsClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<EnvironmentsClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private EnvironmentsClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return EnvironmentsClient.Create(callInvoker, Settings);
}
private async stt::Task<EnvironmentsClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return EnvironmentsClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => EnvironmentsClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => EnvironmentsClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => EnvironmentsClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>Environments client wrapper, for convenient use.</summary>
/// <remarks>
/// Service for managing [Environments][google.cloud.dialogflow.v2.Environment].
/// </remarks>
public abstract partial class EnvironmentsClient
{
/// <summary>
/// The default endpoint for the Environments service, which is a host of "dialogflow.googleapis.com" and a port
/// of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "dialogflow.googleapis.com:443";
/// <summary>The default Environments scopes.</summary>
/// <remarks>
/// The default Environments scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// <item><description>https://www.googleapis.com/auth/dialogflow</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/dialogflow",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="EnvironmentsClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="EnvironmentsClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="EnvironmentsClient"/>.</returns>
public static stt::Task<EnvironmentsClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new EnvironmentsClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="EnvironmentsClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="EnvironmentsClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="EnvironmentsClient"/>.</returns>
public static EnvironmentsClient Create() => new EnvironmentsClientBuilder().Build();
/// <summary>
/// Creates a <see cref="EnvironmentsClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="EnvironmentsSettings"/>.</param>
/// <returns>The created <see cref="EnvironmentsClient"/>.</returns>
internal static EnvironmentsClient Create(grpccore::CallInvoker callInvoker, EnvironmentsSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
Environments.EnvironmentsClient grpcClient = new Environments.EnvironmentsClient(callInvoker);
return new EnvironmentsClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC Environments client</summary>
public virtual Environments.EnvironmentsClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the list of all non-default environments of the specified agent.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Environment"/> resources.</returns>
public virtual gax::PagedEnumerable<ListEnvironmentsResponse, Environment> ListEnvironments(ListEnvironmentsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the list of all non-default environments of the specified agent.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Environment"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListEnvironmentsResponse, Environment> ListEnvironmentsAsync(ListEnvironmentsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the list of all non-default environments of the specified agent.
/// </summary>
/// <param name="parent">
/// Required. The agent to list all environments from.
/// Format:
///
/// - `projects/{Project ID}/agent`
/// - `projects/{Project ID}/locations/{Location ID}/agent`
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Environment"/> resources.</returns>
public virtual gax::PagedEnumerable<ListEnvironmentsResponse, Environment> ListEnvironments(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListEnvironments(new ListEnvironmentsRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Returns the list of all non-default environments of the specified agent.
/// </summary>
/// <param name="parent">
/// Required. The agent to list all environments from.
/// Format:
///
/// - `projects/{Project ID}/agent`
/// - `projects/{Project ID}/locations/{Location ID}/agent`
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Environment"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListEnvironmentsResponse, Environment> ListEnvironmentsAsync(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListEnvironmentsAsync(new ListEnvironmentsRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Returns the list of all non-default environments of the specified agent.
/// </summary>
/// <param name="parent">
/// Required. The agent to list all environments from.
/// Format:
///
/// - `projects/{Project ID}/agent`
/// - `projects/{Project ID}/locations/{Location ID}/agent`
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Environment"/> resources.</returns>
public virtual gax::PagedEnumerable<ListEnvironmentsResponse, Environment> ListEnvironments(AgentName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListEnvironments(new ListEnvironmentsRequest
{
ParentAsAgentName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Returns the list of all non-default environments of the specified agent.
/// </summary>
/// <param name="parent">
/// Required. The agent to list all environments from.
/// Format:
///
/// - `projects/{Project ID}/agent`
/// - `projects/{Project ID}/locations/{Location ID}/agent`
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Environment"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListEnvironmentsResponse, Environment> ListEnvironmentsAsync(AgentName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListEnvironmentsAsync(new ListEnvironmentsRequest
{
ParentAsAgentName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Retrieves the specified agent environment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Environment GetEnvironment(GetEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Retrieves the specified agent environment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Environment> GetEnvironmentAsync(GetEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Retrieves the specified agent environment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Environment> GetEnvironmentAsync(GetEnvironmentRequest request, st::CancellationToken cancellationToken) =>
GetEnvironmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates an agent environment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Environment CreateEnvironment(CreateEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates an agent environment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Environment> CreateEnvironmentAsync(CreateEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates an agent environment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Environment> CreateEnvironmentAsync(CreateEnvironmentRequest request, st::CancellationToken cancellationToken) =>
CreateEnvironmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates the specified agent environment.
///
/// This method allows you to deploy new agent versions into the environment.
/// When an environment is pointed to a new agent version by setting
/// `environment.agent_version`, the environment is temporarily set to the
/// `LOADING` state. During that time, the environment continues serving the
/// previous version of the agent. After the new agent version is done loading,
/// the environment is set back to the `RUNNING` state.
/// You can use "-" as Environment ID in environment name to update an agent
/// version in the default environment. WARNING: this will negate all recent
/// changes to the draft agent and can't be undone. You may want to save the
/// draft agent to a version before calling this method.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Environment UpdateEnvironment(UpdateEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates the specified agent environment.
///
/// This method allows you to deploy new agent versions into the environment.
/// When an environment is pointed to a new agent version by setting
/// `environment.agent_version`, the environment is temporarily set to the
/// `LOADING` state. During that time, the environment continues serving the
/// previous version of the agent. After the new agent version is done loading,
/// the environment is set back to the `RUNNING` state.
/// You can use "-" as Environment ID in environment name to update an agent
/// version in the default environment. WARNING: this will negate all recent
/// changes to the draft agent and can't be undone. You may want to save the
/// draft agent to a version before calling this method.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Environment> UpdateEnvironmentAsync(UpdateEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates the specified agent environment.
///
/// This method allows you to deploy new agent versions into the environment.
/// When an environment is pointed to a new agent version by setting
/// `environment.agent_version`, the environment is temporarily set to the
/// `LOADING` state. During that time, the environment continues serving the
/// previous version of the agent. After the new agent version is done loading,
/// the environment is set back to the `RUNNING` state.
/// You can use "-" as Environment ID in environment name to update an agent
/// version in the default environment. WARNING: this will negate all recent
/// changes to the draft agent and can't be undone. You may want to save the
/// draft agent to a version before calling this method.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Environment> UpdateEnvironmentAsync(UpdateEnvironmentRequest request, st::CancellationToken cancellationToken) =>
UpdateEnvironmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Deletes the specified agent environment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual void DeleteEnvironment(DeleteEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes the specified agent environment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task DeleteEnvironmentAsync(DeleteEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes the specified agent environment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task DeleteEnvironmentAsync(DeleteEnvironmentRequest request, st::CancellationToken cancellationToken) =>
DeleteEnvironmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets the history of the specified environment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="EnvironmentHistory.Types.Entry"/> resources.</returns>
public virtual gax::PagedEnumerable<EnvironmentHistory, EnvironmentHistory.Types.Entry> GetEnvironmentHistory(GetEnvironmentHistoryRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the history of the specified environment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="EnvironmentHistory.Types.Entry"/> resources.
/// </returns>
public virtual gax::PagedAsyncEnumerable<EnvironmentHistory, EnvironmentHistory.Types.Entry> GetEnvironmentHistoryAsync(GetEnvironmentHistoryRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
}
/// <summary>Environments client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service for managing [Environments][google.cloud.dialogflow.v2.Environment].
/// </remarks>
public sealed partial class EnvironmentsClientImpl : EnvironmentsClient
{
private readonly gaxgrpc::ApiCall<ListEnvironmentsRequest, ListEnvironmentsResponse> _callListEnvironments;
private readonly gaxgrpc::ApiCall<GetEnvironmentRequest, Environment> _callGetEnvironment;
private readonly gaxgrpc::ApiCall<CreateEnvironmentRequest, Environment> _callCreateEnvironment;
private readonly gaxgrpc::ApiCall<UpdateEnvironmentRequest, Environment> _callUpdateEnvironment;
private readonly gaxgrpc::ApiCall<DeleteEnvironmentRequest, wkt::Empty> _callDeleteEnvironment;
private readonly gaxgrpc::ApiCall<GetEnvironmentHistoryRequest, EnvironmentHistory> _callGetEnvironmentHistory;
/// <summary>
/// Constructs a client wrapper for the Environments service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="EnvironmentsSettings"/> used within this client.</param>
public EnvironmentsClientImpl(Environments.EnvironmentsClient grpcClient, EnvironmentsSettings settings)
{
GrpcClient = grpcClient;
EnvironmentsSettings effectiveSettings = settings ?? EnvironmentsSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callListEnvironments = clientHelper.BuildApiCall<ListEnvironmentsRequest, ListEnvironmentsResponse>(grpcClient.ListEnvironmentsAsync, grpcClient.ListEnvironments, effectiveSettings.ListEnvironmentsSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callListEnvironments);
Modify_ListEnvironmentsApiCall(ref _callListEnvironments);
_callGetEnvironment = clientHelper.BuildApiCall<GetEnvironmentRequest, Environment>(grpcClient.GetEnvironmentAsync, grpcClient.GetEnvironment, effectiveSettings.GetEnvironmentSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callGetEnvironment);
Modify_GetEnvironmentApiCall(ref _callGetEnvironment);
_callCreateEnvironment = clientHelper.BuildApiCall<CreateEnvironmentRequest, Environment>(grpcClient.CreateEnvironmentAsync, grpcClient.CreateEnvironment, effectiveSettings.CreateEnvironmentSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callCreateEnvironment);
Modify_CreateEnvironmentApiCall(ref _callCreateEnvironment);
_callUpdateEnvironment = clientHelper.BuildApiCall<UpdateEnvironmentRequest, Environment>(grpcClient.UpdateEnvironmentAsync, grpcClient.UpdateEnvironment, effectiveSettings.UpdateEnvironmentSettings).WithGoogleRequestParam("environment.name", request => request.Environment?.Name);
Modify_ApiCall(ref _callUpdateEnvironment);
Modify_UpdateEnvironmentApiCall(ref _callUpdateEnvironment);
_callDeleteEnvironment = clientHelper.BuildApiCall<DeleteEnvironmentRequest, wkt::Empty>(grpcClient.DeleteEnvironmentAsync, grpcClient.DeleteEnvironment, effectiveSettings.DeleteEnvironmentSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callDeleteEnvironment);
Modify_DeleteEnvironmentApiCall(ref _callDeleteEnvironment);
_callGetEnvironmentHistory = clientHelper.BuildApiCall<GetEnvironmentHistoryRequest, EnvironmentHistory>(grpcClient.GetEnvironmentHistoryAsync, grpcClient.GetEnvironmentHistory, effectiveSettings.GetEnvironmentHistorySettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callGetEnvironmentHistory);
Modify_GetEnvironmentHistoryApiCall(ref _callGetEnvironmentHistory);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_ListEnvironmentsApiCall(ref gaxgrpc::ApiCall<ListEnvironmentsRequest, ListEnvironmentsResponse> call);
partial void Modify_GetEnvironmentApiCall(ref gaxgrpc::ApiCall<GetEnvironmentRequest, Environment> call);
partial void Modify_CreateEnvironmentApiCall(ref gaxgrpc::ApiCall<CreateEnvironmentRequest, Environment> call);
partial void Modify_UpdateEnvironmentApiCall(ref gaxgrpc::ApiCall<UpdateEnvironmentRequest, Environment> call);
partial void Modify_DeleteEnvironmentApiCall(ref gaxgrpc::ApiCall<DeleteEnvironmentRequest, wkt::Empty> call);
partial void Modify_GetEnvironmentHistoryApiCall(ref gaxgrpc::ApiCall<GetEnvironmentHistoryRequest, EnvironmentHistory> call);
partial void OnConstruction(Environments.EnvironmentsClient grpcClient, EnvironmentsSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC Environments client</summary>
public override Environments.EnvironmentsClient GrpcClient { get; }
partial void Modify_ListEnvironmentsRequest(ref ListEnvironmentsRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_GetEnvironmentRequest(ref GetEnvironmentRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_CreateEnvironmentRequest(ref CreateEnvironmentRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_UpdateEnvironmentRequest(ref UpdateEnvironmentRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_DeleteEnvironmentRequest(ref DeleteEnvironmentRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_GetEnvironmentHistoryRequest(ref GetEnvironmentHistoryRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the list of all non-default environments of the specified agent.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Environment"/> resources.</returns>
public override gax::PagedEnumerable<ListEnvironmentsResponse, Environment> ListEnvironments(ListEnvironmentsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListEnvironmentsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListEnvironmentsRequest, ListEnvironmentsResponse, Environment>(_callListEnvironments, request, callSettings);
}
/// <summary>
/// Returns the list of all non-default environments of the specified agent.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Environment"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListEnvironmentsResponse, Environment> ListEnvironmentsAsync(ListEnvironmentsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListEnvironmentsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListEnvironmentsRequest, ListEnvironmentsResponse, Environment>(_callListEnvironments, request, callSettings);
}
/// <summary>
/// Retrieves the specified agent environment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Environment GetEnvironment(GetEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetEnvironmentRequest(ref request, ref callSettings);
return _callGetEnvironment.Sync(request, callSettings);
}
/// <summary>
/// Retrieves the specified agent environment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Environment> GetEnvironmentAsync(GetEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetEnvironmentRequest(ref request, ref callSettings);
return _callGetEnvironment.Async(request, callSettings);
}
/// <summary>
/// Creates an agent environment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Environment CreateEnvironment(CreateEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateEnvironmentRequest(ref request, ref callSettings);
return _callCreateEnvironment.Sync(request, callSettings);
}
/// <summary>
/// Creates an agent environment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Environment> CreateEnvironmentAsync(CreateEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateEnvironmentRequest(ref request, ref callSettings);
return _callCreateEnvironment.Async(request, callSettings);
}
/// <summary>
/// Updates the specified agent environment.
///
/// This method allows you to deploy new agent versions into the environment.
/// When an environment is pointed to a new agent version by setting
/// `environment.agent_version`, the environment is temporarily set to the
/// `LOADING` state. During that time, the environment continues serving the
/// previous version of the agent. After the new agent version is done loading,
/// the environment is set back to the `RUNNING` state.
/// You can use "-" as Environment ID in environment name to update an agent
/// version in the default environment. WARNING: this will negate all recent
/// changes to the draft agent and can't be undone. You may want to save the
/// draft agent to a version before calling this method.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Environment UpdateEnvironment(UpdateEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateEnvironmentRequest(ref request, ref callSettings);
return _callUpdateEnvironment.Sync(request, callSettings);
}
/// <summary>
/// Updates the specified agent environment.
///
/// This method allows you to deploy new agent versions into the environment.
/// When an environment is pointed to a new agent version by setting
/// `environment.agent_version`, the environment is temporarily set to the
/// `LOADING` state. During that time, the environment continues serving the
/// previous version of the agent. After the new agent version is done loading,
/// the environment is set back to the `RUNNING` state.
/// You can use "-" as Environment ID in environment name to update an agent
/// version in the default environment. WARNING: this will negate all recent
/// changes to the draft agent and can't be undone. You may want to save the
/// draft agent to a version before calling this method.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Environment> UpdateEnvironmentAsync(UpdateEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateEnvironmentRequest(ref request, ref callSettings);
return _callUpdateEnvironment.Async(request, callSettings);
}
/// <summary>
/// Deletes the specified agent environment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override void DeleteEnvironment(DeleteEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteEnvironmentRequest(ref request, ref callSettings);
_callDeleteEnvironment.Sync(request, callSettings);
}
/// <summary>
/// Deletes the specified agent environment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task DeleteEnvironmentAsync(DeleteEnvironmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteEnvironmentRequest(ref request, ref callSettings);
return _callDeleteEnvironment.Async(request, callSettings);
}
/// <summary>
/// Gets the history of the specified environment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="EnvironmentHistory.Types.Entry"/> resources.</returns>
public override gax::PagedEnumerable<EnvironmentHistory, EnvironmentHistory.Types.Entry> GetEnvironmentHistory(GetEnvironmentHistoryRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetEnvironmentHistoryRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<GetEnvironmentHistoryRequest, EnvironmentHistory, EnvironmentHistory.Types.Entry>(_callGetEnvironmentHistory, request, callSettings);
}
/// <summary>
/// Gets the history of the specified environment.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="EnvironmentHistory.Types.Entry"/> resources.
/// </returns>
public override gax::PagedAsyncEnumerable<EnvironmentHistory, EnvironmentHistory.Types.Entry> GetEnvironmentHistoryAsync(GetEnvironmentHistoryRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetEnvironmentHistoryRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<GetEnvironmentHistoryRequest, EnvironmentHistory, EnvironmentHistory.Types.Entry>(_callGetEnvironmentHistory, request, callSettings);
}
}
public partial class ListEnvironmentsRequest : gaxgrpc::IPageRequest
{
}
public partial class GetEnvironmentHistoryRequest : gaxgrpc::IPageRequest
{
}
public partial class ListEnvironmentsResponse : gaxgrpc::IPageResponse<Environment>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<Environment> GetEnumerator() => Environments.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
public partial class EnvironmentHistory : gaxgrpc::IPageResponse<EnvironmentHistory.Types.Entry>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<Types.Entry> GetEnumerator() => Entries.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using IBits = Lucene.Net.Util.IBits;
using MultiSortedDocValues = Lucene.Net.Index.MultiDocValues.MultiSortedDocValues;
using MultiSortedSetDocValues = Lucene.Net.Index.MultiDocValues.MultiSortedSetDocValues;
using OrdinalMap = Lucene.Net.Index.MultiDocValues.OrdinalMap;
/// <summary>
/// This class forces a composite reader (eg a
/// <see cref="MultiReader"/> or <see cref="DirectoryReader"/>) to emulate an
/// atomic reader. This requires implementing the postings
/// APIs on-the-fly, using the static methods in
/// <see cref="MultiFields"/>, <see cref="MultiDocValues"/>, by stepping through
/// the sub-readers to merge fields/terms, appending docs, etc.
///
/// <para/><b>NOTE</b>: This class almost always results in a
/// performance hit. If this is important to your use case,
/// you'll get better performance by gathering the sub readers using
/// <see cref="IndexReader.Context"/> to get the
/// atomic leaves and then operate per-AtomicReader,
/// instead of using this class.
/// </summary>
public sealed class SlowCompositeReaderWrapper : AtomicReader
{
private readonly CompositeReader @in;
private readonly Fields fields;
private readonly IBits liveDocs;
/// <summary>
/// This method is sugar for getting an <see cref="AtomicReader"/> from
/// an <see cref="IndexReader"/> of any kind. If the reader is already atomic,
/// it is returned unchanged, otherwise wrapped by this class.
/// </summary>
public static AtomicReader Wrap(IndexReader reader)
{
CompositeReader compositeReader = reader as CompositeReader;
if (compositeReader != null)
{
return new SlowCompositeReaderWrapper(compositeReader);
}
else
{
Debug.Assert(reader is AtomicReader);
return (AtomicReader)reader;
}
}
private SlowCompositeReaderWrapper(CompositeReader reader)
: base()
{
@in = reader;
fields = MultiFields.GetFields(@in);
liveDocs = MultiFields.GetLiveDocs(@in);
@in.RegisterParentReader(this);
}
public override string ToString()
{
return "SlowCompositeReaderWrapper(" + @in + ")";
}
public override Fields Fields
{
get
{
EnsureOpen();
return fields;
}
}
public override NumericDocValues GetNumericDocValues(string field)
{
EnsureOpen();
return MultiDocValues.GetNumericValues(@in, field);
}
public override IBits GetDocsWithField(string field)
{
EnsureOpen();
return MultiDocValues.GetDocsWithField(@in, field);
}
public override BinaryDocValues GetBinaryDocValues(string field)
{
EnsureOpen();
return MultiDocValues.GetBinaryValues(@in, field);
}
public override SortedDocValues GetSortedDocValues(string field)
{
EnsureOpen();
OrdinalMap map = null;
lock (cachedOrdMaps)
{
if (!cachedOrdMaps.TryGetValue(field, out map))
{
// uncached, or not a multi dv
SortedDocValues dv = MultiDocValues.GetSortedValues(@in, field);
MultiSortedDocValues docValues = dv as MultiSortedDocValues;
if (docValues != null)
{
map = docValues.Mapping;
if (map.owner == CoreCacheKey)
{
cachedOrdMaps[field] = map;
}
}
return dv;
}
}
// cached ordinal map
if (FieldInfos.FieldInfo(field).DocValuesType != DocValuesType.SORTED)
{
return null;
}
int size = @in.Leaves.Count;
SortedDocValues[] values = new SortedDocValues[size];
int[] starts = new int[size + 1];
for (int i = 0; i < size; i++)
{
AtomicReaderContext context = @in.Leaves[i];
SortedDocValues v = context.AtomicReader.GetSortedDocValues(field) ?? DocValues.EMPTY_SORTED;
values[i] = v;
starts[i] = context.DocBase;
}
starts[size] = MaxDoc;
return new MultiSortedDocValues(values, starts, map);
}
public override SortedSetDocValues GetSortedSetDocValues(string field)
{
EnsureOpen();
OrdinalMap map = null;
lock (cachedOrdMaps)
{
if (!cachedOrdMaps.TryGetValue(field, out map))
{
// uncached, or not a multi dv
SortedSetDocValues dv = MultiDocValues.GetSortedSetValues(@in, field);
MultiSortedSetDocValues docValues = dv as MultiSortedSetDocValues;
if (docValues != null)
{
map = docValues.Mapping;
if (map.owner == CoreCacheKey)
{
cachedOrdMaps[field] = map;
}
}
return dv;
}
}
// cached ordinal map
if (FieldInfos.FieldInfo(field).DocValuesType != DocValuesType.SORTED_SET)
{
return null;
}
Debug.Assert(map != null);
int size = @in.Leaves.Count;
var values = new SortedSetDocValues[size];
int[] starts = new int[size + 1];
for (int i = 0; i < size; i++)
{
AtomicReaderContext context = @in.Leaves[i];
SortedSetDocValues v = context.AtomicReader.GetSortedSetDocValues(field) ?? DocValues.EMPTY_SORTED_SET;
values[i] = v;
starts[i] = context.DocBase;
}
starts[size] = MaxDoc;
return new MultiSortedSetDocValues(values, starts, map);
}
// TODO: this could really be a weak map somewhere else on the coreCacheKey,
// but do we really need to optimize slow-wrapper any more?
private readonly IDictionary<string, OrdinalMap> cachedOrdMaps = new Dictionary<string, OrdinalMap>();
public override NumericDocValues GetNormValues(string field)
{
EnsureOpen();
return MultiDocValues.GetNormValues(@in, field);
}
public override Fields GetTermVectors(int docID)
{
EnsureOpen();
return @in.GetTermVectors(docID);
}
public override int NumDocs
{
get
{
// Don't call ensureOpen() here (it could affect performance)
return @in.NumDocs;
}
}
public override int MaxDoc
{
get
{
// Don't call ensureOpen() here (it could affect performance)
return @in.MaxDoc;
}
}
public override void Document(int docID, StoredFieldVisitor visitor)
{
EnsureOpen();
@in.Document(docID, visitor);
}
public override IBits LiveDocs
{
get
{
EnsureOpen();
return liveDocs;
}
}
public override FieldInfos FieldInfos
{
get
{
EnsureOpen();
return MultiFields.GetMergedFieldInfos(@in);
}
}
public override object CoreCacheKey
{
get
{
return @in.CoreCacheKey;
}
}
public override object CombinedCoreAndDeletesKey
{
get
{
return @in.CombinedCoreAndDeletesKey;
}
}
protected internal override void DoClose()
{
// TODO: as this is a wrapper, should we really close the delegate?
@in.Dispose();
}
public override void CheckIntegrity()
{
EnsureOpen();
foreach (AtomicReaderContext ctx in @in.Leaves)
{
ctx.AtomicReader.CheckIntegrity();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public static class CtorTests
{
[Fact]
public static void TestDefaultConstructor()
{
using (X509Certificate2 c = new X509Certificate2())
{
VerifyDefaultConstructor(c);
}
}
private static void VerifyDefaultConstructor(X509Certificate2 c)
{
IntPtr h = c.Handle;
object ignored;
Assert.Equal(IntPtr.Zero, h);
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithm());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParameters());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParametersString());
Assert.ThrowsAny<CryptographicException>(() => c.GetPublicKey());
Assert.ThrowsAny<CryptographicException>(() => c.GetSerialNumber());
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Issuer);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Subject);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.RawData);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Thumbprint);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.SignatureAlgorithm);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.HasPrivateKey);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Version);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Archived);
Assert.ThrowsAny<CryptographicException>(() => c.Archived = false);
Assert.ThrowsAny<CryptographicException>(() => c.FriendlyName = "Hi");
Assert.ThrowsAny<CryptographicException>(() => ignored = c.SubjectName);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.IssuerName);
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHashString());
Assert.ThrowsAny<CryptographicException>(() => c.GetEffectiveDateString());
Assert.ThrowsAny<CryptographicException>(() => c.GetExpirationDateString());
Assert.ThrowsAny<CryptographicException>(() => c.GetPublicKeyString());
Assert.ThrowsAny<CryptographicException>(() => c.GetRawCertData());
Assert.ThrowsAny<CryptographicException>(() => c.GetRawCertDataString());
Assert.ThrowsAny<CryptographicException>(() => c.GetSerialNumberString());
#pragma warning disable 0618
Assert.ThrowsAny<CryptographicException>(() => c.GetIssuerName());
Assert.ThrowsAny<CryptographicException>(() => c.GetName());
#pragma warning restore 0618
}
[Fact]
public static void TestConstructor_DER()
{
byte[] expectedThumbPrint = new byte[]
{
0x10, 0x8e, 0x2b, 0xa2, 0x36, 0x32, 0x62, 0x0c,
0x42, 0x7c, 0x57, 0x0b, 0x6d, 0x9d, 0xb5, 0x1a,
0xc3, 0x13, 0x87, 0xfe,
};
Action<X509Certificate2> assert = (c) =>
{
IntPtr h = c.Handle;
Assert.NotEqual(IntPtr.Zero, h);
byte[] actualThumbprint = c.GetCertHash();
Assert.Equal(expectedThumbPrint, actualThumbprint);
};
using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate))
{
assert(c);
using (X509Certificate2 c2 = new X509Certificate2(c))
{
assert(c2);
}
}
}
[Fact]
public static void TestConstructor_PEM()
{
byte[] expectedThumbPrint =
{
0x10, 0x8e, 0x2b, 0xa2, 0x36, 0x32, 0x62, 0x0c,
0x42, 0x7c, 0x57, 0x0b, 0x6d, 0x9d, 0xb5, 0x1a,
0xc3, 0x13, 0x87, 0xfe,
};
Action<X509Certificate2> assert = (cert) =>
{
IntPtr h = cert.Handle;
Assert.NotEqual(IntPtr.Zero, h);
byte[] actualThumbprint = cert.GetCertHash();
Assert.Equal(expectedThumbPrint, actualThumbprint);
};
using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificatePemBytes))
{
assert(c);
using (X509Certificate2 c2 = new X509Certificate2(c))
{
assert(c2);
}
}
}
[Fact]
public static void TestCopyConstructor_NoPal()
{
using (var c1 = new X509Certificate2())
using (var c2 = new X509Certificate2(c1))
{
VerifyDefaultConstructor(c1);
VerifyDefaultConstructor(c2);
}
}
[Fact]
public static void TestCopyConstructor_Pal()
{
using (var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
using (var c2 = new X509Certificate2(c1))
{
Assert.Equal(c1.GetCertHash(), c2.GetCertHash());
Assert.Equal(c1.GetKeyAlgorithm(), c2.GetKeyAlgorithm());
Assert.Equal(c1.GetKeyAlgorithmParameters(), c2.GetKeyAlgorithmParameters());
Assert.Equal(c1.GetKeyAlgorithmParametersString(), c2.GetKeyAlgorithmParametersString());
Assert.Equal(c1.GetPublicKey(), c2.GetPublicKey());
Assert.Equal(c1.GetSerialNumber(), c2.GetSerialNumber());
Assert.Equal(c1.Issuer, c2.Issuer);
Assert.Equal(c1.Subject, c2.Subject);
Assert.Equal(c1.RawData, c2.RawData);
Assert.Equal(c1.Thumbprint, c2.Thumbprint);
Assert.Equal(c1.SignatureAlgorithm.Value, c2.SignatureAlgorithm.Value);
Assert.Equal(c1.HasPrivateKey, c2.HasPrivateKey);
Assert.Equal(c1.Version, c2.Version);
Assert.Equal(c1.Archived, c2.Archived);
Assert.Equal(c1.SubjectName.Name, c2.SubjectName.Name);
Assert.Equal(c1.IssuerName.Name, c2.IssuerName.Name);
Assert.Equal(c1.GetCertHashString(), c2.GetCertHashString());
Assert.Equal(c1.GetEffectiveDateString(), c2.GetEffectiveDateString());
Assert.Equal(c1.GetExpirationDateString(), c2.GetExpirationDateString());
Assert.Equal(c1.GetPublicKeyString(), c2.GetPublicKeyString());
Assert.Equal(c1.GetRawCertData(), c2.GetRawCertData());
Assert.Equal(c1.GetRawCertDataString(), c2.GetRawCertDataString());
Assert.Equal(c1.GetSerialNumberString(), c2.GetSerialNumberString());
#pragma warning disable 0618
Assert.Equal(c1.GetIssuerName(), c2.GetIssuerName());
Assert.Equal(c1.GetName(), c2.GetName());
#pragma warning restore 0618
}
}
[Fact]
public static void TestCopyConstructor_Lifetime_Independent()
{
var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword);
using (var c2 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
{
RSA rsa = c2.GetRSAPrivateKey();
byte[] hash = new byte[20];
byte[] sig = rsa.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.Equal(TestData.PfxSha1Empty_ExpectedSig, sig);
c1.Dispose();
rsa.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
// Verify other cert and previous key do not affect cert
using (rsa = c2.GetRSAPrivateKey())
{
hash = new byte[20];
sig = rsa.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.Equal(TestData.PfxSha1Empty_ExpectedSig, sig);
}
}
}
[Fact]
public static void TestCopyConstructor_Lifetime_Cloned()
{
var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword);
var c2 = new X509Certificate2(c1);
TestPrivateKey(c1, true);
TestPrivateKey(c2, true);
c1.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
TestPrivateKey(c1, false);
TestPrivateKey(c2, true);
c2.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
TestPrivateKey(c2, false);
}
[Fact]
public static void TestCopyConstructor_Lifetime_Cloned_Reversed()
{
var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword);
var c2 = new X509Certificate2(c1);
TestPrivateKey(c1, true);
TestPrivateKey(c2, true);
c2.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
TestPrivateKey(c1, true);
TestPrivateKey(c2, false);
c1.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
TestPrivateKey(c1, false);
}
private static void TestPrivateKey(X509Certificate2 c, bool expectSuccess)
{
if (expectSuccess)
{
using (RSA rsa = c.GetRSAPrivateKey())
{
byte[] hash = new byte[20];
byte[] sig = rsa.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.Equal(TestData.PfxSha1Empty_ExpectedSig, sig);
}
}
else
{
Assert.ThrowsAny<CryptographicException>(() => c.GetRSAPrivateKey());
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // StoreSavedAsSerializedCerData not supported on Unix
public static void TestConstructor_SerializedCert_Windows()
{
const string ExpectedThumbPrint = "71CB4E2B02738AD44F8B382C93BD17BA665F9914";
Action<X509Certificate2> assert = (cert) =>
{
IntPtr h = cert.Handle;
Assert.NotEqual(IntPtr.Zero, h);
Assert.Equal(ExpectedThumbPrint, cert.Thumbprint);
};
using (X509Certificate2 c = new X509Certificate2(TestData.StoreSavedAsSerializedCerData))
{
assert(c);
using (X509Certificate2 c2 = new X509Certificate2(c))
{
assert(c2);
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // StoreSavedAsSerializedCerData not supported on Unix
public static void TestByteArrayConstructor_SerializedCert_Unix()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.StoreSavedAsSerializedCerData));
}
[Fact]
public static void TestNullConstructorArguments()
{
Assert.Throws<ArgumentNullException>(() => new X509Certificate2((string)null));
AssertExtensions.Throws<ArgumentException>("handle", () => new X509Certificate2(IntPtr.Zero));
AssertExtensions.Throws<ArgumentException>("rawData", () => new X509Certificate2((byte[])null, (string)null));
AssertExtensions.Throws<ArgumentException>("rawData", () => new X509Certificate2(Array.Empty<byte>(), (string)null));
AssertExtensions.Throws<ArgumentException>("rawData", () => new X509Certificate2((byte[])null, (string)null, X509KeyStorageFlags.DefaultKeySet));
AssertExtensions.Throws<ArgumentException>("rawData", () => new X509Certificate2(Array.Empty<byte>(), (string)null, X509KeyStorageFlags.DefaultKeySet));
// A null string password does not throw
using (new X509Certificate2(TestData.MsCertificate, (string)null)) { }
using (new X509Certificate2(TestData.MsCertificate, (string)null, X509KeyStorageFlags.DefaultKeySet)) { }
Assert.Throws<ArgumentNullException>(() => X509Certificate.CreateFromCertFile(null));
Assert.Throws<ArgumentNullException>(() => X509Certificate.CreateFromSignedFile(null));
AssertExtensions.Throws<ArgumentNullException>("cert", () => new X509Certificate2((X509Certificate2)null));
AssertExtensions.Throws<ArgumentException>("handle", () => new X509Certificate2(IntPtr.Zero));
// A null SecureString password does not throw
using (new X509Certificate2(TestData.MsCertificate, (SecureString)null)) { }
using (new X509Certificate2(TestData.MsCertificate, (SecureString)null, X509KeyStorageFlags.DefaultKeySet)) { }
// For compat reasons, the (byte[]) constructor (and only that constructor) treats a null or 0-length array as the same
// as calling the default constructor.
{
using (X509Certificate2 c = new X509Certificate2((byte[])null))
{
IntPtr h = c.Handle;
Assert.Equal(IntPtr.Zero, h);
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash());
}
}
{
using (X509Certificate2 c = new X509Certificate2(Array.Empty<byte>()))
{
IntPtr h = c.Handle;
Assert.Equal(IntPtr.Zero, h);
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash());
}
}
}
[Fact]
public static void InvalidCertificateBlob()
{
CryptographicException ex = Assert.ThrowsAny<CryptographicException>(
() => new X509Certificate2(new byte[] { 0x01, 0x02, 0x03 }));
CryptographicException defaultException = new CryptographicException();
Assert.NotEqual(defaultException.Message, ex.Message);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Equal(unchecked((int)0x80092009), ex.HResult);
// TODO (3233): Test that Message is also set correctly
//Assert.Equal("Cannot find the requested object.", ex.Message);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Assert.Equal(-25257, ex.HResult);
}
else // Any Unix
{
Assert.Equal(0x0D07803A, ex.HResult);
Assert.Equal("error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error", ex.Message);
}
}
[Fact]
public static void InvalidStorageFlags()
{
byte[] nonEmptyBytes = new byte[1];
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate(nonEmptyBytes, string.Empty, (X509KeyStorageFlags)0xFF));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate(string.Empty, string.Empty, (X509KeyStorageFlags)0xFF));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate2(nonEmptyBytes, string.Empty, (X509KeyStorageFlags)0xFF));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate2(string.Empty, string.Empty, (X509KeyStorageFlags)0xFF));
// No test is performed here for the ephemeral flag failing downlevel, because the live
// binary is always used by default, meaning it doesn't know EphemeralKeySet doesn't exist.
}
[Fact]
public static void InvalidStorageFlags_PersistedEphemeral()
{
const X509KeyStorageFlags PersistedEphemeral =
X509KeyStorageFlags.EphemeralKeySet | X509KeyStorageFlags.PersistKeySet;
byte[] nonEmptyBytes = new byte[1];
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate(nonEmptyBytes, string.Empty, PersistedEphemeral));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate(string.Empty, string.Empty, PersistedEphemeral));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate2(nonEmptyBytes, string.Empty, PersistedEphemeral));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate2(string.Empty, string.Empty, PersistedEphemeral));
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using CURLAUTH = Interop.Http.CURLAUTH;
using CURLcode = Interop.Http.CURLcode;
using CURLoption = Interop.Http.CURLoption;
using CurlProtocols = Interop.Http.CurlProtocols;
using CURLProxyType = Interop.Http.curl_proxytype;
using SafeCurlHandle = Interop.Http.SafeCurlHandle;
using SafeCurlSListHandle = Interop.Http.SafeCurlSListHandle;
using SafeCallbackHandle = Interop.Http.SafeCallbackHandle;
using SeekCallback = Interop.Http.SeekCallback;
using ReadWriteCallback = Interop.Http.ReadWriteCallback;
using ReadWriteFunction = Interop.Http.ReadWriteFunction;
using SslCtxCallback = Interop.Http.SslCtxCallback;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
private sealed class EasyRequest : TaskCompletionSource<HttpResponseMessage>
{
internal readonly CurlHandler _handler;
internal readonly HttpRequestMessage _requestMessage;
internal readonly CurlResponseMessage _responseMessage;
internal readonly CancellationToken _cancellationToken;
internal readonly HttpContentAsyncStream _requestContentStream;
internal SafeCurlHandle _easyHandle;
private SafeCurlSListHandle _requestHeaders;
internal NetworkCredential _networkCredential;
internal MultiAgent _associatedMultiAgent;
internal SendTransferState _sendTransferState;
internal bool _isRedirect = false;
private SafeCallbackHandle _callbackHandle;
public EasyRequest(CurlHandler handler, HttpRequestMessage requestMessage, CancellationToken cancellationToken) :
base(TaskCreationOptions.RunContinuationsAsynchronously)
{
_handler = handler;
_requestMessage = requestMessage;
_cancellationToken = cancellationToken;
if (requestMessage.Content != null)
{
_requestContentStream = new HttpContentAsyncStream(requestMessage.Content);
}
_responseMessage = new CurlResponseMessage(this);
}
/// <summary>
/// Initialize the underlying libcurl support for this EasyRequest.
/// This is separated out of the constructor so that we can take into account
/// any additional configuration needed based on the request message
/// after the EasyRequest is configured and so that error handling
/// can be better handled in the caller.
/// </summary>
internal void InitializeCurl()
{
// Create the underlying easy handle
SafeCurlHandle easyHandle = Interop.Http.EasyCreate();
if (easyHandle.IsInvalid)
{
throw new OutOfMemoryException();
}
_easyHandle = easyHandle;
// Configure the handle
SetUrl();
SetDebugging();
SetMultithreading();
SetRedirection();
SetVerb();
SetDecompressionOptions();
SetProxyOptions(_requestMessage.RequestUri);
SetCredentialsOptions(_handler.GetNetworkCredentials(_handler._serverCredentials, _requestMessage.RequestUri));
SetCookieOption(_requestMessage.RequestUri);
SetRequestHeaders();
SetSslOptions();
}
public void EnsureResponseMessagePublished()
{
bool result = TrySetResult(_responseMessage);
Debug.Assert(result || Task.Status == TaskStatus.RanToCompletion,
"If the task was already completed, it should have been completed succesfully; " +
"we shouldn't be completing as successful after already completing as failed.");
}
public void FailRequest(Exception error)
{
Debug.Assert(error != null, "Expected non-null exception");
var oce = error as OperationCanceledException;
if (oce != null)
{
TrySetCanceled(oce.CancellationToken);
}
else
{
if (error is IOException || error is CurlException || error == null)
{
error = CreateHttpRequestException(error);
}
TrySetException(error);
}
// There's not much we can reasonably assert here about the result of TrySet*.
// It's possible that the task wasn't yet completed (e.g. a failure while initiating the request),
// it's possible that the task was already completed as success (e.g. a failure sending back the response),
// and it's possible that the task was already completed as failure (e.g. we handled the exception and
// faulted the task, but then tried to fault it again while finishing processing in the main loop).
// Make sure the exception is available on the response stream so that it's propagated
// from any attempts to read from the stream.
_responseMessage.ResponseStream.SignalComplete(error);
}
public void Cleanup() // not called Dispose because the request may still be in use after it's cleaned up
{
_responseMessage.ResponseStream.SignalComplete(); // No more callbacks so no more data
// Don't dispose of the ResponseMessage.ResponseStream as it may still be in use
// by code reading data stored in the stream.
// Dispose of the input content stream if there was one. Nothing should be using it any more.
if (_requestContentStream != null)
_requestContentStream.Dispose();
// Dispose of the underlying easy handle. We're no longer processing it.
if (_easyHandle != null)
_easyHandle.Dispose();
// Dispose of the request headers if we had any. We had to keep this handle
// alive as long as the easy handle was using it. We didn't need to do any
// ref counting on the safe handle, though, as the only processing happens
// in Process, which ensures the handle will be rooted while libcurl is
// doing any processing that assumes it's valid.
if (_requestHeaders != null)
_requestHeaders.Dispose();
if (_callbackHandle != null)
_callbackHandle.Dispose();
}
private void SetUrl()
{
VerboseTrace(_requestMessage.RequestUri.AbsoluteUri);
SetCurlOption(CURLoption.CURLOPT_URL, _requestMessage.RequestUri.AbsoluteUri);
SetCurlOption(CURLoption.CURLOPT_PROTOCOLS, (long)(CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS));
}
[Conditional(VerboseDebuggingConditional)]
private void SetDebugging()
{
SetCurlOption(CURLoption.CURLOPT_VERBOSE, 1L);
// In addition to CURLOPT_VERBOSE, CURLOPT_DEBUGFUNCTION could be used here in the future to:
// - Route the verbose output to somewhere other than stderr
// - Dump additional data related to CURLINFO_DATA_* and CURLINFO_SSL_DATA_*
}
private void SetMultithreading()
{
SetCurlOption(CURLoption.CURLOPT_NOSIGNAL, 1L);
}
private void SetRedirection()
{
if (!_handler._automaticRedirection)
{
return;
}
VerboseTrace(_handler._maxAutomaticRedirections.ToString());
SetCurlOption(CURLoption.CURLOPT_FOLLOWLOCATION, 1L);
CurlProtocols redirectProtocols = string.Equals(_requestMessage.RequestUri.Scheme, UriSchemeHttps, StringComparison.OrdinalIgnoreCase) ?
CurlProtocols.CURLPROTO_HTTPS : // redirect only to another https
CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS; // redirect to http or to https
SetCurlOption(CURLoption.CURLOPT_REDIR_PROTOCOLS, (long)redirectProtocols);
SetCurlOption(CURLoption.CURLOPT_MAXREDIRS, _handler._maxAutomaticRedirections);
}
private void SetVerb()
{
VerboseTrace(_requestMessage.Method.Method);
if (_requestMessage.Method == HttpMethod.Put)
{
SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L);
if (_requestMessage.Content == null)
{
SetCurlOption(CURLoption.CURLOPT_INFILESIZE, 0L);
}
}
else if (_requestMessage.Method == HttpMethod.Head)
{
SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L);
}
else if (_requestMessage.Method == HttpMethod.Post)
{
SetCurlOption(CURLoption.CURLOPT_POST, 1L);
if (_requestMessage.Content == null)
{
SetCurlOption(CURLoption.CURLOPT_POSTFIELDSIZE, 0L);
SetCurlOption(CURLoption.CURLOPT_COPYPOSTFIELDS, string.Empty);
}
}
else if (_requestMessage.Method == HttpMethod.Trace)
{
SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method);
SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L);
}
else
{
SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method);
if (_requestMessage.Content != null)
{
SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L);
}
}
}
private void SetDecompressionOptions()
{
if (!_handler.SupportsAutomaticDecompression)
{
return;
}
DecompressionMethods autoDecompression = _handler.AutomaticDecompression;
bool gzip = (autoDecompression & DecompressionMethods.GZip) != 0;
bool deflate = (autoDecompression & DecompressionMethods.Deflate) != 0;
if (gzip || deflate)
{
string encoding = (gzip && deflate) ? EncodingNameGzip + "," + EncodingNameDeflate :
gzip ? EncodingNameGzip :
EncodingNameDeflate;
SetCurlOption(CURLoption.CURLOPT_ACCEPT_ENCODING, encoding);
VerboseTrace(encoding);
}
}
internal void SetProxyOptions(Uri requestUri)
{
if (_handler._proxyPolicy == ProxyUsePolicy.DoNotUseProxy)
{
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
VerboseTrace("No proxy");
return;
}
if ((_handler._proxyPolicy == ProxyUsePolicy.UseDefaultProxy) ||
(_handler.Proxy == null))
{
VerboseTrace("Default proxy");
return;
}
Debug.Assert(_handler.Proxy != null, "proxy is null");
Debug.Assert(_handler._proxyPolicy == ProxyUsePolicy.UseCustomProxy, "_proxyPolicy is not UseCustomProxy");
if (_handler.Proxy.IsBypassed(requestUri))
{
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
VerboseTrace("Bypassed proxy");
return;
}
var proxyUri = _handler.Proxy.GetProxy(requestUri);
if (proxyUri == null)
{
VerboseTrace("No proxy URI");
return;
}
SetCurlOption(CURLoption.CURLOPT_PROXYTYPE, (long)CURLProxyType.CURLPROXY_HTTP);
SetCurlOption(CURLoption.CURLOPT_PROXY, proxyUri.AbsoluteUri);
SetCurlOption(CURLoption.CURLOPT_PROXYPORT, proxyUri.Port);
VerboseTrace("Set proxy: " + proxyUri.ToString());
KeyValuePair<NetworkCredential, CURLAUTH> credentialScheme = GetCredentials(_handler.Proxy.Credentials, _requestMessage.RequestUri);
NetworkCredential credentials = credentialScheme.Key;
if (credentials != null)
{
if (string.IsNullOrEmpty(credentials.UserName))
{
throw new ArgumentException(SR.net_http_argument_empty_string, "UserName");
}
string credentialText = string.IsNullOrEmpty(credentials.Domain) ?
string.Format("{0}:{1}", credentials.UserName, credentials.Password) :
string.Format("{2}\\{0}:{1}", credentials.UserName, credentials.Password, credentials.Domain);
SetCurlOption(CURLoption.CURLOPT_PROXYUSERPWD, credentialText);
VerboseTrace("Set proxy credentials");
}
}
internal void SetCredentialsOptions(KeyValuePair<NetworkCredential, CURLAUTH> credentialSchemePair)
{
if (credentialSchemePair.Key == null)
{
_networkCredential = null;
return;
}
NetworkCredential credentials = credentialSchemePair.Key;
CURLAUTH authScheme = credentialSchemePair.Value;
string userName = string.IsNullOrEmpty(credentials.Domain) ?
credentials.UserName :
string.Format("{0}\\{1}", credentials.Domain, credentials.UserName);
SetCurlOption(CURLoption.CURLOPT_USERNAME, userName);
SetCurlOption(CURLoption.CURLOPT_HTTPAUTH, (long)authScheme);
if (credentials.Password != null)
{
SetCurlOption(CURLoption.CURLOPT_PASSWORD, credentials.Password);
}
_networkCredential = credentials;
VerboseTrace("Set credentials options");
}
internal void SetCookieOption(Uri uri)
{
if (!_handler._useCookie)
{
return;
}
string cookieValues = _handler.CookieContainer.GetCookieHeader(uri);
if (!string.IsNullOrEmpty(cookieValues))
{
SetCurlOption(CURLoption.CURLOPT_COOKIE, cookieValues);
VerboseTrace("Set cookies");
}
}
private void SetRequestHeaders()
{
HttpContentHeaders contentHeaders = null;
if (_requestMessage.Content != null)
{
SetChunkedModeForSend(_requestMessage);
// TODO: Content-Length header isn't getting correctly placed using ToString()
// This is a bug in HttpContentHeaders that needs to be fixed.
if (_requestMessage.Content.Headers.ContentLength.HasValue)
{
long contentLength = _requestMessage.Content.Headers.ContentLength.Value;
_requestMessage.Content.Headers.ContentLength = null;
_requestMessage.Content.Headers.ContentLength = contentLength;
}
contentHeaders = _requestMessage.Content.Headers;
}
var slist = new SafeCurlSListHandle();
// Add request and content request headers
if (_requestMessage.Headers != null)
{
AddRequestHeaders(_requestMessage.Headers, slist);
}
if (contentHeaders != null)
{
AddRequestHeaders(contentHeaders, slist);
if (contentHeaders.ContentType == null)
{
if (!Interop.Http.SListAppend(slist, NoContentType))
{
throw CreateHttpRequestException();
}
}
}
// Since libcurl always adds a Transfer-Encoding header, we need to explicitly block
// it if caller specifically does not want to set the header
if (_requestMessage.Headers.TransferEncodingChunked.HasValue &&
!_requestMessage.Headers.TransferEncodingChunked.Value)
{
if (!Interop.Http.SListAppend(slist, NoTransferEncoding))
{
throw CreateHttpRequestException();
}
}
if (!slist.IsInvalid)
{
_requestHeaders = slist;
SetCurlOption(CURLoption.CURLOPT_HTTPHEADER, slist);
VerboseTrace("Set headers");
}
else
{
slist.Dispose();
}
}
private void SetSslOptions()
{
// SSL Options should be set regardless of the type of the original request,
// in case an http->https redirection occurs.
//
// While this does slow down the theoretical best path of the request the code
// to decide that we need to register the callback is more complicated than, and
// potentially more expensive than, just always setting the callback.
SslProvider.SetSslOptions(this, _handler.ClientCertificateOptions);
}
internal void SetCurlCallbacks(
IntPtr easyGCHandle,
ReadWriteCallback receiveHeadersCallback,
ReadWriteCallback sendCallback,
SeekCallback seekCallback,
ReadWriteCallback receiveBodyCallback)
{
if (_callbackHandle == null)
{
_callbackHandle = new SafeCallbackHandle();
}
// Add callback for processing headers
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Header,
receiveHeadersCallback,
easyGCHandle,
ref _callbackHandle);
// If we're sending data as part of the request, add callbacks for sending request data
if (_requestMessage.Content != null)
{
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Read,
sendCallback,
easyGCHandle,
ref _callbackHandle);
Interop.Http.RegisterSeekCallback(
_easyHandle,
seekCallback,
easyGCHandle,
ref _callbackHandle);
}
// If we're expecting any data in response, add a callback for receiving body data
if (_requestMessage.Method != HttpMethod.Head)
{
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Write,
receiveBodyCallback,
easyGCHandle,
ref _callbackHandle);
}
}
internal CURLcode SetSslCtxCallback(SslCtxCallback callback, IntPtr userPointer)
{
if (_callbackHandle == null)
{
_callbackHandle = new SafeCallbackHandle();
}
CURLcode result = Interop.Http.RegisterSslCtxCallback(_easyHandle, callback, userPointer, ref _callbackHandle);
return result;
}
private static void AddRequestHeaders(HttpHeaders headers, SafeCurlSListHandle handle)
{
foreach (KeyValuePair<string, IEnumerable<string>> header in headers)
{
string headerValue = headers.GetHeaderString(header.Key);
string headerKeyAndValue = string.IsNullOrEmpty(headerValue) ?
header.Key + ";" : // semicolon used by libcurl to denote empty value that should be sent
header.Key + ": " + headerValue;
if (!Interop.Http.SListAppend(handle, headerKeyAndValue))
{
throw CreateHttpRequestException();
}
}
}
internal void SetCurlOption(CURLoption option, string value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionString(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, long value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionLong(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, IntPtr value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, SafeHandle value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value));
}
internal sealed class SendTransferState
{
internal readonly byte[] _buffer = new byte[RequestBufferSize]; // PERF TODO: Determine if this should be optimized to start smaller and grow
internal int _offset;
internal int _count;
internal Task<int> _task;
internal void SetTaskOffsetCount(Task<int> task, int offset, int count)
{
Debug.Assert(offset >= 0, "Offset should never be negative");
Debug.Assert(count >= 0, "Count should never be negative");
Debug.Assert(offset <= count, "Offset should never be greater than count");
_task = task;
_offset = offset;
_count = count;
}
}
[Conditional(VerboseDebuggingConditional)]
private void VerboseTrace(string text = null, [CallerMemberName] string memberName = null)
{
CurlHandler.VerboseTrace(text, memberName, easy: this, agent: null);
}
}
}
}
| |
// Copyright (c) rubicon IT GmbH, www.rubicon.eu
//
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership. rubicon licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Linq.Expressions;
using TITcs.SharePoint.Query.LinqProvider.Clauses;
using TITcs.SharePoint.Query.LinqProvider.Clauses.Expressions;
using TITcs.SharePoint.Query.LinqProvider.Clauses.ExpressionTreeVisitors;
using TITcs.SharePoint.Query.LinqProvider.Clauses.ResultOperators;
using TITcs.SharePoint.Query.LinqProvider.Clauses.StreamedData;
using TITcs.SharePoint.Query.LinqProvider.Parsing.Structure;
using TITcs.SharePoint.Query.SharedSource.Utilities;
namespace TITcs.SharePoint.Query.LinqProvider
{
/// <summary>
/// Provides an abstraction of an expression tree created for a LINQ query. <see cref="QueryModel"/> instances are passed to LINQ providers based
/// on re-linq via <see cref="IQueryExecutor"/>, but you can also use <see cref="QueryParser"/> to parse an expression tree by hand or construct
/// a <see cref="QueryModel"/> manually via its constructor.
/// </summary>
/// <remarks>
/// The different parts of the query are mapped to clauses, see <see cref="MainFromClause"/>, <see cref="BodyClauses"/>, and
/// <see cref="SelectClause"/>. The simplest way to process all the clauses belonging to a <see cref="QueryModel"/> is by implementing
/// <see cref="IQueryModelVisitor"/> (or deriving from <see cref="QueryModelVisitorBase"/>) and calling <see cref="Accept"/>.
/// </remarks>
public sealed class QueryModel
{
private readonly UniqueIdentifierGenerator _uniqueIdentifierGenerator;
private MainFromClause _mainFromClause;
private SelectClause _selectClause;
/// <summary>
/// Initializes a new instance of <see cref="QueryModel"/>
/// </summary>
/// <param name="mainFromClause">The <see cref="Clauses.MainFromClause"/> of the query. This is the starting point of the query, generating items
/// that are filtered and projected by the query.</param>
/// <param name="selectClause">The <see cref="SelectClause"/> of the query. This is the end point of
/// the query, it defines what is actually returned for each of the items coming from the <see cref="MainFromClause"/> and passing the
/// <see cref="BodyClauses"/>. After it, only the <see cref="ResultOperators"/> modify the result of the query.</param>
public QueryModel (MainFromClause mainFromClause, SelectClause selectClause)
{
ArgumentUtility.CheckNotNull ("mainFromClause", mainFromClause);
ArgumentUtility.CheckNotNull ("selectClause", selectClause);
_uniqueIdentifierGenerator = new UniqueIdentifierGenerator();
MainFromClause = mainFromClause;
SelectClause = selectClause;
BodyClauses = new ObservableCollection<IBodyClause>();
BodyClauses.CollectionChanged += BodyClauses_CollectionChanged;
ResultOperators = new ObservableCollection<ResultOperatorBase>();
ResultOperators.CollectionChanged += ResultOperators_CollectionChanged;
}
public Type ResultTypeOverride { get; set; }
public Type GetResultType ()
{
return GetOutputDataInfo ().DataType;
}
/// <summary>
/// Gets an <see cref="IStreamedDataInfo"/> object describing the data streaming out of this <see cref="QueryModel"/>. If a query ends with
/// the <see cref="SelectClause"/>, this corresponds to <see cref="Clauses.SelectClause.GetOutputDataInfo"/>. If a query has
/// <see cref="QueryModel.ResultOperators"/>, the data is further modified by those operators.
/// </summary>
/// <returns>Gets a <see cref="IStreamedDataInfo"/> object describing the data streaming out of this <see cref="QueryModel"/>.</returns>
/// <remarks>
/// The data streamed from a <see cref="QueryModel"/> is often of type <see cref="IQueryable{T}"/> instantiated
/// with a specific item type, unless the
/// query ends with a <see cref="ResultOperatorBase"/>. For example, if the query ends with a <see cref="CountResultOperator"/>, the
/// result type will be <see cref="int"/>.
/// </remarks>
public IStreamedDataInfo GetOutputDataInfo ()
{
var outputDataInfo = ResultOperators
.Aggregate ((IStreamedDataInfo) SelectClause.GetOutputDataInfo (), (current, resultOperator) => resultOperator.GetOutputDataInfo (current));
if (ResultTypeOverride != null)
return outputDataInfo.AdjustDataType (ResultTypeOverride);
else
return outputDataInfo;
}
/// <summary>
/// Gets or sets the query's <see cref="Clauses.MainFromClause"/>. This is the starting point of the query, generating items that are processed by
/// the <see cref="BodyClauses"/> and projected or grouped by the <see cref="SelectClause"/>.
/// </summary>
public MainFromClause MainFromClause
{
get { return _mainFromClause; }
set
{
ArgumentUtility.CheckNotNull ("value", value);
_mainFromClause = value;
_uniqueIdentifierGenerator.AddKnownIdentifier (value.ItemName);
}
}
/// <summary>
/// Gets or sets the query's select clause. This is the end point of the query, it defines what is actually returned for each of the
/// items coming from the <see cref="MainFromClause"/> and passing the <see cref="BodyClauses"/>. After it, only the <see cref="ResultOperators"/>
/// modify the result of the query.
/// </summary>
public SelectClause SelectClause
{
get { return _selectClause; }
set
{
ArgumentUtility.CheckNotNull ("value", value);
_selectClause = value;
}
}
/// <summary>
/// Gets a collection representing the query's body clauses. Body clauses take the items generated by the <see cref="MainFromClause"/>,
/// filtering (<see cref="WhereClause"/>), ordering (<see cref="OrderByClause"/>), augmenting (<see cref="AdditionalFromClause"/>), or otherwise
/// processing them before they are passed to the <see cref="SelectClause"/>.
/// </summary>
public ObservableCollection<IBodyClause> BodyClauses { get; private set; }
/// <summary>
/// Gets the result operators attached to this <see cref="SelectClause"/>. Result operators modify the query's result set, aggregating,
/// filtering, or otherwise processing the result before it is returned.
/// </summary>
public ObservableCollection<ResultOperatorBase> ResultOperators { get; private set; }
/// <summary>
/// Gets the <see cref="UniqueIdentifierGenerator"/> which is used by the <see cref="QueryModel"/>.
/// </summary>
/// <returns></returns>
public UniqueIdentifierGenerator GetUniqueIdentfierGenerator ()
{
return _uniqueIdentifierGenerator;
}
private void ResultOperators_CollectionChanged (object sender, NotifyCollectionChangedEventArgs e)
{
ArgumentUtility.CheckNotNull ("e", e);
ArgumentUtility.CheckItemsNotNullAndType ("e.NewItems", e.NewItems, typeof (ResultOperatorBase));
}
/// <summary>
/// Accepts an implementation of <see cref="IQueryModelVisitor"/> or <see cref="QueryModelVisitorBase"/>, as defined by the Visitor pattern.
/// </summary>
public void Accept (IQueryModelVisitor visitor)
{
ArgumentUtility.CheckNotNull ("visitor", visitor);
visitor.VisitQueryModel (this);
}
/// <summary>
/// Returns a <see cref="System.String"/> representation of this <see cref="QueryModel"/>.
/// </summary>
public override string ToString ()
{
string mainQueryString;
if (IsIdentityQuery ())
{
mainQueryString = FormattingExpressionTreeVisitor.Format (MainFromClause.FromExpression);
}
else
{
mainQueryString = MainFromClause + BodyClauses.Aggregate ("", (s, b) => s + " " + b) + " " + SelectClause;
}
return ResultOperators.Aggregate (mainQueryString, (s, r) => s + " => " + r);
}
/// <summary>
/// Clones this <see cref="QueryModel"/>, returning a new <see cref="QueryModel"/> equivalent to this instance, but with its clauses being
/// clones of this instance's clauses. Any <see cref="QuerySourceReferenceExpression"/> in the cloned clauses that points back to another clause
/// in this <see cref="QueryModel"/> (including its subqueries) is adjusted to point to the respective clones in the cloned
/// <see cref="QueryModel"/>. Any subquery nested in the <see cref="QueryModel"/> is also cloned.
/// </summary>
public QueryModel Clone ()
{
return Clone (new QuerySourceMapping());
}
/// <summary>
/// Clones this <see cref="QueryModel"/>, returning a new <see cref="QueryModel"/> equivalent to this instance, but with its clauses being
/// clones of this instance's clauses. Any <see cref="QuerySourceReferenceExpression"/> in the cloned clauses that points back to another clause
/// in this <see cref="QueryModel"/> (including its subqueries) is adjusted to point to the respective clones in the cloned
/// <see cref="QueryModel"/>. Any subquery nested in the <see cref="QueryModel"/> is also cloned.
/// </summary>
/// <param name="querySourceMapping">The <see cref="QuerySourceMapping"/> defining how to adjust instances of
/// <see cref="QuerySourceReferenceExpression"/> in the cloned <see cref="QueryModel"/>. If there is a <see cref="QuerySourceReferenceExpression"/>
/// that points out of the <see cref="QueryModel"/> being cloned, specify its replacement via this parameter. At the end of the cloning process,
/// this object maps all the clauses in this original <see cref="QueryModel"/> to the clones created in the process.
/// </param>
public QueryModel Clone (QuerySourceMapping querySourceMapping)
{
ArgumentUtility.CheckNotNull ("querySourceMapping", querySourceMapping);
var cloneContext = new CloneContext (querySourceMapping);
var queryModelBuilder = new QueryModelBuilder();
queryModelBuilder.AddClause (MainFromClause.Clone (cloneContext));
foreach (var bodyClause in BodyClauses)
queryModelBuilder.AddClause (bodyClause.Clone (cloneContext));
queryModelBuilder.AddClause (SelectClause.Clone (cloneContext));
foreach (var resultOperator in ResultOperators)
{
var resultOperatorClone = resultOperator.Clone (cloneContext);
queryModelBuilder.AddResultOperator (resultOperatorClone);
}
var clone = queryModelBuilder.Build ();
clone.TransformExpressions (ex => CloningExpressionTreeVisitor.AdjustExpressionAfterCloning (ex, cloneContext.QuerySourceMapping));
clone.ResultTypeOverride = ResultTypeOverride;
return clone;
}
/// <summary>
/// Transforms all the expressions in this <see cref="QueryModel"/>'s clauses via the given <paramref name="transformation"/> delegate.
/// </summary>
/// <param name="transformation">The transformation object. This delegate is called for each <see cref="Expression"/> within this
/// <see cref="QueryModel"/>, and those expressions will be replaced with what the delegate returns.</param>
public void TransformExpressions (Func<Expression, Expression> transformation)
{
ArgumentUtility.CheckNotNull ("transformation", transformation);
MainFromClause.TransformExpressions (transformation);
foreach (var bodyClause in BodyClauses)
bodyClause.TransformExpressions (transformation);
SelectClause.TransformExpressions (transformation);
foreach (var resultOperator in ResultOperators)
resultOperator.TransformExpressions (transformation);
}
/// <summary>
/// Returns a new name with the given prefix. The name is different from that of any <see cref="FromClauseBase"/> added
/// in the <see cref="QueryModel"/>. Note that clause names that are changed after the clause is added as well as names of other clauses
/// than from clauses are not considered when determining "unique" names. Use names only for readability and debugging, not
/// for uniquely identifying clauses.
/// </summary>
public string GetNewName (string prefix)
{
ArgumentUtility.CheckNotNullOrEmpty ("prefix", prefix);
return _uniqueIdentifierGenerator.GetUniqueIdentifier (prefix);
}
private void BodyClauses_CollectionChanged (object sender, NotifyCollectionChangedEventArgs e)
{
ArgumentUtility.CheckNotNull ("e", e);
ArgumentUtility.CheckItemsNotNullAndType ("e.NewItems", e.NewItems, typeof (IBodyClause));
if (e.NewItems != null)
{
foreach (var fromClause in e.NewItems.OfType<FromClauseBase>())
_uniqueIdentifierGenerator.AddKnownIdentifier (fromClause.ItemName);
}
}
/// <summary>
/// Executes this <see cref="QueryModel"/> via the given <see cref="IQueryExecutor"/>. By default, this indirectly calls
/// <see cref="IQueryExecutor.ExecuteCollection{T}"/>, but this can be modified by the <see cref="ResultOperators"/>.
/// </summary>
/// <param name="executor">The <see cref="IQueryExecutor"/> to use for executing this query.</param>
public IStreamedData Execute (IQueryExecutor executor)
{
ArgumentUtility.CheckNotNull ("executor", executor);
var dataInfo = GetOutputDataInfo();
return dataInfo.ExecuteQueryModel (this, executor);
}
/// <summary>
/// Determines whether this <see cref="QueryModel"/> represents an identity query. An identity query is a query without any body clauses
/// whose <see cref="SelectClause"/> selects exactly the items produced by its <see cref="MainFromClause"/>. An identity query can have
/// <see cref="ResultOperators"/>.
/// </summary>
/// <returns>
/// <see langword="true" /> if this <see cref="QueryModel"/> represents an identity query; otherwise, <see langword="false" />.
/// </returns>
/// <example>
/// An example for an identity query is the subquery in that is produced for the <see cref="Clauses.SelectClause.Selector"/> in the following
/// query:
/// <code>
/// from order in ...
/// select order.OrderItems.Count()
/// </code>
/// In this query, the <see cref="Clauses.SelectClause.Selector"/> will become a <see cref="SubQueryExpression"/> because
/// <see cref="Enumerable.Count{TSource}(System.Collections.Generic.IEnumerable{TSource})"/> is treated as a query operator. The
/// <see cref="QueryModel"/> in that <see cref="SubQueryExpression"/> has no <see cref="BodyClauses"/> and a trivial <see cref="SelectClause"/>,
/// so its <see cref="IsIdentityQuery"/> method returns <see langword="true" />. The outer <see cref="QueryModel"/>, on the other hand, does not
/// have a trivial <see cref="SelectClause"/>, so its <see cref="IsIdentityQuery"/> method returns <see langword="false" />.
/// </example>
public bool IsIdentityQuery ()
{
return BodyClauses.Count == 0
&& SelectClause.Selector is QuerySourceReferenceExpression
&& ((QuerySourceReferenceExpression) SelectClause.Selector).ReferencedQuerySource == MainFromClause;
}
/// <summary>
/// Creates a new <see cref="QueryModel"/> that has this <see cref="QueryModel"/> as a sub-query in its <see cref="MainFromClause"/>.
/// </summary>
/// <param name="itemName">The name of the new <see cref="QueryModel"/>'s <see cref="FromClauseBase.ItemName"/>.</param>
/// <returns>A new <see cref="QueryModel"/> whose <see cref="MainFromClause"/>'s <see cref="FromClauseBase.FromExpression"/> is a
/// <see cref="SubQueryExpression"/> that holds this <see cref="QueryModel"/> instance.</returns>
public QueryModel ConvertToSubQuery (string itemName)
{
ArgumentUtility.CheckNotNullOrEmpty ("itemName", itemName);
var outputDataInfo = GetOutputDataInfo() as StreamedSequenceInfo;
if (outputDataInfo == null)
{
var message = string.Format (
"The query must return a sequence of items, but it selects a single object of type '{0}'.",
GetOutputDataInfo ().DataType);
throw new InvalidOperationException (message);
}
// from x in (sourceItemQuery)
// select x
var mainFromClause = new MainFromClause (
itemName,
outputDataInfo.ResultItemType,
new SubQueryExpression (this));
var selectClause = new SelectClause (new QuerySourceReferenceExpression (mainFromClause));
return new QueryModel (mainFromClause, selectClause);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using Internal.LowLevelLinq;
namespace System.Reflection.Runtime.BindingFlagSupport
{
/// <summary>
/// Extension methods offering source-code compatibility with certain instance methods of <see cref="System.Type"/> on other platforms.
/// </summary>
internal static class LowLevelTypeExtensions
{
/// <summary>
/// Searches for the constructors defined for the current Type, using the specified BindingFlags.
/// </summary>
/// <param name="type">Type to retrieve constructors for</param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted.
/// -or-
/// Zero, to return null. </param>
/// <returns>An array of ConstructorInfo objects representing all constructors defined for the current Type that match the specified binding constraints, including the type initializer if it is defined. Returns an empty array of type ConstructorInfo if no constructors are defined for the current Type, if none of the defined constructors match the binding constraints, or if the current Type represents a type parameter in the definition of a generic type or generic method.</returns>
public static ConstructorInfo[] GetConstructors(Type type, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<ConstructorInfo> constructors = type.GetMembers<ConstructorInfo>(MemberEnumerator.AnyName, bindingAttr);
return constructors.ToArray();
}
/// <summary>
/// Returns the EventInfo object representing the specified event, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of an event which is declared or inherited by the current Type. </param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted.
/// -or-
/// Zero, to return null. </param>
/// <returns>The object representing the specified event that is declared or inherited by the current Type, if found; otherwise, null.</returns>
public static EventInfo GetEvent(Type type, string name, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<EventInfo> events = MemberEnumerator.GetMembers<EventInfo>(type, name, bindingAttr);
return Disambiguate(events);
}
/// <summary>
/// Searches for events that are declared or inherited by the current Type, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted.
/// -or-
/// Zero, to return null. </param>
/// <returns>An array of EventInfo objects representing all events that are declared or inherited by the current Type that match the specified binding constraints.
/// -or-
/// An empty array of type EventInfo, if the current Type does not have events, or if none of the events match the binding constraints.</returns>
public static EventInfo[] GetEvents(Type type, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<EventInfo> events = MemberEnumerator.GetMembers<EventInfo>(type, MemberEnumerator.AnyName, bindingAttr);
return events.ToArray();
}
/// <summary>
/// Searches for the specified field, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of the data field to get. </param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted.
/// -or-
/// Zero, to return null.</param>
/// <returns>An object representing the field that matches the specified requirements, if found; otherwise, null.</returns>
public static FieldInfo GetField(Type type, string name, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<FieldInfo> fields = MemberEnumerator.GetMembers<FieldInfo>(type, name, bindingAttr);
return Disambiguate(fields);
}
/// <summary>
/// Searches for the fields defined for the current Type, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted
/// -or-
/// Zero, to return an empty array. </param>
/// <returns>An array of FieldInfo objects representing all fields defined for the current Type that match the specified binding constraints.
/// -or-
/// An empty array of type FieldInfo, if no fields are defined for the current Type, or if none of the defined fields match the binding constraints.</returns>
public static FieldInfo[] GetFields(Type type, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
return MemberEnumerator.GetMembers<FieldInfo>(type, MemberEnumerator.AnyName, bindingAttr).ToArray();
}
/// <summary>
/// Searches for the public members with the specified name.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name"> The string containing the name of the public members to get. </param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted
/// -or-
/// Zero, to return an empty array. </param>
/// <returns>An array of MemberInfo objects representing the public members with the specified name, if found; otherwise, an empty array.</returns>
public static MemberInfo[] GetMember(Type type, string name, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
LowLevelList<MemberInfo> members = GetMembers(type, name, bindingAttr);
return members.ToArray();
}
/// <summary>
/// Searches for the members defined for the current Type, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted
/// -or-
/// Zero, to return an empty array. </param>
/// <returns>An array of MemberInfo objects representing all members defined for the current Type that match the specified binding constraints.
/// -or-
/// An empty array of type MemberInfo, if no members are defined for the current Type, or if none of the defined members match the binding constraints.</returns>
public static MemberInfo[] GetMembers(Type type, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
LowLevelList<MemberInfo> members = GetMembers(type, MemberEnumerator.AnyName, bindingAttr);
return members.ToArray();
}
/// <summary>
/// Searches for the specified method, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of the method to get.</param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted
/// -or-
/// Zero, to return null. </param>
/// <returns>An object representing the method that matches the specified requirements, if found; otherwise, null.</returns>
public static MethodInfo GetMethod(Type type, string name, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<MethodInfo> methods = MemberEnumerator.GetMembers<MethodInfo>(type, name, bindingAttr);
return Disambiguate(methods);
}
/// <summary>
/// Returns all the public methods of the current Type.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted
/// -or-
/// Zero, to return an empty array. </param>
/// <returns>An array of MethodInfo objects representing all the public methods defined for the current Type
/// -or-
/// An empty array of type MethodInfo, if no public methods are defined for the current Type.</returns>
public static MethodInfo[] GetMethods(Type type, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<MethodInfo> methods = MemberEnumerator.GetMembers<MethodInfo>(type, MemberEnumerator.AnyName, bindingAttr);
return methods.ToArray();
}
/// <summary>
/// Searches for the specified method, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of the method to get. </param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted
/// -or-
/// Zero, to return an empty array. </param>
/// <returns>An array of MethodInfo objects representing all the public methods defined for the current Type
/// -or-
/// An empty array of type MethodInfo, if no public methods are defined for the current Type.</returns>
public static MethodInfo[] GetMethods(Type type, string name, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<MethodInfo> methods = MemberEnumerator.GetMembers<MethodInfo>(type, name, bindingAttr);
return methods.ToArray();
}
/// <summary>
/// Searches for the specified nested type, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of the nested type to get. </param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted
/// -or-
/// Zero, to return null. </param>
/// <returns>An object representing the nested type that matches the specified requirements, if found; otherwise, null.</returns>
public static Type GetNestedType(Type type, string name, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<TypeInfo> nestedTypes = MemberEnumerator.GetMembers<TypeInfo>(type, name, bindingAttr);
TypeInfo nestedType = Disambiguate(nestedTypes);
return nestedType == null ? null : nestedType.AsType();
}
/// <summary>
/// Searches for the types nested in the current Type, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted -or- Zero, to return null. </param>
/// <returns>An array of Type objects representing all the types nested in the current Type that match the specified binding constraints (the search is not recursive), or an empty array of type Type, if no nested types are found that match the binding constraints.</returns>
public static Type[] GetNestedTypes(Type type, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<TypeInfo> types = MemberEnumerator.GetMembers<TypeInfo>(type, MemberEnumerator.AnyName, bindingAttr);
return types.Select(t => t.AsType()).ToArray();
}
/// <summary>
/// Searches for the properties of the current Type, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted -or- Zero, to return null. </param>
/// <returns>An array of PropertyInfo objects representing all properties of the current Type that match the specified binding constraints.
/// -or-
/// An empty array of type PropertyInfo, if the current Type does not have properties, or if none of the properties match the binding constraints.</returns>
public static PropertyInfo[] GetProperties(this Type type, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<PropertyInfo> properties = MemberEnumerator.GetMembers<PropertyInfo>(type, MemberEnumerator.AnyName, bindingAttr);
return properties.ToArray();
}
/// <summary>
/// Searches for the specified property, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of the property to get. </param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted
/// -or-
/// Zero, to return an empty array. </param>
/// <returns>An array of PropertyInfo objects representing all the public property defined for the current Type
/// -or-
/// An empty array of type PropertyInfo, if no properties matching the constraints are found.</returns>
public static PropertyInfo[] GetProperties(this Type type, string name, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<PropertyInfo> properties = MemberEnumerator.GetMembers<PropertyInfo>(type, name, bindingAttr);
return properties.ToArray();
}
/// <summary>
/// Searches for the specified property, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of the property to get. </param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted.
/// -or-
/// Zero, to return null. </param>
/// <returns>A bitmask comprised of one or more BindingFlags that specify how the search is conducted.
/// -or-
/// Zero, to return null. </returns>
public static PropertyInfo GetProperty(Type type, string name, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<PropertyInfo> properties = MemberEnumerator.GetMembers<PropertyInfo>(type, name, bindingAttr);
return Disambiguate(properties);
}
private static LowLevelList<MemberInfo> GetMembers(Type type, object nameFilterOrAnyName, BindingFlags bindingAttr)
{
LowLevelList<MemberInfo> members = new LowLevelList<MemberInfo>();
members.AddRange(MemberEnumerator.GetMembers<MethodInfo>(type, nameFilterOrAnyName, bindingAttr));
members.AddRange(MemberEnumerator.GetMembers<ConstructorInfo>(type, nameFilterOrAnyName, bindingAttr));
members.AddRange(MemberEnumerator.GetMembers<PropertyInfo>(type, nameFilterOrAnyName, bindingAttr));
members.AddRange(MemberEnumerator.GetMembers<EventInfo>(type, nameFilterOrAnyName, bindingAttr));
members.AddRange(MemberEnumerator.GetMembers<FieldInfo>(type, nameFilterOrAnyName, bindingAttr));
members.AddRange(MemberEnumerator.GetMembers<TypeInfo>(type, nameFilterOrAnyName, bindingAttr));
return members;
}
private static TypeInfo GetTypeInfoOrThrow(Type type, string parameterName = "type")
{
Debug.Assert(type != null);
TypeInfo typeInfo = type.GetTypeInfo();
if (typeInfo == null)
{
throw new ArgumentException(SR.TypeIsNotReflectable, parameterName);
}
return typeInfo;
}
private static T Disambiguate<T>(IEnumerable<T> members) where T : MemberInfo
{
IEnumerator<T> enumerator = members.GetEnumerator();
if (!enumerator.MoveNext())
{
return null;
}
T result = enumerator.Current;
if (!enumerator.MoveNext())
{
return result;
}
T anotherResult = enumerator.Current;
if (anotherResult.DeclaringType.Equals(result.DeclaringType))
{
throw new AmbiguousMatchException();
}
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Routing.Template;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Routing
{
internal sealed partial class DefaultLinkGenerator : LinkGenerator, IDisposable
{
private readonly TemplateBinderFactory _binderFactory;
private readonly ILogger<DefaultLinkGenerator> _logger;
private readonly IServiceProvider _serviceProvider;
// A LinkOptions object initialized with the values from RouteOptions
// Used when the user didn't specify something more global.
private readonly LinkOptions _globalLinkOptions;
// Caches TemplateBinder instances
private readonly DataSourceDependentCache<ConcurrentDictionary<RouteEndpoint, TemplateBinder>> _cache;
// Used to initialize TemplateBinder instances
private readonly Func<RouteEndpoint, TemplateBinder> _createTemplateBinder;
public DefaultLinkGenerator(
ParameterPolicyFactory parameterPolicyFactory,
TemplateBinderFactory binderFactory,
EndpointDataSource dataSource,
IOptions<RouteOptions> routeOptions,
ILogger<DefaultLinkGenerator> logger,
IServiceProvider serviceProvider)
{
_binderFactory = binderFactory;
_logger = logger;
_serviceProvider = serviceProvider;
// We cache TemplateBinder instances per-Endpoint for performance, but we want to wipe out
// that cache is the endpoints change so that we don't allow unbounded memory growth.
_cache = new DataSourceDependentCache<ConcurrentDictionary<RouteEndpoint, TemplateBinder>>(dataSource, (_) =>
{
// We don't eagerly fill this cache because there's no real reason to. Unlike URL matching, we don't
// need to build a big data structure up front to be correct.
return new ConcurrentDictionary<RouteEndpoint, TemplateBinder>();
});
// Cached to avoid per-call allocation of a delegate on lookup.
_createTemplateBinder = CreateTemplateBinder;
_globalLinkOptions = new LinkOptions()
{
AppendTrailingSlash = routeOptions.Value.AppendTrailingSlash,
LowercaseQueryStrings = routeOptions.Value.LowercaseQueryStrings,
LowercaseUrls = routeOptions.Value.LowercaseUrls,
};
}
public override string? GetPathByAddress<TAddress>(
HttpContext httpContext,
TAddress address,
RouteValueDictionary values,
RouteValueDictionary? ambientValues = default,
PathString? pathBase = default,
FragmentString fragment = default,
LinkOptions? options = null)
{
if (httpContext == null)
{
throw new ArgumentNullException(nameof(httpContext));
}
var endpoints = GetEndpoints(address);
if (endpoints.Count == 0)
{
return null;
}
return GetPathByEndpoints(
httpContext,
endpoints,
values,
ambientValues,
pathBase ?? httpContext.Request.PathBase,
fragment,
options);
}
public override string? GetPathByAddress<TAddress>(
TAddress address,
RouteValueDictionary values,
PathString pathBase = default,
FragmentString fragment = default,
LinkOptions? options = null)
{
var endpoints = GetEndpoints(address);
if (endpoints.Count == 0)
{
return null;
}
return GetPathByEndpoints(
httpContext: null,
endpoints,
values,
ambientValues: null,
pathBase: pathBase,
fragment: fragment,
options: options);
}
public override string? GetUriByAddress<TAddress>(
HttpContext httpContext,
TAddress address,
RouteValueDictionary values,
RouteValueDictionary? ambientValues = default,
string? scheme = default,
HostString? host = default,
PathString? pathBase = default,
FragmentString fragment = default,
LinkOptions? options = null)
{
if (httpContext == null)
{
throw new ArgumentNullException(nameof(httpContext));
}
var endpoints = GetEndpoints(address);
if (endpoints.Count == 0)
{
return null;
}
return GetUriByEndpoints(
endpoints,
values,
ambientValues,
scheme ?? httpContext.Request.Scheme,
host ?? httpContext.Request.Host,
pathBase ?? httpContext.Request.PathBase,
fragment,
options);
}
public override string? GetUriByAddress<TAddress>(
TAddress address,
RouteValueDictionary values,
string? scheme,
HostString host,
PathString pathBase = default,
FragmentString fragment = default,
LinkOptions? options = null)
{
if (string.IsNullOrEmpty(scheme))
{
throw new ArgumentException("A scheme must be provided.", nameof(scheme));
}
if (!host.HasValue)
{
throw new ArgumentException("A host must be provided.", nameof(host));
}
var endpoints = GetEndpoints(address);
if (endpoints.Count == 0)
{
return null;
}
return GetUriByEndpoints(
endpoints,
values,
ambientValues: null,
scheme: scheme,
host: host,
pathBase: pathBase,
fragment: fragment,
options: options);
}
private List<RouteEndpoint> GetEndpoints<TAddress>(TAddress address)
{
var addressingScheme = _serviceProvider.GetRequiredService<IEndpointAddressScheme<TAddress>>();
var endpoints = addressingScheme.FindEndpoints(address).OfType<RouteEndpoint>().ToList();
if (endpoints.Count == 0)
{
Log.EndpointsNotFound(_logger, address);
}
else
{
Log.EndpointsFound(_logger, address, endpoints);
}
return endpoints;
}
private string? GetPathByEndpoints(
HttpContext? httpContext,
List<RouteEndpoint> endpoints,
RouteValueDictionary values,
RouteValueDictionary? ambientValues,
PathString pathBase,
FragmentString fragment,
LinkOptions? options)
{
for (var i = 0; i < endpoints.Count; i++)
{
var endpoint = endpoints[i];
if (TryProcessTemplate(
httpContext: httpContext,
endpoint: endpoint,
values: values,
ambientValues: ambientValues,
options: options,
result: out var result))
{
var uri = UriHelper.BuildRelative(
pathBase,
result.path,
result.query,
fragment);
Log.LinkGenerationSucceeded(_logger, endpoints, uri);
return uri;
}
}
Log.LinkGenerationFailed(_logger, endpoints);
return null;
}
// Also called from DefaultLinkGenerationTemplate
public string? GetUriByEndpoints(
List<RouteEndpoint> endpoints,
RouteValueDictionary values,
RouteValueDictionary? ambientValues,
string scheme,
HostString host,
PathString pathBase,
FragmentString fragment,
LinkOptions? options)
{
for (var i = 0; i < endpoints.Count; i++)
{
var endpoint = endpoints[i];
if (TryProcessTemplate(
httpContext: null,
endpoint: endpoint,
values: values,
ambientValues: ambientValues,
options: options,
result: out var result))
{
var uri = UriHelper.BuildAbsolute(
scheme,
host,
pathBase,
result.path,
result.query,
fragment);
Log.LinkGenerationSucceeded(_logger, endpoints, uri);
return uri;
}
}
Log.LinkGenerationFailed(_logger, endpoints);
return null;
}
private TemplateBinder CreateTemplateBinder(RouteEndpoint endpoint)
{
return _binderFactory.Create(endpoint.RoutePattern);
}
// Internal for testing
internal TemplateBinder GetTemplateBinder(RouteEndpoint endpoint) => _cache.EnsureInitialized().GetOrAdd(endpoint, _createTemplateBinder);
// Internal for testing
internal bool TryProcessTemplate(
HttpContext? httpContext,
RouteEndpoint endpoint,
RouteValueDictionary values,
RouteValueDictionary? ambientValues,
LinkOptions? options,
out (PathString path, QueryString query) result)
{
var templateBinder = GetTemplateBinder(endpoint);
var templateValuesResult = templateBinder.GetValues(ambientValues, values);
if (templateValuesResult == null)
{
// We're missing one of the required values for this route.
result = default;
Log.TemplateFailedRequiredValues(_logger, endpoint, ambientValues, values);
return false;
}
if (!templateBinder.TryProcessConstraints(httpContext, templateValuesResult.CombinedValues, out var parameterName, out var constraint))
{
result = default;
Log.TemplateFailedConstraint(_logger, endpoint, parameterName, constraint, templateValuesResult.CombinedValues);
return false;
}
if (!templateBinder.TryBindValues(templateValuesResult.AcceptedValues, options, _globalLinkOptions, out result))
{
Log.TemplateFailedExpansion(_logger, endpoint, templateValuesResult.AcceptedValues);
return false;
}
Log.TemplateSucceeded(_logger, endpoint, result.path, result.query);
return true;
}
// Also called from DefaultLinkGenerationTemplate
public static RouteValueDictionary? GetAmbientValues(HttpContext? httpContext)
{
return httpContext?.Features.Get<IRouteValuesFeature>()?.RouteValues;
}
public void Dispose()
{
_cache.Dispose();
}
private static partial class Log
{
public static void EndpointsFound(ILogger logger, object? address, IEnumerable<Endpoint> endpoints)
{
// Checking level again to avoid allocation on the common path
if (logger.IsEnabled(LogLevel.Debug))
{
EndpointsFound(logger, endpoints.Select(e => e.DisplayName), address);
}
}
[LoggerMessage(100, LogLevel.Debug, "Found the endpoints {Endpoints} for address {Address}", EventName = "EndpointsFound", SkipEnabledCheck = true)]
private static partial void EndpointsFound(ILogger logger, IEnumerable<string?> endpoints, object? address);
[LoggerMessage(101, LogLevel.Debug, "No endpoints found for address {Address}", EventName = "EndpointsNotFound")]
public static partial void EndpointsNotFound(ILogger logger, object? address);
public static void TemplateSucceeded(ILogger logger, RouteEndpoint endpoint, PathString path, QueryString query)
=> TemplateSucceeded(logger, endpoint.RoutePattern.RawText, endpoint.DisplayName, path.Value, query.Value);
[LoggerMessage(102, LogLevel.Debug,
"Successfully processed template {Template} for {Endpoint} resulting in {Path} and {Query}",
EventName = "TemplateSucceeded")]
private static partial void TemplateSucceeded(ILogger logger, string? template, string? endpoint, string? path, string? query);
public static void TemplateFailedRequiredValues(ILogger logger, RouteEndpoint endpoint, RouteValueDictionary? ambientValues, RouteValueDictionary values)
{
// Checking level again to avoid allocation on the common path
if (logger.IsEnabled(LogLevel.Debug))
{
TemplateFailedRequiredValues(logger, endpoint.RoutePattern.RawText, endpoint.DisplayName, FormatRouteValues(ambientValues), FormatRouteValues(values), FormatRouteValues(endpoint.RoutePattern.Defaults));
}
}
[LoggerMessage(103, LogLevel.Debug,
"Failed to process the template {Template} for {Endpoint}. " +
"A required route value is missing, or has a different value from the required default values. " +
"Supplied ambient values {AmbientValues} and {Values} with default values {Defaults}",
EventName = "TemplateFailedRequiredValues",
SkipEnabledCheck = true)]
private static partial void TemplateFailedRequiredValues(ILogger logger, string? template, string? endpoint, string ambientValues, string values, string defaults);
public static void TemplateFailedConstraint(ILogger logger, RouteEndpoint endpoint, string? parameterName, IRouteConstraint? constraint, RouteValueDictionary values)
{
// Checking level again to avoid allocation on the common path
if (logger.IsEnabled(LogLevel.Debug))
{
TemplateFailedConstraint(logger, endpoint.RoutePattern.RawText, endpoint.DisplayName, constraint, parameterName, FormatRouteValues(values));
}
}
[LoggerMessage(107, LogLevel.Debug,
"Failed to process the template {Template} for {Endpoint}. " +
"The constraint {Constraint} for parameter {ParameterName} failed with values {Values}",
EventName = "TemplateFailedConstraint",
SkipEnabledCheck = true)]
private static partial void TemplateFailedConstraint(ILogger logger, string? template, string? endpoint, IRouteConstraint? constraint, string? parameterName, string values);
public static void TemplateFailedExpansion(ILogger logger, RouteEndpoint endpoint, RouteValueDictionary values)
{
// Checking level again to avoid allocation on the common path
if (logger.IsEnabled(LogLevel.Debug))
{
TemplateFailedExpansion(logger, endpoint.RoutePattern.RawText, endpoint.DisplayName, FormatRouteValues(values));
}
}
[LoggerMessage(104, LogLevel.Debug,
"Failed to process the template {Template} for {Endpoint}. " +
"The failure occurred while expanding the template with values {Values} " +
"This is usually due to a missing or empty value in a complex segment",
EventName = "TemplateFailedExpansion",
SkipEnabledCheck = true)]
private static partial void TemplateFailedExpansion(ILogger logger, string? template, string? endpoint, string values);
public static void LinkGenerationSucceeded(ILogger logger, IEnumerable<Endpoint> endpoints, string uri)
{
// Checking level again to avoid allocation on the common path
if (logger.IsEnabled(LogLevel.Debug))
{
LinkGenerationSucceeded(logger, endpoints.Select(e => e.DisplayName), uri);
}
}
[LoggerMessage(105, LogLevel.Debug,
"Link generation succeeded for endpoints {Endpoints} with result {URI}",
EventName = "LinkGenerationSucceeded",
SkipEnabledCheck = true)]
private static partial void LinkGenerationSucceeded(ILogger logger, IEnumerable<string?> endpoints, string uri);
public static void LinkGenerationFailed(ILogger logger, IEnumerable<Endpoint> endpoints)
{
// Checking level again to avoid allocation on the common path
if (logger.IsEnabled(LogLevel.Debug))
{
LinkGenerationFailed(logger, endpoints.Select(e => e.DisplayName));
}
}
[LoggerMessage(106, LogLevel.Debug, "Link generation failed for endpoints {Endpoints}", EventName = "LinkGenerationFailed", SkipEnabledCheck = true)]
private static partial void LinkGenerationFailed(ILogger logger, IEnumerable<string?> endpoints);
// EXPENSIVE: should only be used at Debug and higher levels of logging.
private static string FormatRouteValues(IReadOnlyDictionary<string, object?>? values)
{
if (values == null || values.Count == 0)
{
return "{ }";
}
var builder = new StringBuilder();
builder.Append("{ ");
foreach (var kvp in values.OrderBy(kvp => kvp.Key))
{
builder.Append('"');
builder.Append(kvp.Key);
builder.Append('"');
builder.Append(':');
builder.Append(' ');
builder.Append('"');
builder.Append(kvp.Value);
builder.Append('"');
builder.Append(", ");
}
// Trim trailing ", "
builder.Remove(builder.Length - 2, 2);
builder.Append(" }");
return builder.ToString();
}
}
}
}
| |
// $ANTLR 3.1.2 abevformula.g 2011-01-22 19:07:24
// The variable 'variable' is assigned but its value is never used.
#pragma warning disable 219
// Unreachable code detected.
#pragma warning disable 162
using System.Collections.Generic;
using Antlr.Runtime;
using Stack = System.Collections.Generic.Stack<object>;
using List = System.Collections.IList;
using ArrayList = System.Collections.Generic.List<object>;
using Map = System.Collections.IDictionary;
using HashMap = System.Collections.Generic.Dictionary<object, object>;
using Antlr.Runtime.Tree;
using RewriteRuleITokenStream = Antlr.Runtime.Tree.RewriteRuleTokenStream;
public partial class abevformulaParser : Parser
{
internal static readonly string[] tokenNames = new string[] {
"<invalid>", "<EOR>", "<DOWN>", "<UP>", "FUNC", "STRING", "WORD", "WS", "','", "'['", "']'"
};
public const int EOF=-1;
public const int T__8=8;
public const int T__9=9;
public const int T__10=10;
public const int FUNC=4;
public const int STRING=5;
public const int WORD=6;
public const int WS=7;
// delegates
// delegators
public abevformulaParser( ITokenStream input )
: this( input, new RecognizerSharedState() )
{
}
public abevformulaParser( ITokenStream input, RecognizerSharedState state )
: base( input, state )
{
this.state.ruleMemo = new System.Collections.Generic.Dictionary<int, int>[10+1];
InitializeTreeAdaptor();
if ( TreeAdaptor == null )
TreeAdaptor = new CommonTreeAdaptor();
}
// Implement this function in your helper file to use a custom tree adaptor
partial void InitializeTreeAdaptor();
ITreeAdaptor adaptor;
public ITreeAdaptor TreeAdaptor
{
get
{
return adaptor;
}
set
{
this.adaptor = value;
}
}
public override string[] TokenNames { get { return abevformulaParser.tokenNames; } }
public override string GrammarFileName { get { return "abevformula.g"; } }
public abevformulaParser.start_return startIt()
{
return this.start();
}
#region Rules
public class start_return : ParserRuleReturnScope
{
internal CommonTree tree;
public override object Tree { get { return tree; } }
}
// $ANTLR start "start"
// abevformula.g:22:0: start : funcwithparams ;
private abevformulaParser.start_return start( )
{
abevformulaParser.start_return retval = new abevformulaParser.start_return();
retval.start = input.LT(1);
int start_StartIndex = input.Index;
CommonTree root_0 = null;
abevformulaParser.funcwithparams_return funcwithparams1 = default(abevformulaParser.funcwithparams_return);
try
{
if ( state.backtracking>0 && AlreadyParsedRule(input, 1) ) { return retval; }
// abevformula.g:22:10: ( funcwithparams )
// abevformula.g:22:10: funcwithparams
{
root_0 = (CommonTree)adaptor.Nil();
PushFollow(Follow._funcwithparams_in_start100);
funcwithparams1=funcwithparams();
state._fsp--;
if (state.failed) return retval;
if ( state.backtracking == 0 ) adaptor.AddChild(root_0, funcwithparams1.Tree);
}
retval.stop = input.LT(-1);
if ( state.backtracking == 0 ) {
retval.tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.tree, retval.start, retval.stop);
}
}
catch ( RecognitionException re )
{
ReportError(re);
Recover(input,re);
retval.tree = (CommonTree)adaptor.ErrorNode(input, retval.start, input.LT(-1), re);
}
finally
{
if ( state.backtracking>0 ) { Memoize(input, 1, start_StartIndex); }
}
return retval;
}
// $ANTLR end "start"
public class funcwithparams_return : ParserRuleReturnScope
{
internal CommonTree tree;
public override object Tree { get { return tree; } }
}
// $ANTLR start "funcwithparams"
// abevformula.g:24:0: funcwithparams : '[' func ',' paramlist ']' -> ^( FUNC func paramlist ) ;
private abevformulaParser.funcwithparams_return funcwithparams( )
{
abevformulaParser.funcwithparams_return retval = new abevformulaParser.funcwithparams_return();
retval.start = input.LT(1);
int funcwithparams_StartIndex = input.Index;
CommonTree root_0 = null;
IToken char_literal2=null;
IToken char_literal4=null;
IToken char_literal6=null;
abevformulaParser.func_return func3 = default(abevformulaParser.func_return);
abevformulaParser.paramlist_return paramlist5 = default(abevformulaParser.paramlist_return);
CommonTree char_literal2_tree=null;
CommonTree char_literal4_tree=null;
CommonTree char_literal6_tree=null;
RewriteRuleITokenStream stream_9=new RewriteRuleITokenStream(adaptor,"token 9");
RewriteRuleITokenStream stream_8=new RewriteRuleITokenStream(adaptor,"token 8");
RewriteRuleITokenStream stream_10=new RewriteRuleITokenStream(adaptor,"token 10");
RewriteRuleSubtreeStream stream_func=new RewriteRuleSubtreeStream(adaptor,"rule func");
RewriteRuleSubtreeStream stream_paramlist=new RewriteRuleSubtreeStream(adaptor,"rule paramlist");
try
{
if ( state.backtracking>0 && AlreadyParsedRule(input, 2) ) { return retval; }
// abevformula.g:24:18: ( '[' func ',' paramlist ']' -> ^( FUNC func paramlist ) )
// abevformula.g:24:18: '[' func ',' paramlist ']'
{
char_literal2=(IToken)Match(input,9,Follow._9_in_funcwithparams109); if (state.failed) return retval;
if ( state.backtracking == 0 ) stream_9.Add(char_literal2);
PushFollow(Follow._func_in_funcwithparams111);
func3=func();
state._fsp--;
if (state.failed) return retval;
if ( state.backtracking == 0 ) stream_func.Add(func3.Tree);
char_literal4=(IToken)Match(input,8,Follow._8_in_funcwithparams113); if (state.failed) return retval;
if ( state.backtracking == 0 ) stream_8.Add(char_literal4);
PushFollow(Follow._paramlist_in_funcwithparams115);
paramlist5=paramlist();
state._fsp--;
if (state.failed) return retval;
if ( state.backtracking == 0 ) stream_paramlist.Add(paramlist5.Tree);
char_literal6=(IToken)Match(input,10,Follow._10_in_funcwithparams117); if (state.failed) return retval;
if ( state.backtracking == 0 ) stream_10.Add(char_literal6);
{
// AST REWRITE
// elements: func, paramlist
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
if ( state.backtracking == 0 ) {
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.Nil();
// 24:45: -> ^( FUNC func paramlist )
{
// abevformula.g:24:48: ^( FUNC func paramlist )
{
CommonTree root_1 = (CommonTree)adaptor.Nil();
root_1 = (CommonTree)adaptor.BecomeRoot((CommonTree)adaptor.Create(FUNC, "FUNC"), root_1);
adaptor.AddChild(root_1, stream_func.NextTree());
adaptor.AddChild(root_1, stream_paramlist.NextTree());
adaptor.AddChild(root_0, root_1);
}
}
retval.tree = root_0;
}
}
}
retval.stop = input.LT(-1);
if ( state.backtracking == 0 ) {
retval.tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.tree, retval.start, retval.stop);
}
}
catch ( RecognitionException re )
{
ReportError(re);
Recover(input,re);
retval.tree = (CommonTree)adaptor.ErrorNode(input, retval.start, input.LT(-1), re);
}
finally
{
if ( state.backtracking>0 ) { Memoize(input, 2, funcwithparams_StartIndex); }
}
return retval;
}
// $ANTLR end "funcwithparams"
public class func_return : ParserRuleReturnScope
{
internal CommonTree tree;
public override object Tree { get { return tree; } }
}
// $ANTLR start "func"
// abevformula.g:25:0: func : WORD ;
private abevformulaParser.func_return func( )
{
abevformulaParser.func_return retval = new abevformulaParser.func_return();
retval.start = input.LT(1);
int func_StartIndex = input.Index;
CommonTree root_0 = null;
IToken WORD7=null;
CommonTree WORD7_tree=null;
try
{
if ( state.backtracking>0 && AlreadyParsedRule(input, 3) ) { return retval; }
// abevformula.g:25:9: ( WORD )
// abevformula.g:25:9: WORD
{
root_0 = (CommonTree)adaptor.Nil();
WORD7=(IToken)Match(input,WORD,Follow._WORD_in_func135); if (state.failed) return retval;
if ( state.backtracking==0 ) {
WORD7_tree = (CommonTree)adaptor.Create(WORD7);
adaptor.AddChild(root_0, WORD7_tree);
}
}
retval.stop = input.LT(-1);
if ( state.backtracking == 0 ) {
retval.tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.tree, retval.start, retval.stop);
}
}
catch ( RecognitionException re )
{
ReportError(re);
Recover(input,re);
retval.tree = (CommonTree)adaptor.ErrorNode(input, retval.start, input.LT(-1), re);
}
finally
{
if ( state.backtracking>0 ) { Memoize(input, 3, func_StartIndex); }
}
return retval;
}
// $ANTLR end "func"
public class paramlist_return : ParserRuleReturnScope
{
internal CommonTree tree;
public override object Tree { get { return tree; } }
}
// $ANTLR start "paramlist"
// abevformula.g:26:0: paramlist : param ( ',' param )* -> ( param )+ ;
private abevformulaParser.paramlist_return paramlist( )
{
abevformulaParser.paramlist_return retval = new abevformulaParser.paramlist_return();
retval.start = input.LT(1);
int paramlist_StartIndex = input.Index;
CommonTree root_0 = null;
IToken char_literal9=null;
abevformulaParser.param_return param8 = default(abevformulaParser.param_return);
abevformulaParser.param_return param10 = default(abevformulaParser.param_return);
CommonTree char_literal9_tree=null;
RewriteRuleITokenStream stream_8=new RewriteRuleITokenStream(adaptor,"token 8");
RewriteRuleSubtreeStream stream_param=new RewriteRuleSubtreeStream(adaptor,"rule param");
try
{
if ( state.backtracking>0 && AlreadyParsedRule(input, 4) ) { return retval; }
// abevformula.g:26:13: ( param ( ',' param )* -> ( param )+ )
// abevformula.g:26:13: param ( ',' param )*
{
PushFollow(Follow._param_in_paramlist143);
param8=param();
state._fsp--;
if (state.failed) return retval;
if ( state.backtracking == 0 ) stream_param.Add(param8.Tree);
// abevformula.g:26:19: ( ',' param )*
for ( ; ; )
{
int alt1=2;
int LA1_0 = input.LA(1);
if ( (LA1_0==8) )
{
alt1=1;
}
switch ( alt1 )
{
case 1:
// abevformula.g:26:20: ',' param
{
char_literal9=(IToken)Match(input,8,Follow._8_in_paramlist146); if (state.failed) return retval;
if ( state.backtracking == 0 ) stream_8.Add(char_literal9);
PushFollow(Follow._param_in_paramlist148);
param10=param();
state._fsp--;
if (state.failed) return retval;
if ( state.backtracking == 0 ) stream_param.Add(param10.Tree);
}
break;
default:
goto loop1;
}
}
loop1:
;
{
// AST REWRITE
// elements: param
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
if ( state.backtracking == 0 ) {
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.Nil();
// 26:32: -> ( param )+
{
if ( !(stream_param.HasNext) )
{
throw new RewriteEarlyExitException();
}
while ( stream_param.HasNext )
{
adaptor.AddChild(root_0, stream_param.NextTree());
}
stream_param.Reset();
}
retval.tree = root_0;
}
}
}
retval.stop = input.LT(-1);
if ( state.backtracking == 0 ) {
retval.tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.tree, retval.start, retval.stop);
}
}
catch ( RecognitionException re )
{
ReportError(re);
Recover(input,re);
retval.tree = (CommonTree)adaptor.ErrorNode(input, retval.start, input.LT(-1), re);
}
finally
{
if ( state.backtracking>0 ) { Memoize(input, 4, paramlist_StartIndex); }
}
return retval;
}
// $ANTLR end "paramlist"
public class word_return : ParserRuleReturnScope
{
internal CommonTree tree;
public override object Tree { get { return tree; } }
}
// $ANTLR start "word"
// abevformula.g:27:0: word : WORD ;
private abevformulaParser.word_return word( )
{
abevformulaParser.word_return retval = new abevformulaParser.word_return();
retval.start = input.LT(1);
int word_StartIndex = input.Index;
CommonTree root_0 = null;
IToken WORD11=null;
CommonTree WORD11_tree=null;
try
{
if ( state.backtracking>0 && AlreadyParsedRule(input, 5) ) { return retval; }
// abevformula.g:27:9: ( WORD )
// abevformula.g:27:9: WORD
{
root_0 = (CommonTree)adaptor.Nil();
WORD11=(IToken)Match(input,WORD,Follow._WORD_in_word163); if (state.failed) return retval;
if ( state.backtracking==0 ) {
WORD11_tree = (CommonTree)adaptor.Create(WORD11);
adaptor.AddChild(root_0, WORD11_tree);
}
}
retval.stop = input.LT(-1);
if ( state.backtracking == 0 ) {
retval.tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.tree, retval.start, retval.stop);
}
}
catch ( RecognitionException re )
{
ReportError(re);
Recover(input,re);
retval.tree = (CommonTree)adaptor.ErrorNode(input, retval.start, input.LT(-1), re);
}
finally
{
if ( state.backtracking>0 ) { Memoize(input, 5, word_StartIndex); }
}
return retval;
}
// $ANTLR end "word"
public class sentence_return : ParserRuleReturnScope
{
internal CommonTree tree;
public override object Tree { get { return tree; } }
}
// $ANTLR start "sentence"
// abevformula.g:28:0: sentence : STRING ;
private abevformulaParser.sentence_return sentence( )
{
abevformulaParser.sentence_return retval = new abevformulaParser.sentence_return();
retval.start = input.LT(1);
int sentence_StartIndex = input.Index;
CommonTree root_0 = null;
IToken STRING12=null;
CommonTree STRING12_tree=null;
try
{
if ( state.backtracking>0 && AlreadyParsedRule(input, 6) ) { return retval; }
// abevformula.g:28:12: ( STRING )
// abevformula.g:28:12: STRING
{
root_0 = (CommonTree)adaptor.Nil();
STRING12=(IToken)Match(input,STRING,Follow._STRING_in_sentence171); if (state.failed) return retval;
if ( state.backtracking==0 ) {
STRING12_tree = (CommonTree)adaptor.Create(STRING12);
adaptor.AddChild(root_0, STRING12_tree);
}
}
retval.stop = input.LT(-1);
if ( state.backtracking == 0 ) {
retval.tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.tree, retval.start, retval.stop);
}
}
catch ( RecognitionException re )
{
ReportError(re);
Recover(input,re);
retval.tree = (CommonTree)adaptor.ErrorNode(input, retval.start, input.LT(-1), re);
}
finally
{
if ( state.backtracking>0 ) { Memoize(input, 6, sentence_StartIndex); }
}
return retval;
}
// $ANTLR end "sentence"
public class param_return : ParserRuleReturnScope
{
internal CommonTree tree;
public override object Tree { get { return tree; } }
}
// $ANTLR start "param"
// abevformula.g:29:0: param : ( word | sentence | funcwithparams );
private abevformulaParser.param_return param( )
{
abevformulaParser.param_return retval = new abevformulaParser.param_return();
retval.start = input.LT(1);
int param_StartIndex = input.Index;
CommonTree root_0 = null;
abevformulaParser.word_return word13 = default(abevformulaParser.word_return);
abevformulaParser.sentence_return sentence14 = default(abevformulaParser.sentence_return);
abevformulaParser.funcwithparams_return funcwithparams15 = default(abevformulaParser.funcwithparams_return);
try
{
if ( state.backtracking>0 && AlreadyParsedRule(input, 7) ) { return retval; }
// abevformula.g:29:10: ( word | sentence | funcwithparams )
int alt2=3;
switch ( input.LA(1) )
{
case WORD:
{
alt2=1;
}
break;
case STRING:
{
alt2=2;
}
break;
case 9:
{
alt2=3;
}
break;
default:
{
if (state.backtracking>0) {state.failed=true; return retval;}
NoViableAltException nvae = new NoViableAltException("", 2, 0, input);
throw nvae;
}
}
switch ( alt2 )
{
case 1:
// abevformula.g:29:10: word
{
root_0 = (CommonTree)adaptor.Nil();
PushFollow(Follow._word_in_param180);
word13=word();
state._fsp--;
if (state.failed) return retval;
if ( state.backtracking == 0 ) adaptor.AddChild(root_0, word13.Tree);
}
break;
case 2:
// abevformula.g:30:6: sentence
{
root_0 = (CommonTree)adaptor.Nil();
PushFollow(Follow._sentence_in_param188);
sentence14=sentence();
state._fsp--;
if (state.failed) return retval;
if ( state.backtracking == 0 ) adaptor.AddChild(root_0, sentence14.Tree);
}
break;
case 3:
// abevformula.g:31:6: funcwithparams
{
root_0 = (CommonTree)adaptor.Nil();
PushFollow(Follow._funcwithparams_in_param195);
funcwithparams15=funcwithparams();
state._fsp--;
if (state.failed) return retval;
if ( state.backtracking == 0 ) adaptor.AddChild(root_0, funcwithparams15.Tree);
}
break;
}
retval.stop = input.LT(-1);
if ( state.backtracking == 0 ) {
retval.tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.tree, retval.start, retval.stop);
}
}
catch ( RecognitionException re )
{
ReportError(re);
Recover(input,re);
retval.tree = (CommonTree)adaptor.ErrorNode(input, retval.start, input.LT(-1), re);
}
finally
{
if ( state.backtracking>0 ) { Memoize(input, 7, param_StartIndex); }
}
return retval;
}
// $ANTLR end "param"
#endregion Rules
#region Follow sets
static class Follow
{
public static readonly BitSet _funcwithparams_in_start100 = new BitSet(new ulong[]{0x2UL});
public static readonly BitSet _9_in_funcwithparams109 = new BitSet(new ulong[]{0x40UL});
public static readonly BitSet _func_in_funcwithparams111 = new BitSet(new ulong[]{0x100UL});
public static readonly BitSet _8_in_funcwithparams113 = new BitSet(new ulong[]{0x260UL});
public static readonly BitSet _paramlist_in_funcwithparams115 = new BitSet(new ulong[]{0x400UL});
public static readonly BitSet _10_in_funcwithparams117 = new BitSet(new ulong[]{0x2UL});
public static readonly BitSet _WORD_in_func135 = new BitSet(new ulong[]{0x2UL});
public static readonly BitSet _param_in_paramlist143 = new BitSet(new ulong[]{0x102UL});
public static readonly BitSet _8_in_paramlist146 = new BitSet(new ulong[]{0x260UL});
public static readonly BitSet _param_in_paramlist148 = new BitSet(new ulong[]{0x102UL});
public static readonly BitSet _WORD_in_word163 = new BitSet(new ulong[]{0x2UL});
public static readonly BitSet _STRING_in_sentence171 = new BitSet(new ulong[]{0x2UL});
public static readonly BitSet _word_in_param180 = new BitSet(new ulong[]{0x2UL});
public static readonly BitSet _sentence_in_param188 = new BitSet(new ulong[]{0x2UL});
public static readonly BitSet _funcwithparams_in_param195 = new BitSet(new ulong[]{0x2UL});
}
#endregion Follow sets
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2014 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit mindtouch.com;
* please review the licensing section.
*
* 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.Globalization;
using System.Reflection;
using System.Xml;
using MindTouch.Collections;
using MindTouch.Dream;
namespace System {
/// <summary>
/// Static utility class containing base Class library level extension and helper methods as well as System properties.
/// </summary>
public static class SysUtil {
//--- Class Fields ---
/// <summary>
/// Global-use XmlNameTable
/// </summary>
public static readonly XmlNameTable NameTable;
/// <summary>
/// Global switch for determining whether Async I/O should be used when calling Asychronous Method Pattern I/O methods.
/// </summary>
/// <remarks>
/// The value of this field is set by the "async-io" configuration key, if present.
/// Mono does not implement asychronous I/O, instead creating blocking threads in the default .NET threadpool for performaing "async" work.
/// By default, if the configuration key is not set and <see cref="IsMono"/> is defined, <see cref="UseAsyncIO"/> is set to <see langword="False"/>,
/// otherwise it is <see langword="True"/>.
/// </remarks>
public static readonly bool UseAsyncIO = true;
private static readonly bool _isMono;
private static Converter<Exception, Exception> _prepareExceptionForRethrow;
//--- Class Constructor ---
static SysUtil() {
_isMono = (Type.GetType("Mono.Runtime") != null);
if(!bool.TryParse(System.Configuration.ConfigurationManager.AppSettings["async-io"], out UseAsyncIO)) {
UseAsyncIO = !_isMono;
}
// intiailzie xml nametable
int capacity;
if(int.TryParse(System.Configuration.ConfigurationManager.AppSettings["xmlnametable-capacity"], out capacity)) {
NameTable = new LockFreeXmlNameTable(capacity);
} else {
// use default capacity for nametable
NameTable = new LockFreeXmlNameTable();
}
}
//--- Class Properties ---
/// <summary>
/// <see langword="True"/> if the program is running under the Mono runtime.
/// </summary>
public static bool IsMono { get { return _isMono; } }
/// <summary>
/// <see langword="True"/> if the program is running on a Unix platform.
/// </summary>
public static bool IsUnix {
get {
// NOTE: taken from http://www.mono-project.com/FAQ:_Technical#Compatibility
int p = (int)Environment.OSVersion.Platform;
return (p == 4) || (p == 128);
}
}
//--- Extension Methods ---
/// <summary>
/// Checks if an object is of a given type or interface.
/// </summary>
/// <typeparam name="T">Type or interface to check.</typeparam>
/// <param name="instance">Object to check.</param>
/// <returns><see langword="True"/> if the object implements the interface or derives from type.</returns>
public static bool IsA<T>(this object instance) {
return instance == null ? false : IsA<T>(instance.GetType());
}
/// <summary>
/// Checks if the type is of a given type or interface.
/// </summary>
/// <typeparam name="T">Type or interface to check.</typeparam>
/// <param name="type">Type to check.</param>
/// <returns><see langword="True"/> if the Type implements the interface or derives from type.</returns>
public static bool IsA<T>(this Type type) {
if(type == null) {
return false;
}
var t = typeof(T);
return t.IsAssignableFrom(type);
}
/// <summary>
/// Rethrow an existing exception.
/// </summary>
/// <remarks>
/// Rethrow claims to return an exception so that it can be used as the argument to <see langword="throw"/> in a <see langword="try"/> block.
/// This usage allows the compiler to see that the code cannot return from the block calling Rethrow, which is otherwise not discoverable.
/// </remarks>
/// <param name="exception">Exception to rethrow.</param>
/// <returns>This method will never return an exception, since it always throws internally.</returns>
public static Exception Rethrow(this Exception exception) {
if(exception == null) {
throw new ArgumentNullException("exception");
}
// check if we need to first create the runtime-appropriate delegate to preserve the stack-trace for a rethrow.
if(_prepareExceptionForRethrow == null) {
// Hack the stack trace so it appears to have been preserved.
// If we can't hack the stack trace, then there's not much we can do as anything we
// choose will alter the semantics of test execution.
if(IsMono) {
MethodInfo method = typeof(Exception).GetMethod("FixRemotingException", BindingFlags.Instance | BindingFlags.NonPublic);
_prepareExceptionForRethrow = delegate(Exception e) { return (Exception)method.Invoke(e, null); };
} else {
MethodInfo method = typeof(Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic);
_prepareExceptionForRethrow = delegate(Exception e) {
method.Invoke(e, null);
return e;
};
}
// just in case the internal methods name have changed!
if(_prepareExceptionForRethrow == null) {
_prepareExceptionForRethrow = delegate(Exception e) { return e; };
}
}
// check if there is a stack-trace to preserve
if(exception.StackTrace != null) {
throw _prepareExceptionForRethrow(exception);
} else {
throw exception;
}
}
//--- Class Methods ---
/// <summary>
/// Wrapper on top of <see cref="Convert.ChangeType(object,System.Type)"/> to add handling of MindTouch Dream base types.
/// </summary>
/// <param name="value">Value to convert.</param>
/// <param name="type">Type to convert value into.</param>
/// <returns>Value converted to type, if possible.</returns>
/// <exception cref="InvalidCastException"></exception>
public static object ChangeType(object value, Type type) {
if(type == null) {
throw new ArgumentNullException("type");
}
// check if this is a noop
if(type == typeof(object)) {
return value;
}
// check if target type is real number, if so use culture-invariant parsing
switch(Type.GetTypeCode(type)) {
case TypeCode.Single:
return Convert.ToSingle(value, CultureInfo.InvariantCulture);
case TypeCode.Double:
return Convert.ToDouble(value, CultureInfo.InvariantCulture);
case TypeCode.Decimal:
return Convert.ToDecimal(value, CultureInfo.InvariantCulture);
}
// check if target type is nullable
Type nullableType = Nullable.GetUnderlyingType(type);
if(nullableType != null) {
if(value == null) {
return null;
}
type = nullableType;
}
// check if type is enum and value is a value type
if(type.IsEnum) {
var valueType = value.GetType();
if(valueType.IsValueType && (value is Byte || value is Int32 || value is SByte || value is Int16 || value is Int64 || value is UInt16 || value is UInt32 || value is UInt64)) {
return Enum.ToObject(type, value);
}
}
// check if value is string
if(value is string) {
if(type == typeof(XUri)) {
// target type is XUri
XUri result = XUri.TryParse((string)value);
if(result == null) {
throw new InvalidCastException();
}
return result;
}
if(type.IsEnum) {
// target type is enum
try {
return Enum.Parse(type, (string)value, true);
} catch {
throw new InvalidCastException();
}
}
} else if((value is XUri) && (type == typeof(string))) {
return value.ToString();
}
// convert type
return Convert.ChangeType(value, type);
}
/// <summary>
/// Generic version of <see cref="ChangeType"/> to allow type change without having to cast the output to the desired type.
/// </summary>
/// <typeparam name="T">Type to convert the value into.</typeparam>
/// <param name="value">Value to convert.</param>
/// <returns>Converted value, if possible.</returns>
/// <exception cref="InvalidCastException"></exception>
public static T ChangeType<T>(object value) {
return (T)ChangeType(value, typeof(T));
}
/// <summary>
/// Excecute an atomic compare and exchange operation and determine whether it succeeded or not.
/// </summary>
/// <typeparam name="T">Type of value do perform compare and exchange on. Must be a class.</typeparam>
/// <param name="location">The reference location of the value to be changed.</param>
/// <param name="oldValue">The current value to expect for the swap to succeed.</param>
/// <param name="newValue">The new value to swap into place, as long as location is still equal to the old value.</param>
/// <returns><see langword="True"/>If the operation successfully replaced old value with new value.</returns>
public static bool CAS<T>(ref T location, T oldValue, T newValue) where T : class {
return ReferenceEquals(System.Threading.Interlocked.CompareExchange(ref location, newValue, oldValue), oldValue);
}
/// <summary>
/// Try to parse a case-insensitive string into an enum value.
/// </summary>
/// <typeparam name="T">Enum type to convert into.</typeparam>
/// <param name="text">Text value to parse.</param>
/// <param name="value">Parsed enum value.</param>
/// <returns><see langword="True"/> if an enum value could be parsed.</returns>
public static bool TryParseEnum<T>(string text, out T value) {
try {
value = (T)Enum.Parse(typeof(T), text, true);
return true;
} catch {
value = default(T);
return false;
}
}
/// <summary>
/// Try to parse a case-insensitive string into an enum value.
/// </summary>
/// <typeparam name="T">Enum type to convert into.</typeparam>
/// <param name="text">Text value to parse.</param>
/// <returns>Parsed enum value or null.</returns>
public static T? TryParseEnum<T>(string text) where T : struct {
try {
return (T)Enum.Parse(typeof(T), text, true);
} catch {
return null;
}
}
/// <summary>
/// Parse a case-insensitive string into an enum value.
/// </summary>
/// <typeparam name="T">Enum type to convert into.</typeparam>
/// <param name="text">Text value to parse.</param>
/// <returns>Parsed enum value.</returns>
public static T ParseEnum<T>(string text) {
return (T)Enum.Parse(typeof(T), text, true);
}
}
}
| |
using System;
using NUnit.Framework;
using System.Collections.ObjectModel;
using OpenQA.Selenium.Internal;
using OpenQA.Selenium.Environment;
namespace OpenQA.Selenium
{
[TestFixture]
public class ElementFindingTest : DriverTestFixture
{
// By.id positive
[Test]
public void ShouldBeAbleToFindASingleElementById()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.Id("linkId"));
Assert.AreEqual("linkId", element.GetAttribute("id"));
}
[Test]
public void ShouldBeAbleToFindASingleElementByNumericId()
{
driver.Url = nestedPage;
IWebElement element = driver.FindElement(By.Id("2"));
Assert.That(element.GetAttribute("id"), Is.EqualTo("2"));
}
[Test]
public void ShouldBeAbleToFindASingleElementByIdWithNonAlphanumericCharacters()
{
driver.Url = nestedPage;
IWebElement element = driver.FindElement(By.Id("white space"));
Assert.That(element.Text, Is.EqualTo("space"));
IWebElement element2 = driver.FindElement(By.Id("css#.chars"));
Assert.That(element2.Text, Is.EqualTo("css escapes"));
}
[Test]
public void ShouldBeAbleToFindMultipleElementsById()
{
driver.Url = nestedPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Id("2"));
Assert.AreEqual(8, elements.Count);
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByNumericId()
{
driver.Url = nestedPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Id("2"));
Assert.That(elements.Count, Is.EqualTo(8));
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByIdWithNonAlphanumericCharacters()
{
driver.Url = nestedPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Id("white space"));
Assert.That(elements.Count, Is.EqualTo(2));
ReadOnlyCollection<IWebElement> elements2 = driver.FindElements(By.Id("css#.chars"));
Assert.That(elements2.Count, Is.EqualTo(2));
}
// By.id negative
[Test]
public void ShouldNotBeAbleToLocateByIdASingleElementThatDoesNotExist()
{
driver.Url = formsPage;
Assert.That(() => driver.FindElement(By.Id("nonExistentButton")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
public void ShouldNotBeAbleToLocateByIdMultipleElementsThatDoNotExist()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Id("nonExistentButton"));
Assert.AreEqual(0, elements.Count);
}
[Test]
public void FindingASingleElementByEmptyIdShouldThrow()
{
driver.Url = formsPage;
Assert.That(() => driver.FindElement(By.Id("")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
public void FindingMultipleElementsByEmptyIdShouldReturnEmptyList()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Id(""));
Assert.AreEqual(0, elements.Count);
}
[Test]
public void FindingASingleElementByIdWithSpaceShouldThrow()
{
driver.Url = formsPage;
Assert.That(() => driver.FindElement(By.Id("nonexistent button")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
public void FindingMultipleElementsByIdWithSpaceShouldReturnEmptyList()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Id("nonexistent button"));
Assert.AreEqual(0, elements.Count);
}
// By.Name positive
[Test]
public void ShouldBeAbleToFindASingleElementByName()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("checky"));
Assert.AreEqual("furrfu", element.GetAttribute("value"));
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByName()
{
driver.Url = nestedPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Name("checky"));
Assert.That(elements, Has.Count.GreaterThan(1));
}
[Test]
public void ShouldBeAbleToFindAnElementThatDoesNotSupportTheNameProperty()
{
driver.Url = nestedPage;
IWebElement element = driver.FindElement(By.Name("div1"));
Assert.AreEqual("div1", element.GetAttribute("name"));
}
// By.Name negative
[Test]
public void ShouldNotBeAbleToLocateByNameASingleElementThatDoesNotExist()
{
driver.Url = formsPage;
Assert.That(() => driver.FindElement(By.Name("nonExistentButton")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
public void ShouldNotBeAbleToLocateByNameMultipleElementsThatDoNotExist()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Name("nonExistentButton"));
Assert.AreEqual(0, elements.Count);
}
[Test]
public void FindingASingleElementByEmptyNameShouldThrow()
{
driver.Url = formsPage;
Assert.That(() => driver.FindElement(By.Name("")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
public void FindingMultipleElementsByEmptyNameShouldReturnEmptyList()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Name(""));
Assert.AreEqual(0, elements.Count);
}
[Test]
public void FindingASingleElementByNameWithSpaceShouldThrow()
{
driver.Url = formsPage;
Assert.That(() => driver.FindElement(By.Name("nonexistent button")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
public void FindingMultipleElementsByNameWithSpaceShouldReturnEmptyList()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Name("nonexistent button"));
Assert.AreEqual(0, elements.Count);
}
// By.tagName positive
[Test]
public void ShouldBeAbleToFindASingleElementByTagName()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.TagName("input"));
Assert.AreEqual("input", element.TagName.ToLower());
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByTagName()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.TagName("input"));
Assert.That(elements, Has.Count.GreaterThan(1));
}
// By.tagName negative
[Test]
public void ShouldNotBeAbleToLocateByTagNameASingleElementThatDoesNotExist()
{
driver.Url = formsPage;
Assert.That(() => driver.FindElement(By.TagName("nonExistentButton")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
public void ShouldNotBeAbleToLocateByTagNameMultipleElementsThatDoNotExist()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.TagName("nonExistentButton"));
Assert.AreEqual(0, elements.Count);
}
[Test]
public void FindingASingleElementByEmptyTagNameShouldThrow()
{
driver.Url = formsPage;
Assert.That(() => driver.FindElement(By.TagName("")), Throws.InstanceOf<InvalidSelectorException>());
}
[Test]
public void FindingMultipleElementsByEmptyTagNameShouldThrow()
{
driver.Url = formsPage;
Assert.That(() => driver.FindElements(By.TagName("")), Throws.InstanceOf<InvalidSelectorException>());
}
[Test]
public void FindingASingleElementByTagNameWithSpaceShouldThrow()
{
driver.Url = formsPage;
Assert.That(() => driver.FindElement(By.TagName("nonexistent button")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
public void FindingMultipleElementsByTagNameWithSpaceShouldReturnEmptyList()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.TagName("nonexistent button"));
Assert.AreEqual(0, elements.Count);
}
// By.ClassName positive
[Test]
public void ShouldBeAbleToFindASingleElementByClass()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("extraDiv"));
Assert.That(element.Text, Does.StartWith("Another div starts here."));
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByClassName()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.ClassName("nameC"));
Assert.That(elements.Count, Is.GreaterThan(1));
}
[Test]
public void ShouldFindElementByClassWhenItIsTheFirstNameAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameA"));
Assert.AreEqual("An H2 title", element.Text);
}
[Test]
public void ShouldFindElementByClassWhenItIsTheLastNameAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameC"));
Assert.AreEqual("An H2 title", element.Text);
}
[Test]
public void ShouldFindElementByClassWhenItIsInTheMiddleAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameBnoise"));
Assert.AreEqual("An H2 title", element.Text);
}
[Test]
public void ShouldFindElementByClassWhenItsNameIsSurroundedByWhitespace()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("spaceAround"));
Assert.AreEqual("Spaced out", element.Text);
}
[Test]
public void ShouldFindElementsByClassWhenItsNameIsSurroundedByWhitespace()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.ClassName("spaceAround"));
Assert.AreEqual(1, elements.Count);
Assert.AreEqual("Spaced out", elements[0].Text);
}
// By.ClassName negative
[Test]
public void ShouldNotFindElementByClassWhenTheNameQueriedIsShorterThanCandidateName()
{
driver.Url = xhtmlTestPage;
Assert.That(() => driver.FindElement(By.ClassName("nameB")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
public void FindingASingleElementByEmptyClassNameShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.That(() => driver.FindElement(By.ClassName("")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
[IgnoreBrowser(Browser.Opera, "Throws WebDriverException")]
public void FindingMultipleElementsByEmptyClassNameShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.That(() => driver.FindElements(By.ClassName("")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
[IgnoreBrowser(Browser.Opera, "Throws WebDriverException")]
public void FindingASingleElementByCompoundClassNameShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.That(() => driver.FindElement(By.ClassName("a b")), Throws.InstanceOf<InvalidSelectorException>());
}
[Test]
[IgnoreBrowser(Browser.Opera, "Throws WebDriverException")]
public void FindingMultipleElementsByCompoundClassNameShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.That(() => driver.FindElements(By.ClassName("a b")), Throws.InstanceOf<InvalidSelectorException>());
}
[Test]
[IgnoreBrowser(Browser.Opera, "Throws WebDriverException")]
public void FindingASingleElementByInvalidClassNameShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.That(() => driver.FindElement(By.ClassName("!@#$%^&*")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
[IgnoreBrowser(Browser.IE, "Class name is perfectly legal when using CSS selector, if properly escaped.")]
[IgnoreBrowser(Browser.Firefox, "Class name is perfectly legal when using CSS selector, if properly escaped.")]
[IgnoreBrowser(Browser.Edge, "Class name is perfectly legal when using CSS selector, if properly escaped.")]
[IgnoreBrowser(Browser.Safari, "Class name is perfectly legal when using CSS selector, if properly escaped.")]
[IgnoreBrowser(Browser.Chrome, "Class name is perfectly legal when using CSS selector, if properly escaped.")]
[IgnoreBrowser(Browser.Opera, "Throws WebDriverException")]
public void FindingMultipleElementsByInvalidClassNameShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.That(() => driver.FindElements(By.ClassName("!@#$%^&*")), Throws.InstanceOf<NoSuchElementException>());
}
// By.XPath positive
[Test]
public void ShouldBeAbleToFindASingleElementByXPath()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.XPath("//h1"));
Assert.AreEqual("XHTML Might Be The Future", element.Text);
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByXPath()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.XPath("//div"));
Assert.AreEqual(13, elements.Count);
}
[Test]
public void ShouldBeAbleToFindManyElementsRepeatedlyByXPath()
{
driver.Url = xhtmlTestPage;
String xpathString = "//node()[contains(@id,'id')]";
Assert.AreEqual(3, driver.FindElements(By.XPath(xpathString)).Count);
xpathString = "//node()[contains(@id,'nope')]";
Assert.AreEqual(0, driver.FindElements(By.XPath(xpathString)).Count);
}
[Test]
public void ShouldBeAbleToIdentifyElementsByClass()
{
driver.Url = xhtmlTestPage;
IWebElement header = driver.FindElement(By.XPath("//h1[@class='header']"));
Assert.AreEqual("XHTML Might Be The Future", header.Text);
}
[Test]
public void ShouldBeAbleToFindAnElementByXPathWithMultipleAttributes()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(
By.XPath("//form[@name='optional']/input[@type='submit' and @value='Click!']"));
Assert.AreEqual("input", element.TagName.ToLower());
Assert.AreEqual("Click!", element.GetAttribute("value"));
}
[Test]
public void FindingALinkByXpathShouldLocateAnElementWithTheGivenText()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.XPath("//a[text()='click me']"));
Assert.AreEqual("click me", element.Text);
}
[Test]
public void FindingALinkByXpathUsingContainsKeywordShouldWork()
{
driver.Url = nestedPage;
IWebElement element = driver.FindElement(By.XPath("//a[contains(.,'hello world')]"));
Assert.That(element.Text, Does.Contain("hello world"));
}
[Test]
[IgnoreBrowser(Browser.IE, "Driver does not support XML namespaces in XPath")]
[IgnoreBrowser(Browser.Firefox, "Driver does not support XML namespaces in XPath")]
[IgnoreBrowser(Browser.Edge, "Driver does not support XML namespaces in XPath")]
[IgnoreBrowser(Browser.Safari, "Not yet implemented")]
public void ShouldBeAbleToFindElementByXPathWithNamespace()
{
driver.Url = svgPage;
IWebElement element = driver.FindElement(By.XPath("//svg:svg//svg:text"));
Assert.That(element.Text, Is.EqualTo("Test Chart"));
}
[Test]
[IgnoreBrowser(Browser.IE, "Driver does not support finding elements on XML documents.")]
[IgnoreBrowser(Browser.Chrome, "Driver does not support finding elements on XML documents.")]
[IgnoreBrowser(Browser.Edge, "Driver does not support finding elements on XML documents.")]
[IgnoreBrowser(Browser.Safari, "Not yet implemented")]
public void ShouldBeAbleToFindElementByXPathInXmlDocument()
{
driver.Url = simpleXmlDocument;
IWebElement element = driver.FindElement(By.XPath("//foo"));
Assert.That(element.Text, Is.EqualTo("baz"));
}
// By.XPath negative
[Test]
public void ShouldThrowAnExceptionWhenThereIsNoLinkToClick()
{
driver.Url = xhtmlTestPage;
Assert.That(() => driver.FindElement(By.XPath("//a[@id='Not here']")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void ShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInDriverFindElement()
{
driver.Url = formsPage;
Assert.That(() => driver.FindElement(By.XPath("this][isnot][valid")), Throws.InstanceOf<InvalidSelectorException>());
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void ShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInDriverFindElements()
{
if (TestUtilities.IsIE6(driver))
{
// Ignoring xpath error test in IE6
return;
}
driver.Url = formsPage;
Assert.That(() => driver.FindElements(By.XPath("this][isnot][valid")), Throws.InstanceOf<InvalidSelectorException>());
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void ShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInElementFindElement()
{
driver.Url = formsPage;
IWebElement body = driver.FindElement(By.TagName("body"));
Assert.That(() => body.FindElement(By.XPath("this][isnot][valid")), Throws.InstanceOf<InvalidSelectorException>());
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void ShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInElementFindElements()
{
driver.Url = formsPage;
IWebElement body = driver.FindElement(By.TagName("body"));
Assert.That(() => body.FindElements(By.XPath("this][isnot][valid")), Throws.InstanceOf<InvalidSelectorException>());
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void ShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInDriverFindElement()
{
driver.Url = formsPage;
Assert.That(() => driver.FindElement(By.XPath("count(//input)")), Throws.InstanceOf<InvalidSelectorException>());
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void ShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInDriverFindElements()
{
if (TestUtilities.IsIE6(driver))
{
// Ignoring xpath error test in IE6
return;
}
driver.Url = formsPage;
Assert.That(() => driver.FindElements(By.XPath("count(//input)")), Throws.InstanceOf<InvalidSelectorException>());
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void ShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInElementFindElement()
{
driver.Url = formsPage;
IWebElement body = driver.FindElement(By.TagName("body"));
Assert.That(() => body.FindElement(By.XPath("count(//input)")), Throws.InstanceOf<InvalidSelectorException>());
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void ShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInElementFindElements()
{
if (TestUtilities.IsIE6(driver))
{
// Ignoring xpath error test in IE6
return;
}
driver.Url = formsPage;
IWebElement body = driver.FindElement(By.TagName("body"));
Assert.That(() => body.FindElements(By.XPath("count(//input)")), Throws.InstanceOf<InvalidSelectorException>());
}
// By.CssSelector positive
[Test]
public void ShouldBeAbleToFindASingleElementByCssSelector()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.CssSelector("div.content"));
Assert.AreEqual("div", element.TagName.ToLower());
Assert.AreEqual("content", element.GetAttribute("class"));
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByCssSelector()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.CssSelector("p"));
Assert.That(elements, Has.Count.GreaterThan(1));
}
[Test]
public void ShouldBeAbleToFindASingleElementByCompoundCssSelector()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.CssSelector("div.extraDiv, div.content"));
Assert.AreEqual("div", element.TagName.ToLower());
Assert.AreEqual("content", element.GetAttribute("class"));
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByCompoundCssSelector()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.CssSelector("div.extraDiv, div.content"));
Assert.That(elements, Has.Count.GreaterThan(1));
Assert.That(elements[0].GetAttribute("class"), Is.EqualTo("content"));
Assert.That(elements[1].GetAttribute("class"), Is.EqualTo("extraDiv"));
}
[Test]
public void ShouldBeAbleToFindAnElementByBooleanAttributeUsingCssSelector()
{
driver.Url = (EnvironmentManager.Instance.UrlBuilder.WhereIs("locators_tests/boolean_attribute_selected.html"));
IWebElement element = driver.FindElement(By.CssSelector("option[selected='selected']"));
Assert.AreEqual("two", element.GetAttribute("value"));
}
[Test]
public void ShouldBeAbleToFindAnElementByBooleanAttributeUsingShortCssSelector()
{
driver.Url = (EnvironmentManager.Instance.UrlBuilder.WhereIs("locators_tests/boolean_attribute_selected.html"));
IWebElement element = driver.FindElement(By.CssSelector("option[selected]"));
Assert.AreEqual("two", element.GetAttribute("value"));
}
[Test]
public void ShouldBeAbleToFindAnElementByBooleanAttributeUsingShortCssSelectorOnHtml4Page()
{
driver.Url = (EnvironmentManager.Instance.UrlBuilder.WhereIs("locators_tests/boolean_attribute_selected_html4.html"));
IWebElement element = driver.FindElement(By.CssSelector("option[selected]"));
Assert.AreEqual("two", element.GetAttribute("value"));
}
// By.CssSelector negative
[Test]
public void ShouldNotFindElementByCssSelectorWhenThereIsNoSuchElement()
{
driver.Url = xhtmlTestPage;
Assert.That(() => driver.FindElement(By.CssSelector(".there-is-no-such-class")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
public void ShouldNotFindElementsByCssSelectorWhenThereIsNoSuchElement()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.CssSelector(".there-is-no-such-class"));
Assert.AreEqual(0, elements.Count);
}
[Test]
public void FindingASingleElementByEmptyCssSelectorShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.That(() => driver.FindElement(By.CssSelector("")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
[IgnoreBrowser(Browser.Opera, "Throws WebDriverException")]
public void FindingMultipleElementsByEmptyCssSelectorShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.That(() => driver.FindElements(By.CssSelector("")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
public void FindingASingleElementByInvalidCssSelectorShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.That(() => driver.FindElement(By.CssSelector("//a/b/c[@id='1']")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
[IgnoreBrowser(Browser.Opera, "Throws InvalidElementStateException")]
public void FindingMultipleElementsByInvalidCssSelectorShouldThrow()
{
driver.Url = xhtmlTestPage;
Assert.That(() => driver.FindElements(By.CssSelector("//a/b/c[@id='1']")), Throws.InstanceOf<NoSuchElementException>());
}
// By.linkText positive
[Test]
public void ShouldBeAbleToFindALinkByText()
{
driver.Url = xhtmlTestPage;
IWebElement link = driver.FindElement(By.LinkText("click me"));
Assert.AreEqual("click me", link.Text);
}
[Test]
public void ShouldBeAbleToFindMultipleLinksByText()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.LinkText("click me"));
Assert.AreEqual(2, elements.Count, "Expected 2 links, got " + elements.Count);
}
[Test]
public void ShouldFindElementByLinkTextContainingEqualsSign()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.LinkText("Link=equalssign"));
Assert.AreEqual("linkWithEqualsSign", element.GetAttribute("id"));
}
[Test]
public void ShouldFindMultipleElementsByLinkTextContainingEqualsSign()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.LinkText("Link=equalssign"));
Assert.AreEqual(1, elements.Count);
Assert.AreEqual("linkWithEqualsSign", elements[0].GetAttribute("id"));
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void FindsByLinkTextOnXhtmlPage()
{
if (TestUtilities.IsOldIE(driver))
{
// Old IE doesn't render XHTML pages, don't try loading XHTML pages in it
return;
}
driver.Url = (EnvironmentManager.Instance.UrlBuilder.WhereIs("actualXhtmlPage.xhtml"));
string linkText = "Foo";
IWebElement element = driver.FindElement(By.LinkText(linkText));
Assert.AreEqual(linkText, element.Text);
}
[Test]
[IgnoreBrowser(Browser.Remote)]
public void LinkWithFormattingTags()
{
driver.Url = (simpleTestPage);
IWebElement elem = driver.FindElement(By.Id("links"));
IWebElement res = elem.FindElement(By.PartialLinkText("link with formatting tags"));
Assert.AreEqual("link with formatting tags", res.Text);
}
[Test]
public void DriverCanGetLinkByLinkTestIgnoringTrailingWhitespace()
{
driver.Url = simpleTestPage;
IWebElement link = driver.FindElement(By.LinkText("link with trailing space"));
Assert.AreEqual("linkWithTrailingSpace", link.GetAttribute("id"));
Assert.AreEqual("link with trailing space", link.Text);
}
// By.linkText negative
[Test]
public void ShouldNotBeAbleToLocateByLinkTextASingleElementThatDoesNotExist()
{
driver.Url = xhtmlTestPage;
Assert.That(() => driver.FindElement(By.LinkText("Not here either")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
public void ShouldNotBeAbleToLocateByLinkTextMultipleElementsThatDoNotExist()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.LinkText("Not here either"));
Assert.AreEqual(0, elements.Count);
}
// By.partialLinkText positive
[Test]
public void ShouldBeAbleToFindMultipleElementsByPartialLinkText()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.PartialLinkText("ick me"));
Assert.AreEqual(2, elements.Count);
}
[Test]
public void ShouldBeAbleToFindASingleElementByPartialLinkText()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.PartialLinkText("anon"));
Assert.That(element.Text, Does.Contain("anon"));
}
[Test]
public void ShouldFindElementByPartialLinkTextContainingEqualsSign()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.PartialLinkText("Link="));
Assert.AreEqual("linkWithEqualsSign", element.GetAttribute("id"));
}
[Test]
public void ShouldFindMultipleElementsByPartialLinkTextContainingEqualsSign()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.PartialLinkText("Link="));
Assert.AreEqual(1, elements.Count);
Assert.AreEqual("linkWithEqualsSign", elements[0].GetAttribute("id"));
}
// Misc tests
[Test]
public void DriverShouldBeAbleToFindElementsAfterLoadingMoreThanOnePageAtATime()
{
driver.Url = formsPage;
driver.Url = xhtmlTestPage;
IWebElement link = driver.FindElement(By.LinkText("click me"));
Assert.AreEqual("click me", link.Text);
}
// You don't want to ask why this is here
[Test]
public void WhenFindingByNameShouldNotReturnById()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("id-name1"));
Assert.AreEqual("name", element.GetAttribute("value"));
element = driver.FindElement(By.Id("id-name1"));
Assert.AreEqual("id", element.GetAttribute("value"));
element = driver.FindElement(By.Name("id-name2"));
Assert.AreEqual("name", element.GetAttribute("value"));
element = driver.FindElement(By.Id("id-name2"));
Assert.AreEqual("id", element.GetAttribute("value"));
}
[Test]
public void ShouldBeAbleToFindAHiddenElementsByName()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("hidden"));
Assert.AreEqual("hidden", element.GetAttribute("name"));
}
[Test]
public void ShouldNotBeAbleToFindAnElementOnABlankPage()
{
driver.Url = "about:blank";
Assert.That(() => driver.FindElement(By.TagName("a")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
[NeedsFreshDriver(IsCreatedBeforeTest = true)]
public void ShouldNotBeAbleToLocateASingleElementOnABlankPage()
{
// Note we're on the default start page for the browser at this point.
Assert.That(() => driver.FindElement(By.Id("nonExistantButton")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
[IgnoreBrowser(Browser.Opera, "Just not working")]
public void AnElementFoundInADifferentFrameIsStale()
{
driver.Url = missedJsReferencePage;
driver.SwitchTo().Frame("inner");
IWebElement element = driver.FindElement(By.Id("oneline"));
driver.SwitchTo().DefaultContent();
Assert.That(() => { string foo = element.Text; }, Throws.InstanceOf<StaleElementReferenceException>());
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void AnElementFoundInADifferentFrameViaJsCanBeUsed()
{
driver.Url = missedJsReferencePage;
try
{
driver.SwitchTo().Frame("inner");
IWebElement first = driver.FindElement(By.Id("oneline"));
driver.SwitchTo().DefaultContent();
IWebElement element = (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript(
"return frames[0].document.getElementById('oneline');");
driver.SwitchTo().Frame("inner");
IWebElement second = driver.FindElement(By.Id("oneline"));
Assert.AreEqual(first, element);
Assert.AreEqual(second, element);
}
finally
{
driver.SwitchTo().DefaultContent();
}
}
/////////////////////////////////////////////////
// Tests unique to the .NET bindings
/////////////////////////////////////////////////
[Test]
public void ShouldReturnTitleOfPageIfSet()
{
driver.Url = xhtmlTestPage;
Assert.AreEqual(driver.Title, "XHTML Test Page");
driver.Url = simpleTestPage;
Assert.AreEqual(driver.Title, "Hello WebDriver");
}
[Test]
public void ShouldBeAbleToClickOnLinkIdentifiedByText()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.LinkText("click me")).Click();
WaitFor(() => { return driver.Title == "We Arrive Here"; }, "Browser title is not 'We Arrive Here'");
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ShouldBeAbleToClickOnLinkIdentifiedById()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.Id("linkId")).Click();
WaitFor(() => { return driver.Title == "We Arrive Here"; }, "Browser title is not 'We Arrive Here'");
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ShouldFindAnElementBasedOnId()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("checky"));
Assert.That(element.Selected, Is.False);
}
[Test]
public void ShouldBeAbleToFindChildrenOfANode()
{
driver.Url = selectableItemsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.XPath("/html/head"));
IWebElement head = elements[0];
ReadOnlyCollection<IWebElement> importedScripts = head.FindElements(By.TagName("script"));
Assert.AreEqual(importedScripts.Count, 3);
}
[Test]
public void ReturnAnEmptyListWhenThereAreNoChildrenOfANode()
{
driver.Url = xhtmlTestPage;
IWebElement table = driver.FindElement(By.Id("table"));
ReadOnlyCollection<IWebElement> rows = table.FindElements(By.TagName("tr"));
Assert.AreEqual(rows.Count, 0);
}
[Test]
public void ShouldFindElementsByName()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("checky"));
Assert.AreEqual(element.GetAttribute("value"), "furrfu");
}
[Test]
public void ShouldFindElementsByClassWhenItIsTheFirstNameAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameA"));
Assert.AreEqual(element.Text, "An H2 title");
}
[Test]
public void ShouldFindElementsByClassWhenItIsTheLastNameAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameC"));
Assert.AreEqual(element.Text, "An H2 title");
}
[Test]
public void ShouldFindElementsByClassWhenItIsInTheMiddleAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameBnoise"));
Assert.AreEqual(element.Text, "An H2 title");
}
[Test]
public void ShouldFindGrandChildren()
{
driver.Url = formsPage;
IWebElement form = driver.FindElement(By.Id("nested_form"));
form.FindElement(By.Name("x"));
}
[Test]
public void ShouldNotFindElementOutSideTree()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("login"));
Assert.That(() => element.FindElement(By.Name("x")), Throws.InstanceOf<NoSuchElementException>());
}
[Test]
public void ShouldReturnElementsThatDoNotSupportTheNameProperty()
{
driver.Url = nestedPage;
driver.FindElement(By.Name("div1"));
// If this works, we're all good
}
[Test]
public void ShouldBeAbleToClickOnLinksWithNoHrefAttribute()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.LinkText("No href"));
element.Click();
// if any exception is thrown, we won't get this far. Sanity check
Assert.AreEqual("Changed", driver.Title);
}
[Test]
public void RemovingAnElementDynamicallyFromTheDomShouldCauseAStaleRefException()
{
driver.Url = javascriptPage;
IWebElement toBeDeleted = driver.FindElement(By.Id("deleted"));
Assert.That(toBeDeleted.Displayed, "Element is not displayed");
driver.FindElement(By.Id("delete")).Click();
Assert.That(() => { bool displayedAfterDelete = toBeDeleted.Displayed; }, Throws.InstanceOf<StaleElementReferenceException>());
}
[Test]
public void FindingByTagNameShouldNotIncludeParentElementIfSameTagType()
{
driver.Url = xhtmlTestPage;
IWebElement parent = driver.FindElement(By.Id("my_span"));
Assert.AreEqual(2, parent.FindElements(By.TagName("div")).Count);
Assert.AreEqual(2, parent.FindElements(By.TagName("span")).Count);
}
[Test]
public void FindingByCssShouldNotIncludeParentElementIfSameTagType()
{
driver.Url = xhtmlTestPage;
IWebElement parent = driver.FindElement(By.CssSelector("div#parent"));
IWebElement child = parent.FindElement(By.CssSelector("div"));
Assert.AreEqual("child", child.GetAttribute("id"));
}
[Test]
public void FindingByXPathShouldNotIncludeParentElementIfSameTagType()
{
driver.Url = xhtmlTestPage;
IWebElement parent = driver.FindElement(By.Id("my_span"));
Assert.AreEqual(2, parent.FindElements(By.TagName("div")).Count);
Assert.AreEqual(2, parent.FindElements(By.TagName("span")).Count);
}
[Test]
public void ShouldBeAbleToInjectXPathEngineIfNeeded()
{
driver.Url = alertsPage;
driver.FindElement(By.XPath("//body"));
driver.FindElement(By.XPath("//h1"));
driver.FindElement(By.XPath("//div"));
driver.FindElement(By.XPath("//p"));
driver.FindElement(By.XPath("//a"));
}
[Test]
public void ShouldFindElementByLinkTextContainingDoubleQuote()
{
driver.Url = simpleTestPage;
IWebElement element = driver.FindElement(By.LinkText("link with \" (double quote)"));
Assert.AreEqual("quote", element.GetAttribute("id"));
}
[Test]
public void ShouldFindElementByLinkTextContainingBackslash()
{
driver.Url = simpleTestPage;
IWebElement element = driver.FindElement(By.LinkText("link with \\ (backslash)"));
Assert.AreEqual("backslash", element.GetAttribute("id"));
}
private bool SupportsSelectorApi()
{
IJavaScriptExecutor javascriptDriver = driver as IJavaScriptExecutor;
IFindsByCssSelector cssSelectorDriver = driver as IFindsByCssSelector;
return (cssSelectorDriver != null) && (javascriptDriver != null);
}
}
}
| |
/* ====================================================================
*/
using System;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
using System.IO;
using Oranikle.Report.Engine;
namespace Oranikle.Report.Engine
{
///<summary>
/// Handle SQL configuration and connections
///</summary>
public class RdlEngineConfig
{
static public IDictionary SqlEntries = null; // list of entries
static public Dictionary<string, CustomReportItemEntry> CustomReportItemEntries = null;
static DateTime _InitFileCreationTime = DateTime.MinValue;
// Compression entries
static CompressionConfig _Compression = null;
static string _DirectoryLoadedFrom = null;
static public string DirectoryLoadedFrom
{
get
{
return _DirectoryLoadedFrom;
}
}
// initializes when no init available
static public void RdlEngineConfigInit()
{
string d1, d2;
d1 = AppDomain.CurrentDomain.BaseDirectory;
d2 = AppDomain.CurrentDomain.RelativeSearchPath;
if (d2 != null && d2 != string.Empty)
d2 = (d2.Contains(":") ? "" : AppDomain.CurrentDomain.BaseDirectory) + d2 + Path.DirectorySeparatorChar;
RdlEngineConfigInit(d1, d2);
}
// initialize configuration
static public void RdlEngineConfigInit(params string[] dirs)
{
bool bLoaded = false;
XmlDocument xDoc = new XmlDocument();
xDoc.PreserveWhitespace = false;
string file = null;
DateTime fileTime = DateTime.MinValue;
foreach (string dir in dirs)
{
if (dir == null)
continue;
file = dir + "RdlEngineConfig.xml";
try
{
FileInfo fi = new FileInfo(file);
fileTime = fi.CreationTime;
if (_InitFileCreationTime == fileTime && SqlEntries != null)
return; // we've already inited with this file
xDoc.Load(file);
bLoaded = true;
_DirectoryLoadedFrom = dir;
}
catch (Exception ex)
{ // can't do much about failures; no place to report them
System.Console.WriteLine("Error opening RdlEngineConfig.xml: {0}", ex.Message);
}
if (bLoaded)
break;
}
if (!bLoaded) // we couldn't find the configuration so we'll use public one
{
if (SqlEntries != null) // we don't need to reinit with public one
return;
xDoc.InnerXml = @"
<config>
<DataSources>
<DataSource>
<DataProvider>SQL</DataProvider>
<TableSelect>SELECT TABLE_NAME, TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES ORDER BY 2, 1</TableSelect>
<Interface>SQL</Interface>
</DataSource>
<DataSource>
<DataProvider>ODBC</DataProvider>
<TableSelect>SELECT TABLE_NAME, TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES ORDER BY 2, 1</TableSelect>
<Interface>SQL</Interface>
<ReplaceParameters>true</ReplaceParameters>
</DataSource>
<DataSource>
<DataProvider>OLEDB</DataProvider>
<TableSelect>SELECT TABLE_NAME, TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES ORDER BY 2, 1</TableSelect>
<Interface>SQL</Interface>
</DataSource>
<DataSource>
<DataProvider>XML</DataProvider>
<CodeModule>DataProviders.dll</CodeModule>
<ClassName>fyiReporting.Data.XmlConnection</ClassName>
<TableSelect></TableSelect>
<Interface>File</Interface>
</DataSource>
<DataSource>
<DataProvider>WebService</DataProvider>
<CodeModule>DataProviders.dll</CodeModule>
<ClassName>fyiReporting.Data.WebServiceConnection</ClassName>
<TableSelect></TableSelect>
<Interface>WebService</Interface>
</DataSource>
<DataSource>
<DataProvider>WebLog</DataProvider>
<CodeModule>DataProviders.dll</CodeModule>
<ClassName>fyiReporting.Data.LogConnection</ClassName>
<TableSelect></TableSelect>
<Interface>File</Interface>
</DataSource>
<DataSource>
<DataProvider>Text</DataProvider>
<CodeModule>DataProviders.dll</CodeModule>
<ClassName>fyiReporting.Data.TxtConnection</ClassName>
<TableSelect></TableSelect>
<Interface>File</Interface>
</DataSource>
<DataSource>
<DataProvider>FileDirectory</DataProvider>
<CodeModule>DataProviders.dll</CodeModule>
<ClassName>fyiReporting.Data.FileDirConnection</ClassName>
<TableSelect></TableSelect>
<Interface>File</Interface>
</DataSource>
</DataSources>
<Compression>
<CodeModule>ICSharpCode.SharpZipLib.dll</CodeModule>
<ClassName>ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream</ClassName>
<Finish>Finish</Finish>
<Enable>true</Enable>
</Compression>
<CustomReportItems>
<CustomReportItem>
<Type>BarCode</Type>
<CodeModule>RdlCri.dll</CodeModule>
<ClassName>fyiReporting.CRI.BarCode</ClassName>
</CustomReportItem>
</CustomReportItems>
</config>";
}
XmlNode xNode;
xNode = xDoc.SelectSingleNode("//config");
IDictionary dsDir = new ListDictionary();
Dictionary<string, CustomReportItemEntry> crieDir =
new Dictionary<string, CustomReportItemEntry>(); // list of entries
// Loop thru all the child nodes
foreach (XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "DataSources":
GetDataSources(dsDir, xNodeLoop);
break;
case "Compression":
GetCompression(xNodeLoop);
break;
case "CustomReportItems":
GetCustomReportItems(crieDir, xNodeLoop);
break;
default:
break;
}
}
SqlEntries = dsDir;
CustomReportItemEntries = crieDir;
_InitFileCreationTime = fileTime; // save initialization time
return;
}
public static CompressionConfig GetCompression()
{
if (SqlEntries == null)
RdlEngineConfigInit(); // init if necessary
return _Compression;
}
static void GetCompression(XmlNode xNode)
{
// loop thru looking to process all the datasource elements
string cm = null;
string cn = null;
string fn = null;
bool bEnable = true;
foreach (XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "CodeModule":
if (xNodeLoop.InnerText.Length > 0)
cm = xNodeLoop.InnerText;
break;
case "ClassName":
if (xNodeLoop.InnerText.Length > 0)
cn = xNodeLoop.InnerText;
break;
case "Finish":
if (xNodeLoop.InnerText.Length > 0)
fn = xNodeLoop.InnerText;
break;
case "Enable":
if (xNodeLoop.InnerText.ToLower() == "false")
bEnable = false;
break;
}
}
if (bEnable)
_Compression = new CompressionConfig(cm, cn, fn);
else
_Compression = null;
}
static void GetDataSources(IDictionary dsDir, XmlNode xNode)
{
// loop thru looking to process all the datasource elements
foreach (XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
if (xNodeLoop.Name != "DataSource")
continue;
GetDataSource(dsDir, xNodeLoop);
}
}
static void GetDataSource(IDictionary dsDir, XmlNode xNode)
{
string provider = null;
string codemodule = null;
string cname = null;
string inter = "SQL";
string tselect = null;
bool replaceparameters = false;
foreach (XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "DataProvider":
provider = xNodeLoop.InnerText;
break;
case "CodeModule":
codemodule = xNodeLoop.InnerText;
break;
case "Interface":
inter = xNodeLoop.InnerText;
break;
case "ClassName":
cname = xNodeLoop.InnerText;
break;
case "TableSelect":
tselect = xNodeLoop.InnerText;
break;
case "ReplaceParameters":
if (xNodeLoop.InnerText.ToLower() == "true")
replaceparameters = true;
break;
default:
break;
}
}
if (provider == null)
return; // nothing to do if no provider specified
SqlConfigEntry sce;
try
{ // load the module early; saves problems with concurrency later
string msg = null;
Assembly la = null;
if (codemodule != null && cname != null)
{
// check to see if the DLL has been previously loaded
// many of the DataProvider done by fyiReporting are in a single code module
foreach (SqlConfigEntry sc in dsDir.Values)
{
if (sc.FileName == codemodule &&
sc.CodeModule != null)
{
la = sc.CodeModule;
break;
}
}
if (la == null)
la = XmlUtil.AssemblyLoadFrom(codemodule);
if (la == null)
msg = string.Format("{0} could not be loaded", codemodule);
}
sce = new SqlConfigEntry(provider, codemodule, cname, la, tselect, msg);
dsDir.Add(provider, sce);
}
catch (Exception e)
{ // keep exception; if this DataProvided is ever useed we will see the message
sce = new SqlConfigEntry(provider, codemodule, cname, null, tselect, e.Message);
dsDir.Add(provider, sce);
}
sce.ReplaceParameters = replaceparameters;
}
public static IDbConnection GetConnection(string provider, string cstring)
{
IDbConnection cn = null;
switch (provider.ToLower())
{
case "sql":
// can't connect unless information provided;
// when user wants to set the connection programmatically this they should do this
if (cstring.Length > 0)
cn = new SqlConnection(cstring);
break;
case "odbc":
cn = new OdbcConnection(cstring);
break;
case "oledb":
cn = new OleDbConnection(cstring);
break;
default:
if (SqlEntries == null) // if never initialized; we should init
RdlEngineConfigInit();
SqlConfigEntry sce = SqlEntries[provider] as SqlConfigEntry;
if (sce == null || sce.CodeModule == null)
{
if (sce != null && sce.ErrorMsg != null) // error during initialization??
throw new Exception(sce.ErrorMsg);
break;
}
object[] args = new object[] { cstring };
Assembly asm = sce.CodeModule;
object o = asm.CreateInstance(sce.ClassName, false,
BindingFlags.CreateInstance, null, args, null, null);
if (o == null)
throw new Exception(string.Format("Unable to create instance of '{0}' for provider '{1}'", sce.ClassName, provider));
cn = o as IDbConnection;
break;
}
return cn;
}
static public string GetTableSelect(string provider)
{
return GetTableSelect(provider, null);
}
static public bool DoParameterReplacement(string provider, IDbConnection cn)
{
if (SqlEntries == null)
RdlEngineConfigInit();
SqlConfigEntry sce = SqlEntries[provider] as SqlConfigEntry;
return sce == null ? false : sce.ReplaceParameters;
}
static public string GetTableSelect(string provider, IDbConnection cn)
{
if (SqlEntries == null)
RdlEngineConfigInit();
SqlConfigEntry sce = SqlEntries[provider] as SqlConfigEntry;
if (sce == null)
{
if (cn != null)
{
OdbcConnection oc = cn as OdbcConnection;
if (oc != null && oc.Driver.ToLower().IndexOf("my") >= 0) // not a good way but ...
return "show tables"; // mysql syntax is non-standard
}
return "SELECT TABLE_NAME, TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES ORDER BY 2, 1";
}
if (cn != null)
{
OdbcConnection oc = cn as OdbcConnection;
if (oc != null && oc.Driver.ToLower().IndexOf("my") >= 0) // not a good way but ...
return "show tables"; // mysql syntax is non-standard
}
return sce.TableSelect;
}
static public string[] GetProviders()
{
if (SqlEntries == null)
RdlEngineConfigInit();
if (SqlEntries.Count == 0)
return null;
string[] items = new string[SqlEntries.Count];
int i = 0;
foreach (SqlConfigEntry sce in SqlEntries.Values)
{
items[i++] = sce.Provider;
}
return items;
}
static public string[] GetCustomReportTypes()
{
if (CustomReportItemEntries == null)
RdlEngineConfigInit();
if (CustomReportItemEntries.Count == 0)
return null;
string[] items = new string[CustomReportItemEntries.Count];
int i = 0;
foreach (CustomReportItemEntry crie in CustomReportItemEntries.Values)
{
items[i++] = crie.ItemName;
}
return items;
}
static void GetCustomReportItems(Dictionary<string, CustomReportItemEntry> crieDir, XmlNode xNode)
{
// loop thru looking to process all the datasource elements
foreach (XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
if (xNodeLoop.Name != "CustomReportItem")
continue;
GetCustomReportItem(crieDir, xNodeLoop);
}
}
static void GetCustomReportItem(Dictionary<string, CustomReportItemEntry> crieDir, XmlNode xNode)
{
string friendlyTypeName = null;
string codemodule = null;
string classname = null;
foreach (XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "Type":
friendlyTypeName = xNodeLoop.InnerText;
break;
case "CodeModule":
codemodule = xNodeLoop.InnerText;
break;
case "ClassName":
classname = xNodeLoop.InnerText;
break;
default:
break;
}
}
if (friendlyTypeName == null)
return; // nothing to do if no provider specified
CustomReportItemEntry crie;
try
{ // load the module early; saves problems with concurrency later
string msg = null;
Type dotNetType = null;
Assembly la = null;
if (codemodule != null && classname != null)
{
// Check to see if previously loaded. Many CustomReportItems share same CodeModule.
Assembly[] allLoadedAss = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly ass in allLoadedAss)
if (ass.Location.Equals(codemodule, StringComparison.CurrentCultureIgnoreCase))
{
la = ass;
break;
}
if (la == null) // not previously loaded?
la = XmlUtil.AssemblyLoadFrom(codemodule);
if (la == null)
msg = string.Format("{0} could not be loaded", codemodule);
else
dotNetType = la.GetType(classname);
}
crie = new CustomReportItemEntry(friendlyTypeName, dotNetType, msg);
crieDir.Add(friendlyTypeName, crie);
}
catch (Exception e)
{ // keep exception; if this CustomReportItem is ever used we will see the message
crie = new CustomReportItemEntry(friendlyTypeName, null, e.Message);
crieDir.Add(friendlyTypeName, crie);
}
}
public static ICustomReportItem CreateCustomReportItem(string friendlyTypeName)
{
CustomReportItemEntry crie = null;
if (!CustomReportItemEntries.TryGetValue(friendlyTypeName, out crie))
throw new Exception(string.Format("{0} is not a known CustomReportItem type", friendlyTypeName));
if (crie.Type == null)
throw new Exception(crie.ErrorMsg ??
string.Format("{0} is not a known CustomReportItem type", friendlyTypeName));
ICustomReportItem item = (ICustomReportItem)Activator.CreateInstance(crie.Type);
return item;
}
public static void DeclareNewCustomReportItem(string itemName, Type type)
{
if (!typeof(ICustomReportItem).IsAssignableFrom(type))
throw new ArgumentException("The type does not implement the ICustomReportItem interface: " +
type == null ? "null" : type.Name);
if (CustomReportItemEntries == null)
RdlEngineConfigInit();
// Let's manage doublons, if any.
CustomReportItemEntry item;
if (!CustomReportItemEntries.TryGetValue(itemName, out item))
CustomReportItemEntries[itemName] = new CustomReportItemEntry(itemName, type, null);
else if (!item.Type.Equals(type))
throw new ArgumentException("A different type of CustomReportItem with the same has already been declared.");
}
}
public class CompressionConfig
{
int _UseCompression = -1;
Assembly _Assembly = null;
string _CodeModule;
string _ClassName;
string _Finish;
MethodInfo _FinishMethodInfo; // if there is a finish method
string _ErrorMsg; // error encountered loading compression
public CompressionConfig(string cm, string cn, string fn)
{
_CodeModule = cm;
_ClassName = cn;
_Finish = fn;
if (cm == null || cn == null || fn == null)
_UseCompression = 2;
}
public bool CanCompress
{
get
{
if (_UseCompression >= 1) // we've already successfully inited
return true;
if (_UseCompression == 0) // we've tried to init and failed
return false;
Init(); // initialize compression
return _UseCompression == 1; // and return the status
}
}
public void CallStreamFinish(Stream strm)
{
if (_UseCompression == 2)
{
strm.Close();
return;
}
if (_FinishMethodInfo == null)
return;
object returnVal = _FinishMethodInfo.Invoke(strm, null);
return;
}
public byte[] GetArray(MemoryStream ms)
{
byte[] cmpData = ms.ToArray();
if (_UseCompression == 1)
return cmpData;
// we're using the MS routines; need to prefix by 2 bytes;
// see http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=97064
// see http://www.faqs.org/rfcs/rfc1950.html
// bit of magic:
// DeflateStream follows RFC1951, so the info I have is based on what I've read about RFC1950.
//First byte:
//Bits 0-3: those will always be 8 for the Deflate compression method.
//Bits 4-7: Our window size is 8K so I think this should be 5. The compression info value is
// log base 2 of the window size minus 8 => 8K = 2^13, so 13-8. If you're having problems with
// this, note that I've seen some comments indicating this is interpreted as max window size,
// so you might also try setting this to 7, corresponding to a window size of 32K.
//The next byte consists of some checksums and flags which may be optional?
byte[] wa = new byte[cmpData.Length + 2 + 4]; // length = data length + prefix length + checksum length
// These values don't actally work for all since some compressions go wrong???
// (may have been corrected: kas 9/16/08 but didn't do exhaustive tests since ziplib is better in any case)
wa[0] = 0x58; // 78
wa[1] = 0x85; // 9c
cmpData.CopyTo(wa, 2);
uint c = adler(cmpData); // this is the checksum
wa[2 + cmpData.Length + 0] = (byte)(c >> 24);
wa[2 + cmpData.Length + 1] = (byte)(c >> 16);
wa[2 + cmpData.Length + 2] = (byte)(c >> 8);
wa[2 + cmpData.Length + 3] = (byte)(c);
return wa;
}
/// <summary>
/// Adler 32 checksum routine comes from http://en.wikipedia.org/wiki/Adler-32
/// </summary>
/// <param name="cmpData"></param>
/// <returns></returns>
private uint adler(byte[] cmpData)
{
const int MOD_ADLER = 65521;
int len = cmpData.Length;
uint a = 1, b = 0;
int i = 0;
while (len > 0)
{
int tlen = len > 5552 ? 5552 : len;
len -= tlen;
do
{
a += cmpData[i++];
b += a;
} while (--tlen > 0);
a %= MOD_ADLER;
b %= MOD_ADLER;
}
return (b << 16) | a;
}
public Stream GetStream(Stream str)
{
if (_UseCompression == 2)
{ // use the built-in compression .NET 2 provides
//System.IO.Compression.GZipStream cs =
// new System.IO.Compression.GZipStream(str, System.IO.Compression.CompressionMode.Compress);
System.IO.Compression.DeflateStream cs =
new System.IO.Compression.DeflateStream(str, System.IO.Compression.CompressionMode.Compress);
return cs;
}
if (_UseCompression == 0)
return null;
if (_UseCompression == -1) // make sure we're init'ed
{
Init();
if (_UseCompression != 1)
return null;
}
try
{
object[] args = new object[] { str };
Stream so = _Assembly.CreateInstance(_ClassName, false,
BindingFlags.CreateInstance, null, args, null, null) as Stream;
return so;
}
catch
{
return null;
}
}
public string ErrorMsg
{
get { return _ErrorMsg; }
}
void Init()
{
lock (this)
{
if (_UseCompression != -1)
return;
_UseCompression = 0; // assume failure; and use the builtin MS routines
try
{
// Load the assembly
_Assembly = XmlUtil.AssemblyLoadFrom(_CodeModule);
// Load up a test stream to make sure it will work
object[] args = new object[] { new MemoryStream() };
Stream so = _Assembly.CreateInstance(_ClassName, false,
BindingFlags.CreateInstance, null, args, null, null) as Stream;
if (so != null)
{ // we've successfully inited
so.Close();
_UseCompression = 1;
}
else
_Assembly = null;
if (_Finish != null)
{
Type theClassType = so.GetType();
this._FinishMethodInfo = theClassType.GetMethod(_Finish);
}
}
catch (Exception e)
{
_ErrorMsg = e.InnerException == null ? e.Message : e.InnerException.Message;
_UseCompression = 0; // failure; force use the builtin MS routines
}
}
}
}
public class SqlConfigEntry
{
public string Provider;
public Assembly CodeModule;
public string ClassName;
public string TableSelect;
public string ErrorMsg;
public bool ReplaceParameters;
public string FileName;
public SqlConfigEntry(string provider, string file, string cname, Assembly codemodule, string tselect, string msg)
{
Provider = provider;
CodeModule = codemodule;
ClassName = cname;
TableSelect = tselect;
ErrorMsg = msg;
ReplaceParameters = false;
FileName = file;
}
}
public class CustomReportItemEntry
{
public string ItemName;
public Type Type;
public string ErrorMsg;
public CustomReportItemEntry(string itemName, Type type, string msg)
{
Type = type;
ItemName = itemName;
ErrorMsg = msg;
}
}
}
| |
/// Credit BinaryX
/// Sourced from - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/page-2#post-1945602
/// Updated by ddreaper - removed dependency on a custom ScrollRect script. Now implements drag interfaces and standard Scroll Rect.
/// Update by xesenix - rewrited almost entire code
/// - configuration for direction move instead of 2 concurrent class (easiear to change direction in editor)
/// - supports list layouted with horizontal or vertical layout need to match direction with type of layout used
/// - dynamicly checks if scrolled list size changes and recalculates anchor positions
/// and item size based on itemsVisibleAtOnce and size of root container
/// if you dont wish to use this auto resize turn of autoLayoutItems
/// - fixed current page made it independant from pivot
/// - replaced pagination with delegate function
using System;
using UnityEngine.EventSystems;
namespace UnityEngine.UI.Extensions
{
[ExecuteInEditMode]
[RequireComponent(typeof(ScrollRect))]
[AddComponentMenu("UI/Extensions/Scroll Snap")]
public class ScrollSnap : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler
{
// needed becouse of reversed behavior of axis Y compared to X
// (positions of children lower in children list in horizontal directions grows when in vertical it gets smaller)
public enum ScrollDirection
{
Horizontal,
Vertical
}
public delegate void PageSnapChange(int page);
public event PageSnapChange onPageChange;
public ScrollDirection direction = ScrollDirection.Horizontal;
protected ScrollRect scrollRect;
protected RectTransform scrollRectTransform;
protected Transform listContainerTransform;
protected RectTransform rectTransform;
private int pages;
protected int startingPage = 0;
// anchor points to lerp to to see child on certain indexes
protected Vector3[] pageAnchorPositions;
protected Vector3 lerpTarget;
protected bool lerp;
// item list related
protected float listContainerMinPosition;
protected float listContainerMaxPosition;
protected float listContainerSize;
protected RectTransform listContainerRectTransform;
protected Vector2 listContainerCachedSize;
protected float itemSize;
protected int itemsCount = 0;
[Tooltip("Button to go to the next page. (optional)")]
public Button nextButton;
[Tooltip("Button to go to the previous page. (optional)")]
public Button prevButton;
[Tooltip("Number of items visible in one page of scroll frame.")]
[RangeAttribute(1, 100)]
public int itemsVisibleAtOnce = 1;
[Tooltip("Sets minimum width of list items to 1/itemsVisibleAtOnce.")]
public bool autoLayoutItems = true;
[Tooltip("If you wish to update scrollbar numberOfSteps to number of active children on list.")]
public bool linkScrolbarSteps = false;
[Tooltip("If you wish to update scrollrect sensitivity to size of list element.")]
public bool linkScrolrectScrollSensitivity = false;
public Boolean useFastSwipe = true;
public int fastSwipeThreshold = 100;
// drag related
protected bool startDrag = true;
protected Vector3 positionOnDragStart = new Vector3();
protected int pageOnDragStart;
protected bool fastSwipeTimer = false;
protected int fastSwipeCounter = 0;
protected int fastSwipeTarget = 10;
// Use this for initialization
private void Awake()
{
lerp = false;
scrollRect = gameObject.GetComponent<ScrollRect>();
scrollRectTransform = gameObject.GetComponent<RectTransform>();
listContainerTransform = scrollRect.content;
listContainerRectTransform = listContainerTransform.GetComponent<RectTransform>();
rectTransform = listContainerTransform.gameObject.GetComponent<RectTransform>();
UpdateListItemsSize();
UpdateListItemPositions();
PageChanged(CurrentPage());
if (nextButton)
{
nextButton.GetComponent<Button>().onClick.AddListener(() =>
{
NextScreen();
});
}
if (prevButton)
{
prevButton.GetComponent<Button>().onClick.AddListener(() =>
{
PreviousScreen();
});
}
}
private void Start()
{
Awake();
}
public void UpdateListItemsSize()
{
float size = 0;
float currentSize = 0;
if (direction == ScrollSnap.ScrollDirection.Horizontal)
{
size = scrollRectTransform.rect.width / itemsVisibleAtOnce;
currentSize = listContainerRectTransform.rect.width / itemsCount;
}
else
{
size = scrollRectTransform.rect.height / itemsVisibleAtOnce;
currentSize = listContainerRectTransform.rect.height / itemsCount;
}
itemSize = size;
if (linkScrolrectScrollSensitivity)
{
scrollRect.scrollSensitivity = itemSize;
}
if (autoLayoutItems && currentSize != size && itemsCount > 0)
{
if (direction == ScrollSnap.ScrollDirection.Horizontal)
{
foreach (var tr in listContainerTransform)
{
GameObject child = ((Transform)tr).gameObject;
if (child.activeInHierarchy)
{
var childLayout = child.GetComponent<LayoutElement>();
if (childLayout == null)
{
childLayout = child.AddComponent<LayoutElement>();
}
childLayout.minWidth = itemSize;
}
}
}
else
{
foreach (var tr in listContainerTransform)
{
GameObject child = ((Transform)tr).gameObject;
if (child.activeInHierarchy)
{
var childLayout = child.GetComponent<LayoutElement>();
if (childLayout == null)
{
childLayout = child.AddComponent<LayoutElement>();
}
childLayout.minHeight = itemSize;
}
}
}
}
}
public void UpdateListItemPositions()
{
if (!listContainerRectTransform.rect.size.Equals(listContainerCachedSize))
{
// checking how many children of list are active
int activeCount = 0;
foreach (var tr in listContainerTransform)
{
if (((Transform)tr).gameObject.activeInHierarchy)
{
activeCount++;
}
}
// if anything changed since last check reinitialize anchors list
itemsCount = 0;
Array.Resize(ref pageAnchorPositions, activeCount);
if (activeCount > 0)
{
pages = Mathf.Max(activeCount - itemsVisibleAtOnce + 1, 1);
if (direction == ScrollDirection.Horizontal)
{
// looking for list spanning range min/max
scrollRect.horizontalNormalizedPosition = 0;
listContainerMaxPosition = listContainerTransform.localPosition.x;
scrollRect.horizontalNormalizedPosition = 1;
listContainerMinPosition = listContainerTransform.localPosition.x;
listContainerSize = listContainerMaxPosition - listContainerMinPosition;
for (var i = 0; i < pages; i++)
{
pageAnchorPositions[i] = new Vector3(
listContainerMaxPosition - itemSize * i,
listContainerTransform.localPosition.y,
listContainerTransform.localPosition.z
);
}
}
else
{
//Debug.Log ("-------------looking for list spanning range----------------");
// looking for list spanning range
scrollRect.verticalNormalizedPosition = 1;
listContainerMinPosition = listContainerTransform.localPosition.y;
scrollRect.verticalNormalizedPosition = 0;
listContainerMaxPosition = listContainerTransform.localPosition.y;
listContainerSize = listContainerMaxPosition - listContainerMinPosition;
for (var i = 0; i < pages; i++)
{
pageAnchorPositions[i] = new Vector3(
listContainerTransform.localPosition.x,
listContainerMinPosition + itemSize * i,
listContainerTransform.localPosition.z
);
}
}
UpdateScrollbar(linkScrolbarSteps);
startingPage = Mathf.Min(startingPage, pages);
ResetPage();
}
if (itemsCount != activeCount)
{
PageChanged(CurrentPage());
}
itemsCount = activeCount;
listContainerCachedSize.Set(listContainerRectTransform.rect.size.x, listContainerRectTransform.rect.size.y);
}
}
public void ResetPage()
{
if (direction == ScrollDirection.Horizontal)
{
scrollRect.horizontalNormalizedPosition = pages > 1 ? (float)startingPage / (float)(pages - 1) : 0;
}
else
{
scrollRect.verticalNormalizedPosition = pages > 1 ? (float)(pages - startingPage - 1) / (float)(pages - 1) : 0;
}
}
protected void UpdateScrollbar(bool linkSteps)
{
if (linkSteps)
{
if (direction == ScrollDirection.Horizontal)
{
if (scrollRect.horizontalScrollbar != null)
{
scrollRect.horizontalScrollbar.numberOfSteps = pages;
}
}
else
{
if (scrollRect.verticalScrollbar != null)
{
scrollRect.verticalScrollbar.numberOfSteps = pages;
}
}
}
else
{
if (direction == ScrollDirection.Horizontal)
{
if (scrollRect.horizontalScrollbar != null)
{
scrollRect.horizontalScrollbar.numberOfSteps = 0;
}
}
else
{
if (scrollRect.verticalScrollbar != null)
{
scrollRect.verticalScrollbar.numberOfSteps = 0;
}
}
}
}
private void LateUpdate()
{
UpdateListItemsSize();
UpdateListItemPositions();
if (lerp)
{
UpdateScrollbar(false);
listContainerTransform.localPosition = Vector3.Lerp(listContainerTransform.localPosition, lerpTarget, 7.5f * Time.deltaTime);
if (Vector3.Distance(listContainerTransform.localPosition, lerpTarget) < 0.001f)
{
listContainerTransform.localPosition = lerpTarget;
lerp = false;
UpdateScrollbar(linkScrolbarSteps);
}
//change the info bullets at the bottom of the screen. Just for visual effect
if (Vector3.Distance(listContainerTransform.localPosition, lerpTarget) < 10f)
{
PageChanged(CurrentPage());
}
}
if (fastSwipeTimer)
{
fastSwipeCounter++;
}
}
private bool fastSwipe = false; //to determine if a fast swipe was performed
//Function for switching screens with buttons
public void NextScreen()
{
UpdateListItemPositions();
if (CurrentPage() < pages - 1)
{
lerp = true;
lerpTarget = pageAnchorPositions[CurrentPage() + 1];
PageChanged(CurrentPage() + 1);
}
}
//Function for switching screens with buttons
public void PreviousScreen()
{
UpdateListItemPositions();
if (CurrentPage() > 0)
{
lerp = true;
lerpTarget = pageAnchorPositions[CurrentPage() - 1];
PageChanged(CurrentPage() - 1);
}
}
//Because the CurrentScreen function is not so reliable, these are the functions used for swipes
private void NextScreenCommand()
{
if (pageOnDragStart < pages - 1)
{
int targetPage = Mathf.Min(pages - 1, pageOnDragStart + itemsVisibleAtOnce);
lerp = true;
lerpTarget = pageAnchorPositions[targetPage];
PageChanged(targetPage);
}
}
//Because the CurrentScreen function is not so reliable, these are the functions used for swipes
private void PrevScreenCommand()
{
if (pageOnDragStart > 0)
{
int targetPage = Mathf.Max(0, pageOnDragStart - itemsVisibleAtOnce);
lerp = true;
lerpTarget = pageAnchorPositions[targetPage];
PageChanged(targetPage);
}
}
//returns the current screen that the is seeing
public int CurrentPage()
{
//return startingPage;
float pos;
if (direction == ScrollDirection.Horizontal)
{
pos = listContainerMaxPosition - listContainerTransform.localPosition.x;
pos = Mathf.Clamp(pos, 0, listContainerSize);
}
else
{
pos = listContainerTransform.localPosition.y - listContainerMinPosition;
pos = Mathf.Clamp(pos, 0, listContainerSize);
}
float page = pos / itemSize;
//Debug.Log("CurrentPage() " + page);
return Mathf.Clamp(Mathf.RoundToInt(page), 0, pages);
}
public void ChangePage(int page)
{
if (0 <= page && page < pages)
{
lerp = true;
lerpTarget = pageAnchorPositions[page];
PageChanged(page);
}
}
//changes the bullets on the bottom of the page - pagination
private void PageChanged(int currentPage)
{
Debug.Log(currentPage);
startingPage = currentPage;
if (nextButton)
{
nextButton.interactable = currentPage < pages - 1;
}
if (prevButton)
{
prevButton.interactable = currentPage > 0;
}
if (onPageChange != null)
{
onPageChange(currentPage);
}
}
#region Interfaces
public void OnBeginDrag(PointerEventData eventData)
{
//Debug.Log("-- BeginDrag");
UpdateScrollbar(false);
fastSwipeCounter = 0;
fastSwipeTimer = true;
positionOnDragStart = eventData.position;
pageOnDragStart = CurrentPage();
}
public void OnEndDrag(PointerEventData eventData)
{
//Debug.Log("-- EndDrag");
startDrag = true;
float change = 0;
if (direction == ScrollDirection.Horizontal)
{
change = positionOnDragStart.x - eventData.position.x;
}
else
{
change = -positionOnDragStart.y + eventData.position.y;
}
if (useFastSwipe)
{
fastSwipe = false;
fastSwipeTimer = false;
if (fastSwipeCounter <= fastSwipeTarget)
{
if (Math.Abs(change) > fastSwipeThreshold)
{
fastSwipe = true;
}
}
if (fastSwipe)
{
if (change > 0)
{
NextScreenCommand();
}
else
{
PrevScreenCommand();
}
}
else
{
lerp = true;
lerpTarget = pageAnchorPositions[CurrentPage()];
}
}
else
{
lerp = true;
lerpTarget = pageAnchorPositions[CurrentPage()];
}
}
public void OnDrag(PointerEventData eventData)
{
lerp = false;
if (startDrag)
{
OnBeginDrag(eventData);
startDrag = false;
}
}
#endregion Interfaces
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class SwitchTests
{
[Theory]
[ClassData(typeof(CompilationTypes))]
public void IntSwitch1(bool useInterpreter)
{
ParameterExpression p = Expression.Parameter(typeof(int));
ParameterExpression p1 = Expression.Parameter(typeof(string));
SwitchExpression s = Expression.Switch(p,
Expression.Assign(p1, Expression.Constant("default")),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant(1)),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant(2)),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant(1)));
BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1);
Func<int, string> f = Expression.Lambda<Func<int, string>>(block, p).Compile(useInterpreter);
Assert.Equal("hello", f(1));
Assert.Equal("two", f(2));
Assert.Equal("default", f(3));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void NullableIntSwitch1(bool useInterpreter)
{
ParameterExpression p = Expression.Parameter(typeof(int?));
ParameterExpression p1 = Expression.Parameter(typeof(string));
SwitchExpression s = Expression.Switch(p,
Expression.Assign(p1, Expression.Constant("default")),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant((int?)1, typeof(int?))),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant((int?)2, typeof(int?))),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant((int?)1, typeof(int?))));
BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1);
Func<int?, string> f = Expression.Lambda<Func<int?, string>>(block, p).Compile(useInterpreter);
Assert.Equal("hello", f(1));
Assert.Equal("two", f(2));
Assert.Equal("default", f(null));
Assert.Equal("default", f(3));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void SwitchToGotos(bool useInterpreter)
{
ParameterExpression p = Expression.Parameter(typeof(int));
ParameterExpression p1 = Expression.Parameter(typeof(string));
LabelTarget end = Expression.Label();
LabelTarget lala = Expression.Label();
LabelTarget hello = Expression.Label();
BlockExpression block =Expression.Block(
new [] { p1 },
Expression.Switch(
p,
Expression.Block(
Expression.Assign(p1, Expression.Constant("default")),
Expression.Goto(end)
),
Expression.SwitchCase(Expression.Goto(hello), Expression.Constant(1)),
Expression.SwitchCase(Expression.Block(
Expression.Assign(p1, Expression.Constant("two")),
Expression.Goto(end)
), Expression.Constant(2)),
Expression.SwitchCase(Expression.Goto(lala), Expression.Constant(4))
),
Expression.Label(hello),
Expression.Assign(p1, Expression.Constant("hello")),
Expression.Goto(end),
Expression.Label(lala),
Expression.Assign(p1, Expression.Constant("lala")),
Expression.Label(end),
p1
);
Func<int, string> f = Expression.Lambda<Func<int, string>>(block, p).Compile(useInterpreter);
Assert.Equal("hello", f(1));
Assert.Equal("two", f(2));
Assert.Equal("default", f(3));
Assert.Equal("lala", f(4));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void SwitchToGotosOutOfTry(bool useInterpreter)
{
ParameterExpression p = Expression.Parameter(typeof(char));
ParameterExpression p1 = Expression.Parameter(typeof(string));
LabelTarget end = Expression.Label();
LabelTarget lala = Expression.Label();
LabelTarget hello = Expression.Label();
BlockExpression block = Expression.Block(
new[] { p1 },
Expression.TryFinally(
Expression.Switch(
p,
Expression.Block(
Expression.Assign(p1, Expression.Constant("default")),
Expression.Goto(end)
),
Expression.SwitchCase(Expression.Goto(hello), Expression.Constant('a')),
Expression.SwitchCase(Expression.Block(
Expression.Assign(p1, Expression.Constant("two")),
Expression.Goto(end)
), Expression.Constant('b')),
Expression.SwitchCase(Expression.Goto(lala), Expression.Constant('d'))
),
Expression.Empty()
),
Expression.Label(hello),
Expression.Assign(p1, Expression.Constant("hello")),
Expression.Goto(end),
Expression.Label(lala),
Expression.Assign(p1, Expression.Constant("lala")),
Expression.Label(end),
p1
);
Func<char, string> f = Expression.Lambda<Func<char, string>>(block, p).Compile(useInterpreter);
Assert.Equal("hello", f('a'));
Assert.Equal("two", f('b'));
Assert.Equal("default", f('c'));
Assert.Equal("lala", f('d'));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void NullableIntSwitch2(bool useInterpreter)
{
ParameterExpression p = Expression.Parameter(typeof(int?));
ParameterExpression p1 = Expression.Parameter(typeof(string));
SwitchExpression s = Expression.Switch(p,
Expression.Assign(p1, Expression.Constant("default")),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant((int?)1, typeof(int?))),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant((int?)2, typeof(int?))),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("null")), Expression.Constant((int?)null, typeof(int?))),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant((int?)1, typeof(int?))));
BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1);
Func<int?, string> f = Expression.Lambda<Func<int?, string>>(block, p).Compile(useInterpreter);
Assert.Equal("hello", f(1));
Assert.Equal("two", f(2));
Assert.Equal("null", f(null));
Assert.Equal("default", f(3));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void IntSwitch2(bool useInterpreter)
{
ParameterExpression p = Expression.Parameter(typeof(byte));
ParameterExpression p1 = Expression.Parameter(typeof(string));
SwitchExpression s = Expression.Switch(p,
Expression.Assign(p1, Expression.Constant("default")),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant((byte)1)),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant((byte)2)),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant((byte)1)));
BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1);
Func<byte, string> f = Expression.Lambda<Func<byte, string>>(block, p).Compile(useInterpreter);
Assert.Equal("hello", f(1));
Assert.Equal("two", f(2));
Assert.Equal("default", f(3));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void IntSwitch3(bool useInterpreter)
{
ParameterExpression p = Expression.Parameter(typeof(uint));
ParameterExpression p1 = Expression.Parameter(typeof(string));
SwitchExpression s = Expression.Switch(p,
Expression.Assign(p1, Expression.Constant("default")),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant((uint)1)),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant((uint)2)),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant((uint)1)),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("wow")), Expression.Constant(uint.MaxValue)));
BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1);
Func<uint, string> f = Expression.Lambda<Func<uint, string>>(block, p).Compile(useInterpreter);
Assert.Equal("hello", f(1));
Assert.Equal("wow", f(uint.MaxValue));
Assert.Equal("two", f(2));
Assert.Equal("default", f(3));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void LongSwitch(bool useInterpreter)
{
ParameterExpression p = Expression.Parameter(typeof(long));
ParameterExpression p1 = Expression.Parameter(typeof(string));
SwitchExpression s = Expression.Switch(p,
Expression.Assign(p1, Expression.Constant("default")),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant(1L)),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant(2L)),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant(1L)),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("wow")), Expression.Constant(long.MaxValue)));
BlockExpression block = Expression.Block(new [] { p1 }, s, p1);
Func<long, string> f = Expression.Lambda<Func<long, string>>(block, p).Compile(useInterpreter);
Assert.Equal("hello", f(1));
Assert.Equal("wow", f(long.MaxValue));
Assert.Equal("two", f(2));
Assert.Equal("default", f(3));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void ULongSwitch(bool useInterpreter)
{
ParameterExpression p = Expression.Parameter(typeof(ulong));
ParameterExpression p1 = Expression.Parameter(typeof(string));
SwitchExpression s = Expression.Switch(p,
Expression.Assign(p1, Expression.Constant("default")),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant(1UL)),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant(2UL)),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant(1UL)),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("wow")), Expression.Constant(ulong.MaxValue)));
BlockExpression block = Expression.Block(new [] { p1 }, s, p1);
Func<ulong, string> f = Expression.Lambda<Func<ulong, string>>(block, p).Compile(useInterpreter);
Assert.Equal("hello", f(1));
Assert.Equal("wow", f(ulong.MaxValue));
Assert.Equal("two", f(2));
Assert.Equal("default", f(3));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void StringSwitch(bool useInterpreter)
{
ParameterExpression p = Expression.Parameter(typeof(string));
SwitchExpression s = Expression.Switch(p,
Expression.Constant("default"),
Expression.SwitchCase(Expression.Constant("hello"), Expression.Constant("hi")),
Expression.SwitchCase(Expression.Constant("lala"), Expression.Constant("bye")));
Func<string, string> f = Expression.Lambda<Func<string, string>>(s, p).Compile(useInterpreter);
Assert.Equal("hello", f("hi"));
Assert.Equal("lala", f("bye"));
Assert.Equal("default", f("hi2"));
Assert.Equal("default", f(null));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void StringSwitch1(bool useInterpreter)
{
ParameterExpression p = Expression.Parameter(typeof(string));
ParameterExpression p1 = Expression.Parameter(typeof(string));
SwitchExpression s = Expression.Switch(p,
Expression.Assign(p1, Expression.Constant("default")),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant("hi")),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("null")), Expression.Constant(null, typeof(string))),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant("bye")));
BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1);
Func<string, string> f = Expression.Lambda<Func<string, string>>(block, p).Compile(useInterpreter);
Assert.Equal("hello", f("hi"));
Assert.Equal("lala", f("bye"));
Assert.Equal("default", f("hi2"));
Assert.Equal("null", f(null));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void StringSwitchNotConstant(bool useInterpreter)
{
Expression<Func<string>> expr1 = () => new string('a', 5);
Expression<Func<string>> expr2 = () => new string('q', 5);
ParameterExpression p = Expression.Parameter(typeof(string));
SwitchExpression s = Expression.Switch(p,
Expression.Constant("default"),
Expression.SwitchCase(Expression.Invoke(expr1), Expression.Invoke(expr2)),
Expression.SwitchCase(Expression.Constant("lala"), Expression.Constant("bye")));
Func<string, string> f = Expression.Lambda<Func<string, string>>(s, p).Compile(useInterpreter);
Assert.Equal("aaaaa", f("qqqqq"));
Assert.Equal("lala", f("bye"));
Assert.Equal("default", f("hi2"));
Assert.Equal("default", f(null));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void ObjectSwitch1(bool useInterpreter)
{
ParameterExpression p = Expression.Parameter(typeof(object));
ParameterExpression p1 = Expression.Parameter(typeof(string));
SwitchExpression s = Expression.Switch(p,
Expression.Assign(p1, Expression.Constant("default")),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant("hi")),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("null")), Expression.Constant(null, typeof(string))),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant("bye")),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lalala")), Expression.Constant("hi")));
BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1);
Func<object, string> f = Expression.Lambda<Func<object, string>>(block, p).Compile(useInterpreter);
Assert.Equal("hello", f("hi"));
Assert.Equal("lala", f("bye"));
Assert.Equal("default", f("hi2"));
Assert.Equal("default", f("HI"));
Assert.Equal("null", f(null));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void DefaultOnlySwitch(bool useInterpreter)
{
ParameterExpression p = Expression.Parameter(typeof(int));
SwitchExpression s = Expression.Switch(p, Expression.Constant(42));
Func<int, int> fInt32Int32 = Expression.Lambda<Func<int, int>>(s, p).Compile(useInterpreter);
Assert.Equal(42, fInt32Int32(0));
Assert.Equal(42, fInt32Int32(1));
Assert.Equal(42, fInt32Int32(-1));
s = Expression.Switch(typeof(object), p, Expression.Constant("A test string"), null);
Func<int, object> fInt32Object = Expression.Lambda<Func<int, object>>(s, p).Compile(useInterpreter);
Assert.Equal("A test string", fInt32Object(0));
Assert.Equal("A test string", fInt32Object(1));
Assert.Equal("A test string", fInt32Object(-1));
p = Expression.Parameter(typeof(string));
s = Expression.Switch(p, Expression.Constant("foo"));
Func<string, string> fStringString = Expression.Lambda<Func<string, string>>(s, p).Compile(useInterpreter);
Assert.Equal("foo", fStringString("bar"));
Assert.Equal("foo", fStringString(null));
Assert.Equal("foo", fStringString("foo"));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void NoDefaultOrCasesSwitch(bool useInterpreter)
{
ParameterExpression p = Expression.Parameter(typeof(int));
SwitchExpression s = Expression.Switch(p);
Action<int> f = Expression.Lambda<Action<int>>(s, p).Compile(useInterpreter);
f(0);
Assert.Equal(s.Type, typeof(void));
}
[Fact]
public void TypedNoDefaultOrCasesSwitch()
{
ParameterExpression p = Expression.Parameter(typeof(int));
// A SwitchExpression with neither a defaultBody nor any cases can not be any type except void.
AssertExtensions.Throws<ArgumentException>("defaultBody", () => Expression.Switch(typeof(int), p, null, null));
}
private delegate int RefSettingDelegate(ref bool changed);
private delegate void JustRefSettingDelegate(ref bool changed);
public static int QuestionMeaning(ref bool changed)
{
changed = true;
return 42;
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void DefaultOnlySwitchWithSideEffect(bool useInterpreter)
{
bool changed = false;
ParameterExpression pOut = Expression.Parameter(typeof(bool).MakeByRefType(), "changed");
MethodCallExpression switchValue = Expression.Call(typeof(SwitchTests).GetMethod(nameof(QuestionMeaning)), pOut);
SwitchExpression s = Expression.Switch(switchValue, Expression.Constant(42));
RefSettingDelegate fInt32Int32 = Expression.Lambda<RefSettingDelegate>(s, pOut).Compile(useInterpreter);
Assert.False(changed);
Assert.Equal(42, fInt32Int32(ref changed));
Assert.True(changed);
changed = false;
Assert.Equal(42, fInt32Int32(ref changed));
Assert.True(changed);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void NoDefaultOrCasesSwitchWithSideEffect(bool useInterpreter)
{
bool changed = false;
ParameterExpression pOut = Expression.Parameter(typeof(bool).MakeByRefType(), "changed");
MethodCallExpression switchValue = Expression.Call(typeof(SwitchTests).GetMethod(nameof(QuestionMeaning)), pOut);
SwitchExpression s = Expression.Switch(switchValue, (Expression)null);
JustRefSettingDelegate f = Expression.Lambda<JustRefSettingDelegate>(s, pOut).Compile(useInterpreter);
Assert.False(changed);
f(ref changed);
Assert.True(changed);
}
public class TestComparers
{
public static bool CaseInsensitiveStringCompare(string s1, string s2)
{
return StringComparer.OrdinalIgnoreCase.Equals(s1, s2);
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void SwitchWithComparison(bool useInterpreter)
{
ParameterExpression p = Expression.Parameter(typeof(string));
ParameterExpression p1 = Expression.Parameter(typeof(string));
SwitchExpression s = Expression.Switch(p,
Expression.Assign(p1, Expression.Constant("default")),
typeof(TestComparers).GetMethod(nameof(TestComparers.CaseInsensitiveStringCompare)),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant("hi")),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("null")), Expression.Constant(null, typeof(string))),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant("bye")),
Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lalala")), Expression.Constant("hi")));
BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1);
Func<string, string> f = Expression.Lambda<Func<string, string>>(block, p).Compile(useInterpreter);
Assert.Equal("hello", f("hi"));
Assert.Equal("lala", f("bYe"));
Assert.Equal("default", f("hi2"));
Assert.Equal("hello", f("HI"));
Assert.Equal("null", f(null));
}
[Fact]
public void NullSwitchValue()
{
AssertExtensions.Throws<ArgumentNullException>("switchValue", () => Expression.Switch(null));
AssertExtensions.Throws<ArgumentNullException>("switchValue", () => Expression.Switch(null, Expression.Empty()));
AssertExtensions.Throws<ArgumentNullException>("switchValue", () => Expression.Switch(null, Expression.Empty(), default(MethodInfo)));
AssertExtensions.Throws<ArgumentNullException>("switchValue", () => Expression.Switch(null, Expression.Empty(), default(MethodInfo), Enumerable.Empty<SwitchCase>()));
AssertExtensions.Throws<ArgumentNullException>("switchValue", () => Expression.Switch(typeof(int), null, Expression.Constant(1), default(MethodInfo)));
AssertExtensions.Throws<ArgumentNullException>("switchValue", () => Expression.Switch(typeof(int), null, Expression.Constant(1), default(MethodInfo), Enumerable.Empty<SwitchCase>()));
}
[Fact]
public void VoidSwitchValue()
{
AssertExtensions.Throws<ArgumentException>("switchValue", () => Expression.Switch(Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("switchValue", () => Expression.Switch(Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("switchValue", () => Expression.Switch(Expression.Empty(), Expression.Empty(), default(MethodInfo)));
AssertExtensions.Throws<ArgumentException>("switchValue", () => Expression.Switch(Expression.Empty(), Expression.Empty(), default(MethodInfo), Enumerable.Empty<SwitchCase>()));
AssertExtensions.Throws<ArgumentException>("switchValue", () => Expression.Switch(typeof(int), Expression.Empty(), Expression.Constant(1), default(MethodInfo)));
AssertExtensions.Throws<ArgumentException>("switchValue", () => Expression.Switch(typeof(int), Expression.Empty(), Expression.Constant(1), default(MethodInfo), Enumerable.Empty<SwitchCase>()));
}
private static IEnumerable<object[]> ComparisonsWithInvalidParmeterCounts()
{
Func<bool> nullary = () => true;
yield return new object[] { nullary.GetMethodInfo() };
Func<int, bool> unary = x => x % 2 == 0;
yield return new object[] { unary.GetMethodInfo() };
Func<int, int, int, bool> ternary = (x, y, z) => (x == y) == (y == z);
yield return new object[] { ternary.GetMethodInfo() };
Func<int, int, int, int, bool> quaternary = (a, b, c, d) => (a == b) == (c == d);
yield return new object[] { quaternary.GetMethodInfo() };
}
[Theory, MemberData(nameof(ComparisonsWithInvalidParmeterCounts))]
public void InvalidComparisonMethodParameterCount(MethodInfo comparison)
{
AssertExtensions.Throws<ArgumentException>("comparison", () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparison));
AssertExtensions.Throws<ArgumentException>("comparison", () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparison, Enumerable.Empty<SwitchCase>()));
AssertExtensions.Throws<ArgumentException>("comparison", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparison));
AssertExtensions.Throws<ArgumentException>("comparison", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparison, Enumerable.Empty<SwitchCase>()));
}
[Fact]
public void ComparisonLeftParameterIncorrect()
{
Func<string, int, bool> isLength = (x, y) => (x?.Length).GetValueOrDefault() == y;
MethodInfo comparer = isLength.GetMethodInfo();
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparer));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparer, Enumerable.Empty<SwitchCase>()));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparer));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparer, Enumerable.Empty<SwitchCase>()));
}
[Fact]
public void ComparisonRightParameterIncorrect()
{
Func<int, string, bool> isLength = (x, y) => (y?.Length).GetValueOrDefault() == x;
MethodInfo comparer = isLength.GetMethodInfo();
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparer, Expression.SwitchCase(Expression.Empty(), Expression.Constant(0))));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparer, Enumerable.Repeat(Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)), 1)));
AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparer, Expression.SwitchCase(Expression.Empty(), Expression.Constant(0))));
AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparer, Enumerable.Repeat(Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)), 1)));
}
private class GenClass<T>
{
public static bool WithinTwo(int x, int y) => Math.Abs(x - y) < 2;
}
[Theory, ClassData(typeof(CompilationTypes))]
public void OpenGenericMethodDeclarer(bool useInterpreter)
{
Expression switchVal = Expression.Constant(30);
Expression defaultExp = Expression.Constant(0);
SwitchCase switchCase = Expression.SwitchCase(Expression.Constant(1), Expression.Constant(2));
MethodInfo method = typeof(GenClass<>).GetMethod(nameof(GenClass<int>.WithinTwo), BindingFlags.Static | BindingFlags.Public);
AssertExtensions.Throws<ArgumentException>(
"comparison", () => Expression.Switch(switchVal, defaultExp, method, switchCase));
}
static bool WithinTen(int x, int y) => Math.Abs(x - y) < 10;
[Theory, ClassData(typeof(CompilationTypes))]
public void LiftedCall(bool useInterpreter)
{
Func<int> f = Expression.Lambda<Func<int>>(
Expression.Switch(
Expression.Constant(30, typeof(int?)),
Expression.Constant(0),
typeof(SwitchTests).GetMethod(nameof(WithinTen), BindingFlags.Static | BindingFlags.NonPublic),
Expression.SwitchCase(Expression.Constant(1), Expression.Constant(2, typeof(int?))),
Expression.SwitchCase(Expression.Constant(2), Expression.Constant(9, typeof(int?)), Expression.Constant(28, typeof(int?))),
Expression.SwitchCase(Expression.Constant(3), Expression.Constant(49, typeof(int?)))
)
).Compile(useInterpreter);
Assert.Equal(2, f());
}
[Fact]
public void LeftLiftedCall()
{
AssertExtensions.Throws<ArgumentException>(null, () =>
Expression.Switch(
Expression.Constant(30, typeof(int?)),
Expression.Constant(0),
typeof(SwitchTests).GetMethod(nameof(WithinTen), BindingFlags.Static | BindingFlags.NonPublic),
Expression.SwitchCase(Expression.Constant(1), Expression.Constant(2))
)
);
}
[Fact]
public void CaseTypeMisMatch()
{
AssertExtensions.Throws<ArgumentException>("cases", () =>
Expression.Switch(
Expression.Constant(30),
Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0)),
Expression.SwitchCase(Expression.Constant(2), Expression.Constant("Foo"))
)
);
AssertExtensions.Throws<ArgumentException>("cases", () =>
Expression.Switch(
Expression.Constant(30),
Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0), Expression.Constant("Foo"))
)
);
}
static int NonBooleanMethod(int x, int y) => x + y;
[Fact]
public void NonBooleanComparer()
{
MethodInfo comparer = typeof(SwitchTests).GetMethod(nameof(NonBooleanMethod), BindingFlags.Static | BindingFlags.NonPublic);
AssertExtensions.Throws<ArgumentException>("comparison", () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparer, Expression.SwitchCase(Expression.Empty(), Expression.Constant(0))));
AssertExtensions.Throws<ArgumentException>("comparison", () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparer, Enumerable.Repeat(Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)), 1)));
AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparer, Expression.SwitchCase(Expression.Empty(), Expression.Constant(0))));
AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparer, Enumerable.Repeat(Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)), 1)));
}
[Fact]
public void MismatchingCasesAndType()
{
AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch(Expression.Constant(2), Expression.SwitchCase(Expression.Constant("Foo"), Expression.Constant(0)), Expression.SwitchCase(Expression.Constant(3), Expression.Constant(9))));
}
[Fact]
public void MismatchingCasesAndExpclitType()
{
AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch(typeof(int), Expression.Constant(0), null, null, Expression.SwitchCase(Expression.Constant("Foo"), Expression.Constant(0))));
}
[Fact]
public void MismatchingDefaultAndExpclitType()
{
AssertExtensions.Throws<ArgumentException>("defaultBody", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant("Foo"), null));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void MismatchingAllowedIfExplicitlyVoidIntgralValueType(bool useInterpreter)
{
Expression.Lambda<Action>(
Expression.Switch(
typeof(void),
Expression.Constant(0),
Expression.Constant(1),
null,
Expression.SwitchCase(Expression.Constant("Foo"), Expression.Constant(2)),
Expression.SwitchCase(Expression.Constant(DateTime.MinValue), Expression.Constant(3))
)
).Compile(useInterpreter)();
}
[Theory, ClassData(typeof(CompilationTypes))]
public void MismatchingAllowedIfExplicitlyVoidStringValueType(bool useInterpreter)
{
Expression.Lambda<Action>(
Expression.Switch(
typeof(void),
Expression.Constant("Foo"),
Expression.Constant(1),
null,
Expression.SwitchCase(Expression.Constant("Foo"), Expression.Constant("Bar")),
Expression.SwitchCase(Expression.Constant(DateTime.MinValue), Expression.Constant("Foo"))
)
).Compile(useInterpreter)();
}
[Theory, ClassData(typeof(CompilationTypes))]
public void MismatchingAllowedIfExplicitlyVoidDateTimeValueType(bool useInterpreter)
{
Expression.Lambda<Action>(
Expression.Switch(
typeof(void),
Expression.Constant(DateTime.MinValue),
Expression.Constant(1),
null,
Expression.SwitchCase(Expression.Constant("Foo"), Expression.Constant(DateTime.MinValue)),
Expression.SwitchCase(Expression.Constant(DateTime.MinValue), Expression.Constant(DateTime.MaxValue))
)
).Compile(useInterpreter)();
}
[Fact]
public void SwitchCaseUpdateSameToSame()
{
Expression[] tests = {Expression.Constant(0), Expression.Constant(2)};
SwitchCase sc = Expression.SwitchCase(Expression.Constant(1), tests);
Assert.Same(sc, sc.Update(tests, sc.Body));
Assert.Same(sc, sc.Update(sc.TestValues, sc.Body));
}
[Fact]
public void SwitchCaseUpdateNullTestsToSame()
{
SwitchCase sc = Expression.SwitchCase(Expression.Constant(0), Expression.Constant(1));
AssertExtensions.Throws<ArgumentException>("testValues", () => sc.Update(null, sc.Body));
AssertExtensions.Throws<ArgumentNullException>("body", () => sc.Update(sc.TestValues, null));
}
[Fact]
public void SwitchCaseDifferentBodyToDifferent()
{
SwitchCase sc = Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0), Expression.Constant(2));
Assert.NotSame(sc, sc.Update(sc.TestValues, Expression.Constant(1)));
}
[Fact]
public void SwitchCaseDifferentTestsToDifferent()
{
SwitchCase sc = Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0), Expression.Constant(2));
Assert.NotSame(sc, sc.Update(new[] { Expression.Constant(0), Expression.Constant(2) }, sc.Body));
}
[Fact]
public void SwitchCaseUpdateDoesntRepeatEnumeration()
{
SwitchCase sc = Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0), Expression.Constant(2));
Assert.NotSame(sc, sc.Update(new RunOnceEnumerable<Expression>(new[] { Expression.Constant(0), Expression.Constant(2) }), sc.Body));
}
[Fact]
public void SwitchUpdateSameToSame()
{
SwitchCase[] cases =
{
Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)),
Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2))
};
SwitchExpression sw = Expression.Switch(
Expression.Constant(0),
Expression.Constant(0),
cases
);
Assert.Same(sw, sw.Update(sw.SwitchValue, cases.Skip(0), sw.DefaultBody));
Assert.Same(sw, sw.Update(sw.SwitchValue, cases, sw.DefaultBody));
Assert.Same(sw, NoOpVisitor.Instance.Visit(sw));
}
[Fact]
public void SwitchUpdateDifferentDefaultToDifferent()
{
SwitchExpression sw = Expression.Switch(
Expression.Constant(0),
Expression.Constant(0),
Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)),
Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2))
);
Assert.NotSame(sw, sw.Update(sw.SwitchValue, sw.Cases, Expression.Constant(0)));
}
[Fact]
public void SwitchUpdateDifferentValueToDifferent()
{
SwitchExpression sw = Expression.Switch(
Expression.Constant(0),
Expression.Constant(0),
Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)),
Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2))
);
Assert.NotSame(sw, sw.Update(Expression.Constant(0), sw.Cases, sw.DefaultBody));
}
[Fact]
public void SwitchUpdateDifferentCasesToDifferent()
{
SwitchExpression sw = Expression.Switch(
Expression.Constant(0),
Expression.Constant(0),
Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)),
Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2))
);
SwitchCase[] newCases = new[]
{
Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)),
Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2))
};
Assert.NotSame(sw, sw.Update(sw.SwitchValue, newCases, sw.DefaultBody));
}
[Fact]
public void SwitchUpdateDoesntRepeatEnumeration()
{
SwitchExpression sw = Expression.Switch(
Expression.Constant(0),
Expression.Constant(0),
Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)),
Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2))
);
IEnumerable<SwitchCase> newCases =
new RunOnceEnumerable<SwitchCase>(
new SwitchCase[]
{
Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)),
Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2))
});
Assert.NotSame(sw, sw.Update(sw.SwitchValue, newCases, sw.DefaultBody));
}
[Fact]
public void SingleTestCaseToString()
{
SwitchCase sc = Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0));
Assert.Equal("case (0): ...", sc.ToString());
}
[Fact]
public void MultipleTestCaseToString()
{
SwitchCase sc = Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0), Expression.Constant("A"));
Assert.Equal("case (0, \"A\"): ...", sc.ToString());
}
[Theory, ClassData(typeof(CompilationTypes))]
public void SwitchOnString(bool useInterpreter)
{
var values = new string[] { "foobar", "foo", "bar", "baz", "qux", "quux", "corge", "grault", "garply", "waldo", "fred", "plugh", "xyzzy", "thud" };
for (var i = 1; i <= values.Length; i++)
{
SwitchCase[] cases = values.Take(i).Select((s, j) => Expression.SwitchCase(Expression.Constant(j), Expression.Constant(values[j]))).ToArray();
ParameterExpression value = Expression.Parameter(typeof(string));
Expression<Func<string, int>> e = Expression.Lambda<Func<string, int>>(Expression.Switch(value, Expression.Constant(-1), cases), value);
Func<string, int> f = e.Compile(useInterpreter);
int k = 0;
foreach (var str in values.Take(i))
{
Assert.Equal(k, f(str));
k++;
}
foreach (var str in values.Skip(i).Concat(new[] { default(string), "whatever", "FOO" }))
{
Assert.Equal(-1, f(str));
k++;
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public void SwitchOnStringEqualsMethod(bool useInterpreter)
{
var values = new string[] { "foobar", "foo", "bar", "baz", "qux", "quux", "corge", "grault", "garply", "waldo", "fred", "plugh", "xyzzy", "thud", null };
for (var i = 1; i <= values.Length; i++)
{
SwitchCase[] cases = values.Take(i).Select((s, j) => Expression.SwitchCase(Expression.Constant(j), Expression.Constant(values[j], typeof(string)))).ToArray();
ParameterExpression value = Expression.Parameter(typeof(string));
Expression<Func<string, int>> e = Expression.Lambda<Func<string, int>>(Expression.Switch(value, Expression.Constant(-1), typeof(string).GetMethod("Equals", new[] { typeof(string), typeof(string) }), cases), value);
Func<string, int> f = e.Compile(useInterpreter);
int k = 0;
foreach (var str in values.Take(i))
{
Assert.Equal(k, f(str));
k++;
}
foreach (var str in values.Skip(i).Concat(new[] { "whatever", "FOO" }))
{
Assert.Equal(-1, f(str));
k++;
}
}
}
[Fact]
public void ToStringTest()
{
SwitchExpression e1 = Expression.Switch(Expression.Parameter(typeof(int), "x"), Expression.SwitchCase(Expression.Empty(), Expression.Constant(1)));
Assert.Equal("switch (x) { ... }", e1.ToString());
SwitchCase e2 = Expression.SwitchCase(Expression.Parameter(typeof(int), "x"), Expression.Constant(1));
Assert.Equal("case (1): ...", e2.ToString());
SwitchCase e3 = Expression.SwitchCase(Expression.Parameter(typeof(int), "x"), Expression.Constant(1), Expression.Constant(2));
Assert.Equal("case (1, 2): ...", e3.ToString());
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.GenerateEnumMember;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.GenerateEnumMember
{
public class GenerateEnumMemberTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return new Tuple<DiagnosticAnalyzer, CodeFixProvider>(null, new GenerateEnumMemberCodeFixProvider());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestEmptyEnum()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Red|] ; } } enum Color { } ",
@"class Program { void Main ( ) { Color . Red ; } } enum Color { Red } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestWithSingleMember()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red , Blue } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestWithExistingComma()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red , } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red , Blue , } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestWithMultipleMembers()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Green|] ; } } enum Color { Red , Blue } ",
@"class Program { void Main ( ) { Color . Green ; } } enum Color { Red , Blue , Green } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestWithZero()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 0 } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 0 , Blue = 1 } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestWithIntegralValue()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 1 } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 1 , Blue = 2 } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestWithSingleBitIntegral()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 2 } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 2 , Blue = 4 } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerateIntoGeometricSequence()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 1 , Yellow = 2 , Green = 4 }",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 1 , Yellow = 2 , Green = 4 , Blue = 8}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestWithSimpleSequence1()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 1 , Green = 2 } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 1 , Green = 2 , Blue = 3 } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestWithSimpleSequence2()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Yellow = 0, Red = 1 , Green = 2 } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Yellow = 0, Red = 1 , Green = 2 , Blue = 3 } ");
}
[Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestWithNonZeroInteger()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Green = 5 } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Green = 5 , Blue = 6 } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestWithLeftShift0()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Green = 1 << 0 } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Green = 1 << 0 , Blue = 1 << 1 } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestWithLeftShift5()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Green = 1 << 5 } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Green = 1 << 5 , Blue = 1 << 6 } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestWithDifferentStyles()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 2 , Green = 1 << 5 } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 2 , Green = 1 << 5 , Blue = 33 } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestBinary()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 0b01 } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 0b01 , Blue = 0b10 } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestHex1()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 0x1 } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 0x1 , Blue = 0x2 } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestHex9()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 0x9 } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 0x9 , Blue = 0xA } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestHexF()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 0xF } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 0xF , Blue = 0x10 } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerateAfterEnumWithIntegerMaxValue()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = int.MaxValue } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = int.MaxValue , Blue = int.MinValue } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestUnsigned16BitEnums()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color : ushort { Red = 65535 } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color : ushort { Red = 65535 , Blue = 0 } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerateEnumMemberOfTypeLong()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color : long { Red = long.MaxValue } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color : long { Red = long.MaxValue , Blue = long.MinValue } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerateAfterEnumWithLongMaxValueInBinary()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color : long { Red = 0b0111111111111111111111111111111111111111111111111111111111111111 } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color : long { Red = 0b0111111111111111111111111111111111111111111111111111111111111111 , Blue = 0b1000000000000000000000000000000000000000000000000000000000000000 } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerateAfterEnumWithLongMaxValueInHex()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color : long { Red = 0x7FFFFFFFFFFFFFFF } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color : long { Red = 0x7FFFFFFFFFFFFFFF , Blue = 0x8000000000000000 } ");
}
[WorkItem(528312, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528312")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerateAfterEnumWithLongMinValueInHex()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color : long { Red = 0xFFFFFFFFFFFFFFFF } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color : long { Red = 0xFFFFFFFFFFFFFFFF , Blue} ");
}
[WorkItem(528312, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528312")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerateAfterPositiveLongInHex()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color : long { Red = 0xFFFFFFFFFFFFFFFF , Green = 0x0 } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color : long { Red = 0xFFFFFFFFFFFFFFFF , Green = 0x0 , Blue = 0x1 } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerateAfterPositiveLongExprInHex()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color : long { Red = 0x414 / 2 } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color : long { Red = 0x414 / 2 , Blue = 523 } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerateAfterEnumWithULongMaxValue()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color : ulong { Red = ulong.MaxValue } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color : ulong { Red = ulong.MaxValue , Blue = 0 } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestNegativeRangeIn64BitSignedEnums()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color : long { Red = -10 } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color : long { Red = -10 , Blue = -9 } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerateWithImplicitValues()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red , Green , Yellow = -1 }",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red , Green , Yellow = -1 , Blue = 2 }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerateWithImplicitValues2()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red , Green = 10 , Yellow }",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red , Green = 10 , Yellow , Blue }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestNoExtraneousStatementTerminatorBeforeCommentedMember()
{
await TestAsync(
@"class Program
{
static void Main(string[] args)
{
Color . [|Blue|] ;
}
}
enum Color
{
Red
//Blue
}",
@"class Program
{
static void Main(string[] args)
{
Color . Blue ;
}
}
enum Color
{
Red,
Blue
//Blue
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestNoExtraneousStatementTerminatorBeforeCommentedMember2()
{
await TestAsync(
@"class Program
{
static void Main(string[] args)
{
Color . [|Blue|] ;
}
}
enum Color
{
Red
/*Blue*/
}",
@"class Program
{
static void Main(string[] args)
{
Color . Blue ;
}
}
enum Color
{
Red,
Blue
/*Blue*/
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerateAfterEnumWithMinValue()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = int.MinValue } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = int.MinValue , Blue = -2147483647 } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerateAfterEnumWithMinValuePlusConstant()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = int.MinValue + 100 } ",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = int.MinValue + 100 , Blue = -2147483547 } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerateAfterEnumWithByteMaxValue()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color : byte { Red = 255 }",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color : byte { Red = 255 , Blue = 0 }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerateIntoBitshiftEnum1()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 1 << 1 , Green = 1 << 2 }",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 1 << 1 , Green = 1 << 2 , Blue = 1 << 3 }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerateIntoBitshiftEnum2()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = 2 >> 1 }",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = 2 >> 1 , Blue = 2 }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestStandaloneReference()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red = int.MinValue , Green = 1 }",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red = int.MinValue , Green = 1 , Blue = 2 }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestCircularEnumsForErrorTolerance()
{
await TestAsync(
@"class Program { void Main ( ) { Circular . [|C|] ; } } enum Circular { A = B , B }",
@"class Program { void Main ( ) { Circular . C ; } } enum Circular { A = B , B , C }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestEnumWithIncorrectValueForErrorTolerance()
{
await TestAsync(
@"class Program { void Main ( ) { Circular . [|B|] ; } } enum Circular : byte { A = -2 }",
@"class Program { void Main ( ) { Circular . B ; } } enum Circular : byte { A = -2 , B }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerateIntoNewEnum()
{
await TestAsync(
@"class B : A { void Main ( ) { BaseColor . [|Blue|] ; } public new enum BaseColor { Yellow = 3 } } class A { public enum BaseColor { Red = 1, Green = 2 } }",
@"class B : A { void Main ( ) { BaseColor . Blue ; } public new enum BaseColor { Yellow = 3 , Blue = 4 } } class A { public enum BaseColor { Red = 1, Green = 2 } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerateIntoDerivedEnumMissingNewKeyword()
{
await TestAsync(
@"class B : A { void Main ( ) { BaseColor . [|Blue|] ; } public enum BaseColor { Yellow = 3 } } class A { public enum BaseColor { Red = 1, Green = 2 } }",
@"class B : A { void Main ( ) { BaseColor . Blue ; } public enum BaseColor { Yellow = 3 , Blue = 4 } } class A { public enum BaseColor { Red = 1, Green = 2 } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerateIntoBaseEnum()
{
await TestAsync(
@"class B : A { void Main ( ) { BaseColor . [|Blue|] ; } } class A { public enum BaseColor { Red = 1, Green = 2 } }",
@"class B : A { void Main ( ) { BaseColor . Blue ; } } class A { public enum BaseColor { Red = 1, Green = 2 , Blue = 3 } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestGenerationWhenMembersShareValues()
{
await TestAsync(
@"class Program { void Main ( ) { Color . [|Blue|] ; } } enum Color { Red , Green , Yellow = Green }",
@"class Program { void Main ( ) { Color . Blue ; } } enum Color { Red , Green , Yellow = Green , Blue = 2 }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestInvokeFromAddAssignmentStatement()
{
await TestAsync(
@"class Program { void Main ( ) { int a = 1 ; a += Color . [|Blue|] ; } } enum Color { Red , Green = 10 , Yellow }",
@"class Program { void Main ( ) { int a = 1 ; a += Color . Blue ; } } enum Color { Red , Green = 10 , Yellow , Blue }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestFormatting()
{
await TestAsync(
@"class Program
{
static void Main(string[] args)
{
Weekday.[|Tuesday|];
}
}
enum Weekday
{
Monday
}",
@"class Program
{
static void Main(string[] args)
{
Weekday.Tuesday;
}
}
enum Weekday
{
Monday,
Tuesday
}",
compareTokens: false);
}
[WorkItem(540919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540919")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestKeyword()
{
await TestAsync(
@"class Program { static void Main ( string [ ] args ) { Color . [|@enum|] ; } } enum Color { Red } ",
@"class Program { static void Main ( string [ ] args ) { Color . @enum ; } } enum Color { Red , @enum } ");
}
[WorkItem(544333, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544333")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestNotAfterPointer()
{
await TestMissingAsync(
@"struct MyStruct { public int MyField ; } class Program { static unsafe void Main ( string [ ] args ) { MyStruct s = new MyStruct ( ) ; MyStruct * ptr = & s ; var i1 = ( ( ) => & s ) -> [|M|] ; } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestMissingOnHiddenEnum()
{
await TestMissingAsync(
@"using System;
enum E
{
#line hidden
}
#line default
class Program
{
void Main()
{
Console.WriteLine(E.[|x|]);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestMissingOnPartiallyHiddenEnum()
{
await TestMissingAsync(
@"using System;
enum E
{
A,
B,
C,
#line hidden
}
#line default
class Program
{
void Main()
{
Console.WriteLine(E.[|x|]);
}
}");
}
[WorkItem(545903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545903")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestNoOctal()
{
await TestAsync(
@"enum E { A = 007 , } class C { E x = E . [|B|] ; } ",
@"enum E { A = 007 , B = 8 , } class C { E x = E . B ; } ");
}
[WorkItem(546654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546654")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEnumMember)]
public async Task TestLastValueDoesNotHaveInitializer()
{
await TestAsync(
@"enum E { A = 1 , B } class Program { void Main ( ) { E . [|C|] } } ",
@"enum E { A = 1 , B , C } class Program { void Main ( ) { E . C } } ");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.UI.WebControls;
namespace MvcContrib.UI.DataList
{
/// <summary>
/// By default, the DataList displays the items in a single column, However, you can specify any number of columns.
/// </summary>
/// <example>
/// <code>
/// Html.DataList(_dataSource)
/// .NumberOfColumns(3)
/// .RepeatHorizontally()
/// .CellTemplate(x => { Writer.Write(x.ToLower()); })
/// .CellCondition(x => x == "test1")
/// .EmptyDateSourceTemplate(() => { Writer.Write("There is no data available."); })
/// .NoItemTemplate(() => { Writer.Write("No Data."); });
/// </code>
/// </example>
/// <typeparam name="T"></typeparam>
[Obsolete]
public class DataList<T>
{
private readonly IEnumerable<T> _dataSource;
private readonly Hash _tableAttributes;
private Action _emptyDataSourceTemplate;
private Action _noItemTemplate;
private Func<T, bool> _cellCondition = x => true;
private Hash _cellAttribute;
private const string TABLE = "table";
protected TextWriter Writer { get; set; }
/// <summary>
/// Gets or sets the repeat direction.
/// </summary>
/// <value>The repeat direction.</value>
public RepeatDirection RepeatDirection { get; set; }
/// <summary>
/// Gets or sets the the amount of columns to display.
/// </summary>
/// <remarks>
/// If this property is set to 0, the DataList will displays its items in a single row or column, based on the value of the RepeatDirection property.
/// </remarks>
/// <value>The repeat columns.</value>
public int RepeatColumns { get; protected set; }
/// <summary>
/// Gets or sets the item renderer. You should use <see cref="CellTemplate"/>
/// </summary>
/// <value>The item renderer.</value>
public virtual Action<T> ItemRenderer { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="DataList<T>"/> class.
/// </summary>
/// <param name="dataSource">The data source.</param>
/// <param name="writer">The writer.</param>
public DataList(IEnumerable<T> dataSource, TextWriter writer)
: this(dataSource, writer, null) { }
/// <summary>
/// Initializes a new instance of the <see cref="DataList<T>"/> class.
/// </summary>
/// <param name="dataSource">The data source.</param>
/// <param name="writer">The writer.</param>
/// <param name="tableAttributes">The table attributes.</param>
public DataList(IEnumerable<T> dataSource, TextWriter writer, Hash tableAttributes)
{
_dataSource = dataSource;
RepeatColumns = 0;
RepeatDirection = RepeatDirection.Vertical;
_tableAttributes = tableAttributes;
Writer = writer;
}
/// <summary>
/// The main cell template.
/// </summary>
/// <param name="contentTemplate">The template.</param>
/// <returns></returns>
public virtual DataList<T> CellTemplate(Action<T> contentTemplate)
{
ItemRenderer = contentTemplate;
return this;
}
protected void Write(string text)
{
Writer.Write(text);
}
/// <summary>
/// If you provide an empty date source the it will use this template in the first cell.
/// </summary>
/// <param name="template">The template.</param>
/// <returns></returns>
public virtual DataList<T> EmptyDateSourceTemplate(Action template)
{
_emptyDataSourceTemplate = template;
return this;
}
/// <summary>
/// If you have lets say two items and you repeat 3 times
/// then one cell is going to be empty so fill it with this template.
/// </summary>
/// <param name="template">The template.</param>
/// <returns></returns>
public virtual DataList<T> NoItemTemplate(Action template)
{
_noItemTemplate = template;
return this;
}
/// <summary>
/// Filters the items that will be rendered (This should normally be done in the database)
/// </summary>
/// <param name="func">The condition to check.</param>
/// <returns></returns>
public virtual DataList<T> CellCondition(Func<T, bool> func)
{
_cellCondition = func;
return this;
}
/// <summary>
/// Attributes that go on every cell (<td id="foo" class="bar">).
/// </summary>
/// <example>CellAttributes(id => "foo", @class => "bar")</example>
/// <param name="attributes">The attributes.</param>
/// <returns></returns>
public virtual DataList<T> CellAttributes(params Func<object, object>[] attributes)
{
_cellAttribute = new Hash(attributes);
return this;
}
/// <summary>
/// Checks if a item should be rendered, this checks <see cref="CellCondition" />.
/// </summary>
/// <param name="item">The item.</param>
/// <returns></returns>
protected virtual bool ShouldRenderCell(T item)
{
return _cellCondition(item);
}
/// <summary>
/// The amount of Columns to render.
/// </summary>
/// <param name="amount">The amount.</param>
/// <returns></returns>
public virtual DataList<T> NumberOfColumns(int amount)
{
RepeatColumns = amount;
return this;
}
/// <summary>
/// Repeats the items vertically.
/// </summary>
/// <returns></returns>
public DataList<T> RepeatVertically()
{
RepeatDirection = RepeatDirection.Vertical;
return this;
}
/// <summary>
/// Repeats the items horizontally.
/// </summary>
/// <returns></returns>
public DataList<T> RepeatHorizontally()
{
RepeatDirection = RepeatDirection.Horizontal;
return this;
}
/// <summary>
/// Renders the cell.
/// </summary>
/// <param name="item">The item.</param>
protected virtual void RenderCell(T item)
{
Writer.Write(string.Format("<td{0}>", BuildHtmlAttributes(_cellAttribute)));
if (ItemRenderer != null)
ItemRenderer(item);
Writer.Write("</td>");
}
/// <summary>
/// Renders this DataList.
/// </summary>
public virtual void Render()
{
Write(string.Format("<{0}{1}>", TABLE, BuildHtmlAttributes(_tableAttributes)));
BuildTable();
Write(string.Format("</{0}>", TABLE));
}
/// <summary>
/// Renders to the TextWriter, and returns null.
/// This is by design so that it can be used with inline syntax in views.
/// </summary>
/// <returns>null</returns>
public override string ToString()
{
Render();
return null;
}
private void BuildTable()
{
IList<T> items = _dataSource.Where(x => _cellCondition(x)).ToList();
if (items.Count < 1)
{
Write("<tr><td>");
if (_emptyDataSourceTemplate != null) _emptyDataSourceTemplate();
Write("</td></tr>");
return;
}
int tmpRepeatColumns = RepeatColumns < 1 ? 1 : RepeatColumns;
if (RepeatDirection == RepeatDirection.Horizontal)
RenderHorizontal(tmpRepeatColumns, items);
else
RenderVertical(tmpRepeatColumns, items);
}
private void RenderHorizontal(int repeatColumns, IList<T> items)
{
int rows = CalculateAmountOfRows(items.Count, repeatColumns);
int columns = repeatColumns;
int i = 0;
for (int row = 0; row < rows; row++)
{
Write("<tr>");
for (int column = 0; column < columns; column++)
{
if (i + 1 <= items.Count)
RenderCell(items[i]);
else
RenderNoItemCell();
i++;
}
Write("</tr>");
}
}
private void RenderVertical(int repeatColumns, IList<T> items)
{
int rows = CalculateAmountOfRows(items.Count, repeatColumns);
int columns = repeatColumns;
int i = 0;
for (int row = 0; row < rows; row++)
{
Write("<tr>");
for (int column = 0; column < columns; column++)
{
if (i + 1 <= items.Count)
{
if (column == 0)
RenderCell(items[row]);
else
RenderCell(items[((column * rows) + row)]);
}
else
RenderNoItemCell();
i++;
}
Write("</tr>");
}
}
private void RenderNoItemCell()
{
Write(string.Format("<td{0}>", BuildHtmlAttributes(_cellAttribute)));
if (_noItemTemplate != null)
_noItemTemplate();
Write("</td>");
}
private int CalculateAmountOfRows(int itemCount, int repeatColumns)
{
int columns = itemCount / repeatColumns;
if ((itemCount % repeatColumns) > 0)
columns += 1;
return columns;
}
private string BuildHtmlAttributes(IDictionary<string, object> attributes)
{
var attrs = DictionaryExtensions.ToHtmlAttributes(attributes);
if(attrs.Length > 0)
{
attrs = " " + attrs;
}
return attrs;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Compute.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedDisksClientTest
{
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetDiskRequest request = new GetDiskRequest
{
Disk = "disk028b6875",
Zone = "zone255f4ea8",
Project = "projectaa6ff846",
};
Disk expectedResponse = new Disk
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Type = "typee2cc9d59",
Zone = "zone255f4ea8",
ResourcePolicies =
{
"resource_policiesdff15734",
},
CreationTimestamp = "creation_timestamp235e59a1",
LastAttachTimestamp = "last_attach_timestamp4fe3fe94",
LicenseCodes =
{
-3549522739643304114L,
},
ReplicaZones =
{
"replica_zonesc1977354",
},
SourceImage = "source_image5e9c0c38",
SourceImageId = "source_image_id954b5e55",
LastDetachTimestamp = "last_detach_timestampffef196b",
GuestOsFeatures =
{
new GuestOsFeature(),
},
SourceSnapshotId = "source_snapshot_id008ab5dd",
Users = { "users2a5cc69b", },
SourceSnapshot = "source_snapshot1fcf3da1",
Region = "regionedb20d96",
LabelFingerprint = "label_fingerprint06ccff3a",
Status = Disk.Types.Status.Deleting,
ProvisionedIops = -3779563869670119518L,
SourceStorageObject = "source_storage_object4e059972",
DiskEncryptionKey = new CustomerEncryptionKey(),
SourceSnapshotEncryptionKey = new CustomerEncryptionKey(),
Licenses =
{
"licensesd1cc2f9d",
},
LocationHint = "location_hint666f366c",
Options = "optionsa965da93",
SourceImageEncryptionKey = new CustomerEncryptionKey(),
PhysicalBlockSizeBytes = -7292518380745299537L,
Description = "description2cf9da67",
SourceDisk = "source_disk0eec086f",
SourceDiskId = "source_disk_id020f9fb8",
SelfLink = "self_link7e87f12d",
SatisfiesPzs = false,
SizeGb = -3653169847519542788L,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null);
Disk response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetDiskRequest request = new GetDiskRequest
{
Disk = "disk028b6875",
Zone = "zone255f4ea8",
Project = "projectaa6ff846",
};
Disk expectedResponse = new Disk
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Type = "typee2cc9d59",
Zone = "zone255f4ea8",
ResourcePolicies =
{
"resource_policiesdff15734",
},
CreationTimestamp = "creation_timestamp235e59a1",
LastAttachTimestamp = "last_attach_timestamp4fe3fe94",
LicenseCodes =
{
-3549522739643304114L,
},
ReplicaZones =
{
"replica_zonesc1977354",
},
SourceImage = "source_image5e9c0c38",
SourceImageId = "source_image_id954b5e55",
LastDetachTimestamp = "last_detach_timestampffef196b",
GuestOsFeatures =
{
new GuestOsFeature(),
},
SourceSnapshotId = "source_snapshot_id008ab5dd",
Users = { "users2a5cc69b", },
SourceSnapshot = "source_snapshot1fcf3da1",
Region = "regionedb20d96",
LabelFingerprint = "label_fingerprint06ccff3a",
Status = Disk.Types.Status.Deleting,
ProvisionedIops = -3779563869670119518L,
SourceStorageObject = "source_storage_object4e059972",
DiskEncryptionKey = new CustomerEncryptionKey(),
SourceSnapshotEncryptionKey = new CustomerEncryptionKey(),
Licenses =
{
"licensesd1cc2f9d",
},
LocationHint = "location_hint666f366c",
Options = "optionsa965da93",
SourceImageEncryptionKey = new CustomerEncryptionKey(),
PhysicalBlockSizeBytes = -7292518380745299537L,
Description = "description2cf9da67",
SourceDisk = "source_disk0eec086f",
SourceDiskId = "source_disk_id020f9fb8",
SelfLink = "self_link7e87f12d",
SatisfiesPzs = false,
SizeGb = -3653169847519542788L,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Disk>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null);
Disk responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Disk responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetDiskRequest request = new GetDiskRequest
{
Disk = "disk028b6875",
Zone = "zone255f4ea8",
Project = "projectaa6ff846",
};
Disk expectedResponse = new Disk
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Type = "typee2cc9d59",
Zone = "zone255f4ea8",
ResourcePolicies =
{
"resource_policiesdff15734",
},
CreationTimestamp = "creation_timestamp235e59a1",
LastAttachTimestamp = "last_attach_timestamp4fe3fe94",
LicenseCodes =
{
-3549522739643304114L,
},
ReplicaZones =
{
"replica_zonesc1977354",
},
SourceImage = "source_image5e9c0c38",
SourceImageId = "source_image_id954b5e55",
LastDetachTimestamp = "last_detach_timestampffef196b",
GuestOsFeatures =
{
new GuestOsFeature(),
},
SourceSnapshotId = "source_snapshot_id008ab5dd",
Users = { "users2a5cc69b", },
SourceSnapshot = "source_snapshot1fcf3da1",
Region = "regionedb20d96",
LabelFingerprint = "label_fingerprint06ccff3a",
Status = Disk.Types.Status.Deleting,
ProvisionedIops = -3779563869670119518L,
SourceStorageObject = "source_storage_object4e059972",
DiskEncryptionKey = new CustomerEncryptionKey(),
SourceSnapshotEncryptionKey = new CustomerEncryptionKey(),
Licenses =
{
"licensesd1cc2f9d",
},
LocationHint = "location_hint666f366c",
Options = "optionsa965da93",
SourceImageEncryptionKey = new CustomerEncryptionKey(),
PhysicalBlockSizeBytes = -7292518380745299537L,
Description = "description2cf9da67",
SourceDisk = "source_disk0eec086f",
SourceDiskId = "source_disk_id020f9fb8",
SelfLink = "self_link7e87f12d",
SatisfiesPzs = false,
SizeGb = -3653169847519542788L,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null);
Disk response = client.Get(request.Project, request.Zone, request.Disk);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetDiskRequest request = new GetDiskRequest
{
Disk = "disk028b6875",
Zone = "zone255f4ea8",
Project = "projectaa6ff846",
};
Disk expectedResponse = new Disk
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Type = "typee2cc9d59",
Zone = "zone255f4ea8",
ResourcePolicies =
{
"resource_policiesdff15734",
},
CreationTimestamp = "creation_timestamp235e59a1",
LastAttachTimestamp = "last_attach_timestamp4fe3fe94",
LicenseCodes =
{
-3549522739643304114L,
},
ReplicaZones =
{
"replica_zonesc1977354",
},
SourceImage = "source_image5e9c0c38",
SourceImageId = "source_image_id954b5e55",
LastDetachTimestamp = "last_detach_timestampffef196b",
GuestOsFeatures =
{
new GuestOsFeature(),
},
SourceSnapshotId = "source_snapshot_id008ab5dd",
Users = { "users2a5cc69b", },
SourceSnapshot = "source_snapshot1fcf3da1",
Region = "regionedb20d96",
LabelFingerprint = "label_fingerprint06ccff3a",
Status = Disk.Types.Status.Deleting,
ProvisionedIops = -3779563869670119518L,
SourceStorageObject = "source_storage_object4e059972",
DiskEncryptionKey = new CustomerEncryptionKey(),
SourceSnapshotEncryptionKey = new CustomerEncryptionKey(),
Licenses =
{
"licensesd1cc2f9d",
},
LocationHint = "location_hint666f366c",
Options = "optionsa965da93",
SourceImageEncryptionKey = new CustomerEncryptionKey(),
PhysicalBlockSizeBytes = -7292518380745299537L,
Description = "description2cf9da67",
SourceDisk = "source_disk0eec086f",
SourceDiskId = "source_disk_id020f9fb8",
SelfLink = "self_link7e87f12d",
SatisfiesPzs = false,
SizeGb = -3653169847519542788L,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Disk>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null);
Disk responseCallSettings = await client.GetAsync(request.Project, request.Zone, request.Disk, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Disk responseCancellationToken = await client.GetAsync(request.Project, request.Zone, request.Disk, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyRequestObject()
{
moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyDiskRequest request = new GetIamPolicyDiskRequest
{
Zone = "zone255f4ea8",
Resource = "resource164eab96",
Project = "projectaa6ff846",
OptionsRequestedPolicyVersion = -1471234741,
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyRequestObjectAsync()
{
moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyDiskRequest request = new GetIamPolicyDiskRequest
{
Zone = "zone255f4ea8",
Resource = "resource164eab96",
Project = "projectaa6ff846",
OptionsRequestedPolicyVersion = -1471234741,
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicy()
{
moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyDiskRequest request = new GetIamPolicyDiskRequest
{
Zone = "zone255f4ea8",
Resource = "resource164eab96",
Project = "projectaa6ff846",
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetIamPolicy(request.Project, request.Zone, request.Resource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyAsync()
{
moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIamPolicyDiskRequest request = new GetIamPolicyDiskRequest
{
Zone = "zone255f4ea8",
Resource = "resource164eab96",
Project = "projectaa6ff846",
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetIamPolicyAsync(request.Project, request.Zone, request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Project, request.Zone, request.Resource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicyRequestObject()
{
moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyDiskRequest request = new SetIamPolicyDiskRequest
{
Zone = "zone255f4ea8",
Resource = "resource164eab96",
Project = "projectaa6ff846",
ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null);
Policy response = client.SetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyRequestObjectAsync()
{
moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyDiskRequest request = new SetIamPolicyDiskRequest
{
Zone = "zone255f4ea8",
Resource = "resource164eab96",
Project = "projectaa6ff846",
ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicy()
{
moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyDiskRequest request = new SetIamPolicyDiskRequest
{
Zone = "zone255f4ea8",
Resource = "resource164eab96",
Project = "projectaa6ff846",
ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null);
Policy response = client.SetIamPolicy(request.Project, request.Zone, request.Resource, request.ZoneSetPolicyRequestResource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyAsync()
{
moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
SetIamPolicyDiskRequest request = new SetIamPolicyDiskRequest
{
Zone = "zone255f4ea8",
Resource = "resource164eab96",
Project = "projectaa6ff846",
ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(),
};
Policy expectedResponse = new Policy
{
Etag = "etage8ad7218",
Rules = { new Rule(), },
AuditConfigs = { new AuditConfig(), },
Version = 271578922,
Bindings = { new Binding(), },
IamOwned = false,
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.SetIamPolicyAsync(request.Project, request.Zone, request.Resource, request.ZoneSetPolicyRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Project, request.Zone, request.Resource, request.ZoneSetPolicyRequestResource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsRequestObject()
{
moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsDiskRequest request = new TestIamPermissionsDiskRequest
{
Zone = "zone255f4ea8",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse response = client.TestIamPermissions(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsRequestObjectAsync()
{
moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsDiskRequest request = new TestIamPermissionsDiskRequest
{
Zone = "zone255f4ea8",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissions()
{
moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsDiskRequest request = new TestIamPermissionsDiskRequest
{
Zone = "zone255f4ea8",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse response = client.TestIamPermissions(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsAsync()
{
moq::Mock<Disks.DisksClient> mockGrpcClient = new moq::Mock<Disks.DisksClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsDiskRequest request = new TestIamPermissionsDiskRequest
{
Zone = "zone255f4ea8",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DisksClient client = new DisksClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System {
using System;
using System.Globalization;
using System.Text;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Diagnostics.Contracts;
// Represents a Globally Unique Identifier.
[StructLayout(LayoutKind.Sequential)]
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
[System.Runtime.Versioning.NonVersionable] // This only applies to field layout
public struct Guid : IFormattable, IComparable
, IComparable<Guid>, IEquatable<Guid>
{
public static readonly Guid Empty = new Guid();
////////////////////////////////////////////////////////////////////////////////
// Member variables
////////////////////////////////////////////////////////////////////////////////
private int _a;
private short _b;
private short _c;
private byte _d;
private byte _e;
private byte _f;
private byte _g;
private byte _h;
private byte _i;
private byte _j;
private byte _k;
////////////////////////////////////////////////////////////////////////////////
// Constructors
////////////////////////////////////////////////////////////////////////////////
// Creates a new guid from an array of bytes.
//
public Guid(byte[] b)
{
if (b==null)
throw new ArgumentNullException("b");
if (b.Length != 16)
throw new ArgumentException(Environment.GetResourceString("Arg_GuidArrayCtor", "16"));
Contract.EndContractBlock();
_a = ((int)b[3] << 24) | ((int)b[2] << 16) | ((int)b[1] << 8) | b[0];
_b = (short)(((int)b[5] << 8) | b[4]);
_c = (short)(((int)b[7] << 8) | b[6]);
_d = b[8];
_e = b[9];
_f = b[10];
_g = b[11];
_h = b[12];
_i = b[13];
_j = b[14];
_k = b[15];
}
[CLSCompliant(false)]
public Guid (uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k)
{
_a = (int)a;
_b = (short)b;
_c = (short)c;
_d = d;
_e = e;
_f = f;
_g = g;
_h = h;
_i = i;
_j = j;
_k = k;
}
// Creates a new GUID initialized to the value represented by the arguments.
//
public Guid(int a, short b, short c, byte[] d)
{
if (d==null)
throw new ArgumentNullException("d");
// Check that array is not too big
if(d.Length != 8)
throw new ArgumentException(Environment.GetResourceString("Arg_GuidArrayCtor", "8"));
Contract.EndContractBlock();
_a = a;
_b = b;
_c = c;
_d = d[0];
_e = d[1];
_f = d[2];
_g = d[3];
_h = d[4];
_i = d[5];
_j = d[6];
_k = d[7];
}
// Creates a new GUID initialized to the value represented by the
// arguments. The bytes are specified like this to avoid endianness issues.
//
public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k)
{
_a = a;
_b = b;
_c = c;
_d = d;
_e = e;
_f = f;
_g = g;
_h = h;
_i = i;
_j = j;
_k = k;
}
[Flags]
private enum GuidStyles {
None = 0x00000000,
AllowParenthesis = 0x00000001, //Allow the guid to be enclosed in parens
AllowBraces = 0x00000002, //Allow the guid to be enclosed in braces
AllowDashes = 0x00000004, //Allow the guid to contain dash group separators
AllowHexPrefix = 0x00000008, //Allow the guid to contain {0xdd,0xdd}
RequireParenthesis = 0x00000010, //Require the guid to be enclosed in parens
RequireBraces = 0x00000020, //Require the guid to be enclosed in braces
RequireDashes = 0x00000040, //Require the guid to contain dash group separators
RequireHexPrefix = 0x00000080, //Require the guid to contain {0xdd,0xdd}
HexFormat = RequireBraces | RequireHexPrefix, /* X */
NumberFormat = None, /* N */
DigitFormat = RequireDashes, /* D */
BraceFormat = RequireBraces | RequireDashes, /* B */
ParenthesisFormat = RequireParenthesis | RequireDashes, /* P */
Any = AllowParenthesis | AllowBraces | AllowDashes | AllowHexPrefix,
}
private enum GuidParseThrowStyle {
None = 0,
All = 1,
AllButOverflow = 2
}
private enum ParseFailureKind {
None = 0,
ArgumentNull = 1,
Format = 2,
FormatWithParameter = 3,
NativeException = 4,
FormatWithInnerException = 5
}
// This will store the result of the parsing. And it will eventually be used to construct a Guid instance.
private struct GuidResult {
internal Guid parsedGuid;
internal GuidParseThrowStyle throwStyle;
internal ParseFailureKind m_failure;
internal string m_failureMessageID;
internal object m_failureMessageFormatArgument;
internal string m_failureArgumentName;
internal Exception m_innerException;
internal void Init(GuidParseThrowStyle canThrow) {
parsedGuid = Guid.Empty;
throwStyle = canThrow;
}
internal void SetFailure(Exception nativeException) {
m_failure = ParseFailureKind.NativeException;
m_innerException = nativeException;
}
internal void SetFailure(ParseFailureKind failure, string failureMessageID) {
SetFailure(failure, failureMessageID, null, null, null);
}
internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument) {
SetFailure(failure, failureMessageID, failureMessageFormatArgument, null, null);
}
internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument,
string failureArgumentName, Exception innerException) {
Contract.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload");
m_failure = failure;
m_failureMessageID = failureMessageID;
m_failureMessageFormatArgument = failureMessageFormatArgument;
m_failureArgumentName = failureArgumentName;
m_innerException = innerException;
if (throwStyle != GuidParseThrowStyle.None) {
throw GetGuidParseException();
}
}
internal Exception GetGuidParseException() {
switch (m_failure) {
case ParseFailureKind.ArgumentNull:
return new ArgumentNullException(m_failureArgumentName, Environment.GetResourceString(m_failureMessageID));
case ParseFailureKind.FormatWithInnerException:
return new FormatException(Environment.GetResourceString(m_failureMessageID), m_innerException);
case ParseFailureKind.FormatWithParameter:
return new FormatException(Environment.GetResourceString(m_failureMessageID, m_failureMessageFormatArgument));
case ParseFailureKind.Format:
return new FormatException(Environment.GetResourceString(m_failureMessageID));
case ParseFailureKind.NativeException:
return m_innerException;
default:
Contract.Assert(false, "Unknown GuidParseFailure: " + m_failure);
return new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"));
}
}
}
// Creates a new guid based on the value in the string. The value is made up
// of hex digits speared by the dash ("-"). The string may begin and end with
// brackets ("{", "}").
//
// The string must be of the form dddddddd-dddd-dddd-dddd-dddddddddddd. where
// d is a hex digit. (That is 8 hex digits, followed by 4, then 4, then 4,
// then 12) such as: "CA761232-ED42-11CE-BACD-00AA0057B223"
//
public Guid(String g)
{
if (g==null) {
throw new ArgumentNullException("g");
}
Contract.EndContractBlock();
this = Guid.Empty;
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.All);
if (TryParseGuid(g, GuidStyles.Any, ref result)) {
this = result.parsedGuid;
}
else {
throw result.GetGuidParseException();
}
}
public static Guid Parse(String input)
{
if (input == null) {
throw new ArgumentNullException("input");
}
Contract.EndContractBlock();
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.AllButOverflow);
if (TryParseGuid(input, GuidStyles.Any, ref result)) {
return result.parsedGuid;
}
else {
throw result.GetGuidParseException();
}
}
public static bool TryParse(String input, out Guid result)
{
GuidResult parseResult = new GuidResult();
parseResult.Init(GuidParseThrowStyle.None);
if (TryParseGuid(input, GuidStyles.Any, ref parseResult)) {
result = parseResult.parsedGuid;
return true;
}
else {
result = Guid.Empty;
return false;
}
}
public static Guid ParseExact(String input, String format)
{
if (input == null)
throw new ArgumentNullException("input");
if (format == null)
throw new ArgumentNullException("format");
if( format.Length != 1) {
// all acceptable format strings are of length 1
throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification"));
}
GuidStyles style;
char formatCh = format[0];
if (formatCh == 'D' || formatCh == 'd') {
style = GuidStyles.DigitFormat;
}
else if (formatCh == 'N' || formatCh == 'n') {
style = GuidStyles.NumberFormat;
}
else if (formatCh == 'B' || formatCh == 'b') {
style = GuidStyles.BraceFormat;
}
else if (formatCh == 'P' || formatCh == 'p') {
style = GuidStyles.ParenthesisFormat;
}
else if (formatCh == 'X' || formatCh == 'x') {
style = GuidStyles.HexFormat;
}
else {
throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification"));
}
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.AllButOverflow);
if (TryParseGuid(input, style, ref result)) {
return result.parsedGuid;
}
else {
throw result.GetGuidParseException();
}
}
public static bool TryParseExact(String input, String format, out Guid result)
{
if (format == null || format.Length != 1) {
result = Guid.Empty;
return false;
}
GuidStyles style;
char formatCh = format[0];
if (formatCh == 'D' || formatCh == 'd') {
style = GuidStyles.DigitFormat;
}
else if (formatCh == 'N' || formatCh == 'n') {
style = GuidStyles.NumberFormat;
}
else if (formatCh == 'B' || formatCh == 'b') {
style = GuidStyles.BraceFormat;
}
else if (formatCh == 'P' || formatCh == 'p') {
style = GuidStyles.ParenthesisFormat;
}
else if (formatCh == 'X' || formatCh == 'x') {
style = GuidStyles.HexFormat;
}
else {
// invalid guid format specification
result = Guid.Empty;
return false;
}
GuidResult parseResult = new GuidResult();
parseResult.Init(GuidParseThrowStyle.None);
if (TryParseGuid(input, style, ref parseResult)) {
result = parseResult.parsedGuid;
return true;
}
else {
result = Guid.Empty;
return false;
}
}
private static bool TryParseGuid(String g, GuidStyles flags, ref GuidResult result)
{
if (g == null) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
String guidString = g.Trim(); //Remove Whitespace
if (guidString.Length == 0) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
// Check for dashes
bool dashesExistInString = (guidString.IndexOf('-', 0) >= 0);
if (dashesExistInString) {
if ((flags & (GuidStyles.AllowDashes | GuidStyles.RequireDashes)) == 0) {
// dashes are not allowed
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
else {
if ((flags & GuidStyles.RequireDashes) != 0) {
// dashes are required
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
// Check for braces
bool bracesExistInString = (guidString.IndexOf('{', 0) >= 0);
if (bracesExistInString) {
if ((flags & (GuidStyles.AllowBraces | GuidStyles.RequireBraces)) == 0) {
// braces are not allowed
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
else {
if ((flags & GuidStyles.RequireBraces) != 0) {
// braces are required
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
// Check for parenthesis
bool parenthesisExistInString = (guidString.IndexOf('(', 0) >= 0);
if (parenthesisExistInString) {
if ((flags & (GuidStyles.AllowParenthesis | GuidStyles.RequireParenthesis)) == 0) {
// parenthesis are not allowed
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
else {
if ((flags & GuidStyles.RequireParenthesis) != 0) {
// parenthesis are required
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
try {
// let's get on with the parsing
if (dashesExistInString) {
// Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)]
return TryParseGuidWithDashes(guidString, ref result);
}
else if (bracesExistInString) {
// Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
return TryParseGuidWithHexPrefix(guidString, ref result);
}
else {
// Check if it's of the form dddddddddddddddddddddddddddddddd
return TryParseGuidWithNoStyle(guidString, ref result);
}
}
catch(IndexOutOfRangeException ex) {
result.SetFailure(ParseFailureKind.FormatWithInnerException, "Format_GuidUnrecognized", null, null, ex);
return false;
}
catch (ArgumentException ex) {
result.SetFailure(ParseFailureKind.FormatWithInnerException, "Format_GuidUnrecognized", null, null, ex);
return false;
}
}
// Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
private static bool TryParseGuidWithHexPrefix(String guidString, ref GuidResult result) {
int numStart = 0;
int numLen = 0;
// Eat all of the whitespace
guidString = EatAllWhitespace(guidString);
// Check for leading '{'
if(String.IsNullOrEmpty(guidString) || guidString[0] != '{') {
result.SetFailure(ParseFailureKind.Format, "Format_GuidBrace");
return false;
}
// Check for '0x'
if(!IsHexPrefix(guidString, 1)) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, etc}");
return false;
}
// Find the end of this hex number (since it is not fixed length)
numStart = 3;
numLen = guidString.IndexOf(',', numStart) - numStart;
if(numLen <= 0) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
return false;
}
if (!StringToInt(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result))
return false;
// Check for '0x'
if(!IsHexPrefix(guidString, numStart+numLen+1)) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, 0xdddd, etc}");
return false;
}
// +3 to get by ',0x'
numStart = numStart + numLen + 3;
numLen = guidString.IndexOf(',', numStart) - numStart;
if(numLen <= 0) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
return false;
}
// Read in the number
if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result))
return false;
// Check for '0x'
if(!IsHexPrefix(guidString, numStart+numLen+1)) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, 0xdddd, 0xdddd, etc}");
return false;
}
// +3 to get by ',0x'
numStart = numStart + numLen + 3;
numLen = guidString.IndexOf(',', numStart) - numStart;
if(numLen <= 0) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
return false;
}
// Read in the number
if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result))
return false;
// Check for '{'
if(guidString.Length <= numStart+numLen+1 || guidString[numStart+numLen+1] != '{') {
result.SetFailure(ParseFailureKind.Format, "Format_GuidBrace");
return false;
}
// Prepare for loop
numLen++;
byte[] bytes = new byte[8];
for(int i = 0; i < 8; i++)
{
// Check for '0x'
if(!IsHexPrefix(guidString, numStart+numLen+1)) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{... { ... 0xdd, ...}}");
return false;
}
// +3 to get by ',0x' or '{0x' for first case
numStart = numStart + numLen + 3;
// Calculate number length
if(i < 7) // first 7 cases
{
numLen = guidString.IndexOf(',', numStart) - numStart;
if(numLen <= 0) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
return false;
}
}
else // last case ends with '}', not ','
{
numLen = guidString.IndexOf('}', numStart) - numStart;
if(numLen <= 0) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidBraceAfterLastNumber");
return false;
}
}
// Read in the number
int signedNumber;
if (!StringToInt(guidString.Substring(numStart, numLen), -1, ParseNumbers.IsTight, out signedNumber, ref result)) {
return false;
}
uint number = (uint)signedNumber;
// check for overflow
if(number > 255) {
result.SetFailure(ParseFailureKind.Format, "Overflow_Byte");
return false;
}
bytes[i] = (byte)number;
}
result.parsedGuid._d = bytes[0];
result.parsedGuid._e = bytes[1];
result.parsedGuid._f = bytes[2];
result.parsedGuid._g = bytes[3];
result.parsedGuid._h = bytes[4];
result.parsedGuid._i = bytes[5];
result.parsedGuid._j = bytes[6];
result.parsedGuid._k = bytes[7];
// Check for last '}'
if(numStart+numLen+1 >= guidString.Length || guidString[numStart+numLen+1] != '}') {
result.SetFailure(ParseFailureKind.Format, "Format_GuidEndBrace");
return false;
}
// Check if we have extra characters at the end
if( numStart+numLen+1 != guidString.Length -1) {
result.SetFailure(ParseFailureKind.Format, "Format_ExtraJunkAtEnd");
return false;
}
return true;
}
// Check if it's of the form dddddddddddddddddddddddddddddddd
private static bool TryParseGuidWithNoStyle(String guidString, ref GuidResult result) {
int startPos=0;
int temp;
long templ;
int currentPos = 0;
if(guidString.Length != 32) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
for(int i= 0; i< guidString.Length; i++) {
char ch = guidString[i];
if(ch >= '0' && ch <= '9') {
continue;
}
else {
char upperCaseCh = Char.ToUpper(ch, CultureInfo.InvariantCulture);
if(upperCaseCh >= 'A' && upperCaseCh <= 'F') {
continue;
}
}
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvalidChar");
return false;
}
if (!StringToInt(guidString.Substring(startPos, 8) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result))
return false;
startPos += 8;
if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result))
return false;
startPos += 4;
if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result))
return false;
startPos += 4;
if (!StringToInt(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out temp, ref result))
return false;
startPos += 4;
currentPos = startPos;
if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result))
return false;
if (currentPos - startPos!=12) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
result.parsedGuid._d = (byte)(temp>>8);
result.parsedGuid._e = (byte)(temp);
temp = (int)(templ >> 32);
result.parsedGuid._f = (byte)(temp>>8);
result.parsedGuid._g = (byte)(temp);
temp = (int)(templ);
result.parsedGuid._h = (byte)(temp>>24);
result.parsedGuid._i = (byte)(temp>>16);
result.parsedGuid._j = (byte)(temp>>8);
result.parsedGuid._k = (byte)(temp);
return true;
}
// Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)]
private static bool TryParseGuidWithDashes(String guidString, ref GuidResult result) {
int startPos=0;
int temp;
long templ;
int currentPos = 0;
// check to see that it's the proper length
if (guidString[0]=='{') {
if (guidString.Length!=38 || guidString[37]!='}') {
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
startPos=1;
}
else if (guidString[0]=='(') {
if (guidString.Length!=38 || guidString[37]!=')') {
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
startPos=1;
}
else if(guidString.Length != 36) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
if (guidString[8+startPos] != '-' ||
guidString[13+startPos] != '-' ||
guidString[18+startPos] != '-' ||
guidString[23+startPos] != '-') {
result.SetFailure(ParseFailureKind.Format, "Format_GuidDashes");
return false;
}
currentPos = startPos;
if (!StringToInt(guidString, ref currentPos, 8, ParseNumbers.NoSpace, out temp, ref result))
return false;
result.parsedGuid._a = temp;
++currentPos; //Increment past the '-';
if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result))
return false;
result.parsedGuid._b = (short)temp;
++currentPos; //Increment past the '-';
if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result))
return false;
result.parsedGuid._c = (short)temp;
++currentPos; //Increment past the '-';
if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result))
return false;
++currentPos; //Increment past the '-';
startPos=currentPos;
if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result))
return false;
if (currentPos - startPos != 12) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
result.parsedGuid._d = (byte)(temp>>8);
result.parsedGuid._e = (byte)(temp);
temp = (int)(templ >> 32);
result.parsedGuid._f = (byte)(temp>>8);
result.parsedGuid._g = (byte)(temp);
temp = (int)(templ);
result.parsedGuid._h = (byte)(temp>>24);
result.parsedGuid._i = (byte)(temp>>16);
result.parsedGuid._j = (byte)(temp>>8);
result.parsedGuid._k = (byte)(temp);
return true;
}
//
// StringToShort, StringToInt, and StringToLong are wrappers around COMUtilNative integer parsing routines;
[System.Security.SecuritySafeCritical]
private static unsafe bool StringToShort(String str, int requiredLength, int flags, out short result, ref GuidResult parseResult) {
return StringToShort(str, null, requiredLength, flags, out result, ref parseResult);
}
[System.Security.SecuritySafeCritical]
private static unsafe bool StringToShort(String str, ref int parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) {
fixed(int * ppos = &parsePos) {
return StringToShort(str, ppos, requiredLength, flags, out result, ref parseResult);
}
}
[System.Security.SecurityCritical]
private static unsafe bool StringToShort(String str, int* parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) {
result = 0;
int x;
bool retValue = StringToInt(str, parsePos, requiredLength, flags, out x, ref parseResult);
result = (short)x;
return retValue;
}
[System.Security.SecuritySafeCritical]
private static unsafe bool StringToInt(String str, int requiredLength, int flags, out int result, ref GuidResult parseResult) {
return StringToInt(str, null, requiredLength, flags, out result, ref parseResult);
}
[System.Security.SecuritySafeCritical]
private static unsafe bool StringToInt(String str, ref int parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) {
fixed(int * ppos = &parsePos) {
return StringToInt(str, ppos, requiredLength, flags, out result, ref parseResult);
}
}
[System.Security.SecurityCritical]
private static unsafe bool StringToInt(String str, int* parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) {
result = 0;
int currStart = (parsePos == null) ? 0 : (*parsePos);
try {
result = ParseNumbers.StringToInt(str, 16, flags, parsePos);
}
catch (OverflowException ex) {
if (parseResult.throwStyle == GuidParseThrowStyle.All) {
throw;
}
else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow) {
throw new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"), ex);
}
else {
parseResult.SetFailure(ex);
return false;
}
}
catch (Exception ex) {
if (parseResult.throwStyle == GuidParseThrowStyle.None) {
parseResult.SetFailure(ex);
return false;
}
else {
throw;
}
}
//If we didn't parse enough characters, there's clearly an error.
if (requiredLength != -1 && parsePos != null && (*parsePos) - currStart != requiredLength) {
parseResult.SetFailure(ParseFailureKind.Format, "Format_GuidInvalidChar");
return false;
}
return true;
}
[System.Security.SecuritySafeCritical]
private static unsafe bool StringToLong(String str, int flags, out long result, ref GuidResult parseResult) {
return StringToLong(str, null, flags, out result, ref parseResult);
}
[System.Security.SecuritySafeCritical]
private static unsafe bool StringToLong(String str, ref int parsePos, int flags, out long result, ref GuidResult parseResult) {
fixed(int * ppos = &parsePos) {
return StringToLong(str, ppos, flags, out result, ref parseResult);
}
}
[System.Security.SecuritySafeCritical]
private static unsafe bool StringToLong(String str, int* parsePos, int flags, out long result, ref GuidResult parseResult) {
result = 0;
try {
result = ParseNumbers.StringToLong(str, 16, flags, parsePos);
}
catch (OverflowException ex) {
if (parseResult.throwStyle == GuidParseThrowStyle.All) {
throw;
}
else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow) {
throw new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"), ex);
}
else {
parseResult.SetFailure(ex);
return false;
}
}
catch (Exception ex) {
if (parseResult.throwStyle == GuidParseThrowStyle.None) {
parseResult.SetFailure(ex);
return false;
}
else {
throw;
}
}
return true;
}
private static String EatAllWhitespace(String str)
{
int newLength = 0;
char[] chArr = new char[str.Length];
char curChar;
// Now get each char from str and if it is not whitespace add it to chArr
for(int i = 0; i < str.Length; i++)
{
curChar = str[i];
if(!Char.IsWhiteSpace(curChar))
{
chArr[newLength++] = curChar;
}
}
// Return a new string based on chArr
return new String(chArr, 0, newLength);
}
private static bool IsHexPrefix(String str, int i)
{
if(str.Length > i+1 && str[i] == '0' && (Char.ToLower(str[i+1], CultureInfo.InvariantCulture) == 'x'))
return true;
else
return false;
}
// Returns an unsigned byte array containing the GUID.
public byte[] ToByteArray()
{
byte[] g = new byte[16];
g[0] = (byte)(_a);
g[1] = (byte)(_a >> 8);
g[2] = (byte)(_a >> 16);
g[3] = (byte)(_a >> 24);
g[4] = (byte)(_b);
g[5] = (byte)(_b >> 8);
g[6] = (byte)(_c);
g[7] = (byte)(_c >> 8);
g[8] = _d;
g[9] = _e;
g[10] = _f;
g[11] = _g;
g[12] = _h;
g[13] = _i;
g[14] = _j;
g[15] = _k;
return g;
}
// Returns the guid in "registry" format.
public override String ToString()
{
return ToString("D",null);
}
public override int GetHashCode()
{
return _a ^ (((int)_b << 16) | (int)(ushort)_c) ^ (((int)_f << 24) | _k);
}
// Returns true if and only if the guid represented
// by o is the same as this instance.
public override bool Equals(Object o)
{
Guid g;
// Check that o is a Guid first
if(o == null || !(o is Guid))
return false;
else g = (Guid) o;
// Now compare each of the elements
if(g._a != _a)
return false;
if(g._b != _b)
return false;
if(g._c != _c)
return false;
if (g._d != _d)
return false;
if (g._e != _e)
return false;
if (g._f != _f)
return false;
if (g._g != _g)
return false;
if (g._h != _h)
return false;
if (g._i != _i)
return false;
if (g._j != _j)
return false;
if (g._k != _k)
return false;
return true;
}
public bool Equals(Guid g)
{
// Now compare each of the elements
if(g._a != _a)
return false;
if(g._b != _b)
return false;
if(g._c != _c)
return false;
if (g._d != _d)
return false;
if (g._e != _e)
return false;
if (g._f != _f)
return false;
if (g._g != _g)
return false;
if (g._h != _h)
return false;
if (g._i != _i)
return false;
if (g._j != _j)
return false;
if (g._k != _k)
return false;
return true;
}
private int GetResult(uint me, uint them) {
if (me<them) {
return -1;
}
return 1;
}
public int CompareTo(Object value) {
if (value == null) {
return 1;
}
if (!(value is Guid)) {
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeGuid"));
}
Guid g = (Guid)value;
if (g._a!=this._a) {
return GetResult((uint)this._a, (uint)g._a);
}
if (g._b!=this._b) {
return GetResult((uint)this._b, (uint)g._b);
}
if (g._c!=this._c) {
return GetResult((uint)this._c, (uint)g._c);
}
if (g._d!=this._d) {
return GetResult((uint)this._d, (uint)g._d);
}
if (g._e!=this._e) {
return GetResult((uint)this._e, (uint)g._e);
}
if (g._f!=this._f) {
return GetResult((uint)this._f, (uint)g._f);
}
if (g._g!=this._g) {
return GetResult((uint)this._g, (uint)g._g);
}
if (g._h!=this._h) {
return GetResult((uint)this._h, (uint)g._h);
}
if (g._i!=this._i) {
return GetResult((uint)this._i, (uint)g._i);
}
if (g._j!=this._j) {
return GetResult((uint)this._j, (uint)g._j);
}
if (g._k!=this._k) {
return GetResult((uint)this._k, (uint)g._k);
}
return 0;
}
public int CompareTo(Guid value)
{
if (value._a!=this._a) {
return GetResult((uint)this._a, (uint)value._a);
}
if (value._b!=this._b) {
return GetResult((uint)this._b, (uint)value._b);
}
if (value._c!=this._c) {
return GetResult((uint)this._c, (uint)value._c);
}
if (value._d!=this._d) {
return GetResult((uint)this._d, (uint)value._d);
}
if (value._e!=this._e) {
return GetResult((uint)this._e, (uint)value._e);
}
if (value._f!=this._f) {
return GetResult((uint)this._f, (uint)value._f);
}
if (value._g!=this._g) {
return GetResult((uint)this._g, (uint)value._g);
}
if (value._h!=this._h) {
return GetResult((uint)this._h, (uint)value._h);
}
if (value._i!=this._i) {
return GetResult((uint)this._i, (uint)value._i);
}
if (value._j!=this._j) {
return GetResult((uint)this._j, (uint)value._j);
}
if (value._k!=this._k) {
return GetResult((uint)this._k, (uint)value._k);
}
return 0;
}
public static bool operator ==(Guid a, Guid b)
{
// Now compare each of the elements
if(a._a != b._a)
return false;
if(a._b != b._b)
return false;
if(a._c != b._c)
return false;
if(a._d != b._d)
return false;
if(a._e != b._e)
return false;
if(a._f != b._f)
return false;
if(a._g != b._g)
return false;
if(a._h != b._h)
return false;
if(a._i != b._i)
return false;
if(a._j != b._j)
return false;
if(a._k != b._k)
return false;
return true;
}
public static bool operator !=(Guid a, Guid b)
{
return !(a == b);
}
// This will create a new guid. Since we've now decided that constructors should 0-init,
// we need a method that allows users to create a guid.
[System.Security.SecuritySafeCritical] // auto-generated
public static Guid NewGuid() {
// CoCreateGuid should never return Guid.Empty, since it attempts to maintain some
// uniqueness guarantees. It should also never return a known GUID, but it's unclear
// how extensively it checks for known values.
Contract.Ensures(Contract.Result<Guid>() != Guid.Empty);
Guid guid;
Marshal.ThrowExceptionForHR(Win32Native.CoCreateGuid(out guid), new IntPtr(-1));
return guid;
}
public String ToString(String format) {
return ToString(format, null);
}
private static char HexToChar(int a)
{
a = a & 0xf;
return (char) ((a > 9) ? a - 10 + 0x61 : a + 0x30);
}
[System.Security.SecurityCritical]
unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b)
{
return HexsToChars(guidChars, offset, a, b, false);
}
[System.Security.SecurityCritical]
unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b, bool hex)
{
if (hex) {
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
}
guidChars[offset++] = HexToChar(a>>4);
guidChars[offset++] = HexToChar(a);
if (hex) {
guidChars[offset++] = ',';
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
}
guidChars[offset++] = HexToChar(b>>4);
guidChars[offset++] = HexToChar(b);
return offset;
}
// IFormattable interface
// We currently ignore provider
[System.Security.SecuritySafeCritical]
public String ToString(String format, IFormatProvider provider)
{
if (format == null || format.Length == 0)
format = "D";
string guidString;
int offset = 0;
bool dash = true;
bool hex = false;
if( format.Length != 1) {
// all acceptable format strings are of length 1
throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification"));
}
char formatCh = format[0];
if (formatCh == 'D' || formatCh == 'd') {
guidString = string.FastAllocateString(36);
}
else if (formatCh == 'N' || formatCh == 'n') {
guidString = string.FastAllocateString(32);
dash = false;
}
else if (formatCh == 'B' || formatCh == 'b') {
guidString = string.FastAllocateString(38);
unsafe {
fixed (char* guidChars = guidString) {
guidChars[offset++] = '{';
guidChars[37] = '}';
}
}
}
else if (formatCh == 'P' || formatCh == 'p') {
guidString = string.FastAllocateString(38);
unsafe {
fixed (char* guidChars = guidString) {
guidChars[offset++] = '(';
guidChars[37] = ')';
}
}
}
else if (formatCh == 'X' || formatCh == 'x') {
guidString = string.FastAllocateString(68);
unsafe {
fixed (char* guidChars = guidString) {
guidChars[offset++] = '{';
guidChars[67] = '}';
}
}
dash = false;
hex = true;
}
else {
throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification"));
}
unsafe {
fixed (char* guidChars = guidString) {
if (hex) {
// {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16);
offset = HexsToChars(guidChars, offset, _a >> 8, _a);
guidChars[offset++] = ',';
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
offset = HexsToChars(guidChars, offset, _b >> 8, _b);
guidChars[offset++] = ',';
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
offset = HexsToChars(guidChars, offset, _c >> 8, _c);
guidChars[offset++] = ',';
guidChars[offset++] = '{';
offset = HexsToChars(guidChars, offset, _d, _e, true);
guidChars[offset++] = ',';
offset = HexsToChars(guidChars, offset, _f, _g, true);
guidChars[offset++] = ',';
offset = HexsToChars(guidChars, offset, _h, _i, true);
guidChars[offset++] = ',';
offset = HexsToChars(guidChars, offset, _j, _k, true);
guidChars[offset++] = '}';
}
else {
// [{|(]dddddddd[-]dddd[-]dddd[-]dddd[-]dddddddddddd[}|)]
offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16);
offset = HexsToChars(guidChars, offset, _a >> 8, _a);
if (dash) guidChars[offset++] = '-';
offset = HexsToChars(guidChars, offset, _b >> 8, _b);
if (dash) guidChars[offset++] = '-';
offset = HexsToChars(guidChars, offset, _c >> 8, _c);
if (dash) guidChars[offset++] = '-';
offset = HexsToChars(guidChars, offset, _d, _e);
if (dash) guidChars[offset++] = '-';
offset = HexsToChars(guidChars, offset, _f, _g);
offset = HexsToChars(guidChars, offset, _h, _i);
offset = HexsToChars(guidChars, offset, _j, _k);
}
}
}
return guidString;
}
}
}
| |
// Copyright (c) 2015-present, Parse, LLC. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Parse.Internal;
namespace Parse.Internal {
internal class ParseCorePlugins {
private static readonly ParseCorePlugins instance = new ParseCorePlugins();
public static ParseCorePlugins Instance {
get {
return instance;
}
}
private readonly object mutex = new object();
#region Server Controllers
private IParseAnalyticsController analyticsController;
private IParseCloudCodeController cloudCodeController;
private IParseConfigController configController;
private IParseFileController fileController;
private IParseObjectController objectController;
private IParseQueryController queryController;
private IParseSessionController sessionController;
private IParseUserController userController;
private IParsePushController pushController;
private IParsePushChannelsController pushChannelsController;
private IObjectSubclassingController subclassingController;
#endregion
#region Current Instance Controller
private IInstallationIdController installationIdController;
private IParseCurrentInstallationController currentInstallationController;
private IParseCurrentUserController currentUserController;
#endregion
internal void Reset() {
lock (mutex) {
AnalyticsController = null;
CloudCodeController = null;
FileController = null;
ObjectController = null;
SessionController = null;
UserController = null;
CurrentInstallationController = null;
CurrentUserController = null;
}
}
public IParseAnalyticsController AnalyticsController {
get {
lock (mutex) {
analyticsController = analyticsController ?? new ParseAnalyticsController(ParseClient.ParseCommandRunner);
return analyticsController;
}
}
internal set {
lock (mutex) {
analyticsController = value;
}
}
}
public IParseCloudCodeController CloudCodeController {
get {
lock (mutex) {
cloudCodeController = cloudCodeController ?? new ParseCloudCodeController(ParseClient.ParseCommandRunner);
return cloudCodeController;
}
}
internal set {
lock (mutex) {
cloudCodeController = value;
}
}
}
public IParseFileController FileController {
get {
lock (mutex) {
fileController = fileController ?? new ParseFileController(ParseClient.ParseCommandRunner);
return fileController;
}
}
internal set {
lock (mutex) {
fileController = value;
}
}
}
public IParseConfigController ConfigController {
get {
lock (mutex) {
if (configController == null) {
configController = new ParseConfigController();
}
return configController;
}
}
internal set {
lock (mutex) {
configController = value;
}
}
}
public IParseObjectController ObjectController {
get {
lock (mutex) {
objectController = objectController ?? new ParseObjectController(ParseClient.ParseCommandRunner);
return objectController;
}
}
internal set {
lock (mutex) {
objectController = value;
}
}
}
public IParseQueryController QueryController {
get {
lock (mutex) {
if (queryController == null) {
queryController = new ParseQueryController();
}
return queryController;
}
}
internal set {
lock (mutex) {
queryController = value;
}
}
}
public IParseSessionController SessionController {
get {
lock (mutex) {
sessionController = sessionController ?? new ParseSessionController(ParseClient.ParseCommandRunner);
return sessionController;
}
}
internal set {
lock (mutex) {
sessionController = value;
}
}
}
public IParseUserController UserController {
get {
lock (mutex) {
userController = userController ?? new ParseUserController(ParseClient.ParseCommandRunner);
return userController;
}
}
internal set {
lock (mutex) {
userController = value;
}
}
}
public IParsePushController PushController {
get {
lock (mutex) {
pushController = pushController ?? new ParsePushController();
return pushController;
}
}
internal set {
lock (mutex) {
pushController = value;
}
}
}
public IParsePushChannelsController PushChannelsController {
get {
lock (mutex) {
pushChannelsController = pushChannelsController ?? new ParsePushChannelsController();
return pushChannelsController;
}
}
internal set {
lock (mutex) {
pushChannelsController = value;
}
}
}
public IInstallationIdController InstallationIdController {
get {
lock (mutex) {
installationIdController = installationIdController ?? new InstallationIdController();
return installationIdController;
}
}
internal set {
lock (mutex) {
installationIdController = value;
}
}
}
public IParseCurrentInstallationController CurrentInstallationController {
get {
lock (mutex) {
if (currentInstallationController == null) {
currentInstallationController = new ParseCurrentInstallationController(InstallationIdController);
}
return currentInstallationController;
}
}
internal set {
lock (mutex) {
currentInstallationController = value;
}
}
}
public IParseCurrentUserController CurrentUserController {
get {
lock (mutex) {
currentUserController = currentUserController ?? new ParseCurrentUserController();
return currentUserController;
}
}
internal set {
lock (mutex) {
currentUserController = value;
}
}
}
public IObjectSubclassingController SubclassingController {
get {
lock (mutex) {
subclassingController = subclassingController ?? new ObjectSubclassingController(new Dictionary<Type, Action> {
// Do these as explicit closures instead of method references,
// as we should still lazy-load the controllers.
{ typeof(ParseUser), () => CurrentUserController.ClearFromMemory() },
{ typeof(ParseInstallation), () => CurrentInstallationController.ClearFromMemory() }
});
return subclassingController;
}
}
internal set {
lock (mutex) {
subclassingController = value;
}
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Controls.TextBlock.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Controls
{
public partial class TextBlock : System.Windows.FrameworkElement, System.Windows.IContentHost, System.Windows.Markup.IAddChild, IServiceProvider
{
#region Methods and constructors
protected sealed override System.Windows.Size ArrangeOverride(System.Windows.Size arrangeSize)
{
return default(System.Windows.Size);
}
public static double GetBaselineOffset(System.Windows.DependencyObject element)
{
return default(double);
}
public static System.Windows.Media.FontFamily GetFontFamily(System.Windows.DependencyObject element)
{
return default(System.Windows.Media.FontFamily);
}
public static double GetFontSize(System.Windows.DependencyObject element)
{
return default(double);
}
public static System.Windows.FontStretch GetFontStretch(System.Windows.DependencyObject element)
{
return default(System.Windows.FontStretch);
}
public static System.Windows.FontStyle GetFontStyle(System.Windows.DependencyObject element)
{
return default(System.Windows.FontStyle);
}
public static System.Windows.FontWeight GetFontWeight(System.Windows.DependencyObject element)
{
return default(System.Windows.FontWeight);
}
public static System.Windows.Media.Brush GetForeground(System.Windows.DependencyObject element)
{
return default(System.Windows.Media.Brush);
}
public static double GetLineHeight(System.Windows.DependencyObject element)
{
return default(double);
}
public static System.Windows.LineStackingStrategy GetLineStackingStrategy(System.Windows.DependencyObject element)
{
return default(System.Windows.LineStackingStrategy);
}
public System.Windows.Documents.TextPointer GetPositionFromPoint(System.Windows.Point point, bool snapToText)
{
return default(System.Windows.Documents.TextPointer);
}
protected virtual new System.Collections.ObjectModel.ReadOnlyCollection<System.Windows.Rect> GetRectanglesCore(System.Windows.ContentElement child)
{
return default(System.Collections.ObjectModel.ReadOnlyCollection<System.Windows.Rect>);
}
public static System.Windows.TextAlignment GetTextAlignment(System.Windows.DependencyObject element)
{
return default(System.Windows.TextAlignment);
}
protected override System.Windows.Media.Visual GetVisualChild(int index)
{
return default(System.Windows.Media.Visual);
}
protected sealed override System.Windows.Media.HitTestResult HitTestCore(System.Windows.Media.PointHitTestParameters hitTestParameters)
{
return default(System.Windows.Media.HitTestResult);
}
protected virtual new System.Windows.IInputElement InputHitTestCore(System.Windows.Point point)
{
return default(System.Windows.IInputElement);
}
protected sealed override System.Windows.Size MeasureOverride(System.Windows.Size constraint)
{
return default(System.Windows.Size);
}
protected virtual new void OnChildDesiredSizeChangedCore(System.Windows.UIElement child)
{
}
protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer()
{
return default(System.Windows.Automation.Peers.AutomationPeer);
}
protected sealed override void OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs e)
{
}
protected sealed override void OnRender(System.Windows.Media.DrawingContext ctx)
{
}
public static void SetBaselineOffset(System.Windows.DependencyObject element, double value)
{
}
public static void SetFontFamily(System.Windows.DependencyObject element, System.Windows.Media.FontFamily value)
{
}
public static void SetFontSize(System.Windows.DependencyObject element, double value)
{
}
public static void SetFontStretch(System.Windows.DependencyObject element, System.Windows.FontStretch value)
{
}
public static void SetFontStyle(System.Windows.DependencyObject element, System.Windows.FontStyle value)
{
}
public static void SetFontWeight(System.Windows.DependencyObject element, System.Windows.FontWeight value)
{
}
public static void SetForeground(System.Windows.DependencyObject element, System.Windows.Media.Brush value)
{
}
public static void SetLineHeight(System.Windows.DependencyObject element, double value)
{
}
public static void SetLineStackingStrategy(System.Windows.DependencyObject element, System.Windows.LineStackingStrategy value)
{
}
public static void SetTextAlignment(System.Windows.DependencyObject element, System.Windows.TextAlignment value)
{
}
public bool ShouldSerializeBaselineOffset()
{
return default(bool);
}
public bool ShouldSerializeInlines(System.Windows.Markup.XamlDesignerSerializationManager manager)
{
return default(bool);
}
public bool ShouldSerializeText()
{
return default(bool);
}
Object System.IServiceProvider.GetService(Type serviceType)
{
return default(Object);
}
System.Collections.ObjectModel.ReadOnlyCollection<System.Windows.Rect> System.Windows.IContentHost.GetRectangles(System.Windows.ContentElement child)
{
return default(System.Collections.ObjectModel.ReadOnlyCollection<System.Windows.Rect>);
}
System.Windows.IInputElement System.Windows.IContentHost.InputHitTest(System.Windows.Point point)
{
return default(System.Windows.IInputElement);
}
void System.Windows.IContentHost.OnChildDesiredSizeChanged(System.Windows.UIElement child)
{
}
void System.Windows.Markup.IAddChild.AddChild(Object value)
{
}
void System.Windows.Markup.IAddChild.AddText(string text)
{
}
public TextBlock(System.Windows.Documents.Inline inline)
{
Contract.Ensures(0 <= this.Inlines.Count);
}
public TextBlock()
{
}
#endregion
#region Properties and indexers
public System.Windows.Media.Brush Background
{
get
{
return default(System.Windows.Media.Brush);
}
set
{
}
}
public double BaselineOffset
{
get
{
return default(double);
}
set
{
}
}
public System.Windows.LineBreakCondition BreakAfter
{
get
{
Contract.Ensures(Contract.Result<System.Windows.LineBreakCondition>() == ((System.Windows.LineBreakCondition)(0)));
return default(System.Windows.LineBreakCondition);
}
}
public System.Windows.LineBreakCondition BreakBefore
{
get
{
Contract.Ensures(Contract.Result<System.Windows.LineBreakCondition>() == ((System.Windows.LineBreakCondition)(0)));
return default(System.Windows.LineBreakCondition);
}
}
public System.Windows.Documents.TextPointer ContentEnd
{
get
{
return default(System.Windows.Documents.TextPointer);
}
}
public System.Windows.Documents.TextPointer ContentStart
{
get
{
return default(System.Windows.Documents.TextPointer);
}
}
public System.Windows.Media.FontFamily FontFamily
{
get
{
return default(System.Windows.Media.FontFamily);
}
set
{
}
}
public double FontSize
{
get
{
return default(double);
}
set
{
}
}
public System.Windows.FontStretch FontStretch
{
get
{
return default(System.Windows.FontStretch);
}
set
{
}
}
public System.Windows.FontStyle FontStyle
{
get
{
return default(System.Windows.FontStyle);
}
set
{
}
}
public System.Windows.FontWeight FontWeight
{
get
{
return default(System.Windows.FontWeight);
}
set
{
}
}
public System.Windows.Media.Brush Foreground
{
get
{
return default(System.Windows.Media.Brush);
}
set
{
}
}
protected virtual new IEnumerator<System.Windows.IInputElement> HostedElementsCore
{
get
{
return default(IEnumerator<System.Windows.IInputElement>);
}
}
public System.Windows.Documents.InlineCollection Inlines
{
get
{
Contract.Ensures(Contract.Result<System.Windows.Documents.InlineCollection>() != null);
return default(System.Windows.Documents.InlineCollection);
}
}
public bool IsHyphenationEnabled
{
get
{
return default(bool);
}
set
{
}
}
public double LineHeight
{
get
{
return default(double);
}
set
{
}
}
public System.Windows.LineStackingStrategy LineStackingStrategy
{
get
{
return default(System.Windows.LineStackingStrategy);
}
set
{
}
}
internal protected override System.Collections.IEnumerator LogicalChildren
{
get
{
return default(System.Collections.IEnumerator);
}
}
public System.Windows.Thickness Padding
{
get
{
return default(System.Windows.Thickness);
}
set
{
}
}
IEnumerator<System.Windows.IInputElement> System.Windows.IContentHost.HostedElements
{
get
{
return default(IEnumerator<System.Windows.IInputElement>);
}
}
public string Text
{
get
{
return default(string);
}
set
{
}
}
public System.Windows.TextAlignment TextAlignment
{
get
{
return default(System.Windows.TextAlignment);
}
set
{
}
}
public System.Windows.TextDecorationCollection TextDecorations
{
get
{
return default(System.Windows.TextDecorationCollection);
}
set
{
}
}
public System.Windows.Media.TextEffectCollection TextEffects
{
get
{
return default(System.Windows.Media.TextEffectCollection);
}
set
{
}
}
public System.Windows.TextTrimming TextTrimming
{
get
{
return default(System.Windows.TextTrimming);
}
set
{
}
}
public System.Windows.TextWrapping TextWrapping
{
get
{
return default(System.Windows.TextWrapping);
}
set
{
}
}
public System.Windows.Documents.Typography Typography
{
get
{
Contract.Ensures(Contract.Result<System.Windows.Documents.Typography>() != null);
return default(System.Windows.Documents.Typography);
}
}
protected override int VisualChildrenCount
{
get
{
return default(int);
}
}
#endregion
#region Fields
public readonly static System.Windows.DependencyProperty BackgroundProperty;
public readonly static System.Windows.DependencyProperty BaselineOffsetProperty;
public readonly static System.Windows.DependencyProperty FontFamilyProperty;
public readonly static System.Windows.DependencyProperty FontSizeProperty;
public readonly static System.Windows.DependencyProperty FontStretchProperty;
public readonly static System.Windows.DependencyProperty FontStyleProperty;
public readonly static System.Windows.DependencyProperty FontWeightProperty;
public readonly static System.Windows.DependencyProperty ForegroundProperty;
public readonly static System.Windows.DependencyProperty IsHyphenationEnabledProperty;
public readonly static System.Windows.DependencyProperty LineHeightProperty;
public readonly static System.Windows.DependencyProperty LineStackingStrategyProperty;
public readonly static System.Windows.DependencyProperty PaddingProperty;
public readonly static System.Windows.DependencyProperty TextAlignmentProperty;
public readonly static System.Windows.DependencyProperty TextDecorationsProperty;
public readonly static System.Windows.DependencyProperty TextEffectsProperty;
public readonly static System.Windows.DependencyProperty TextProperty;
public readonly static System.Windows.DependencyProperty TextTrimmingProperty;
public readonly static System.Windows.DependencyProperty TextWrappingProperty;
#endregion
}
}
| |
// Copyright 2016, Google Inc. 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.
// Generated code. DO NOT EDIT!
using Google.Api;
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Monitoring.V3;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Monitoring.V3.Snippets
{
public class GeneratedMetricServiceClientSnippets
{
public async Task ListMonitoredResourceDescriptorsAsync()
{
// Snippet: ListMonitoredResourceDescriptorsAsync(string,string,int?,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
string formattedName = MetricServiceClient.FormatProjectName("[PROJECT]");
// Make the request
IPagedAsyncEnumerable<ListMonitoredResourceDescriptorsResponse,MonitoredResourceDescriptor> response =
metricServiceClient.ListMonitoredResourceDescriptorsAsync(formattedName);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((MonitoredResourceDescriptor item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over fixed-sized pages, lazily performing RPCs as required
int pageSize = 10;
IAsyncEnumerable<FixedSizePage<MonitoredResourceDescriptor>> fixedSizePages = response.AsPages().WithFixedSize(pageSize);
await fixedSizePages.ForEachAsync((FixedSizePage<MonitoredResourceDescriptor> page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MonitoredResourceDescriptor item in page)
{
Console.WriteLine(item);
}
});
// End snippet
}
public void ListMonitoredResourceDescriptors()
{
// Snippet: ListMonitoredResourceDescriptors(string,string,int?,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
string formattedName = MetricServiceClient.FormatProjectName("[PROJECT]");
// Make the request
IPagedEnumerable<ListMonitoredResourceDescriptorsResponse,MonitoredResourceDescriptor> response =
metricServiceClient.ListMonitoredResourceDescriptors(formattedName);
// Iterate over all response items, lazily performing RPCs as required
foreach (MonitoredResourceDescriptor item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over fixed-sized pages, lazily performing RPCs as required
int pageSize = 10;
foreach (FixedSizePage<MonitoredResourceDescriptor> page in response.AsPages().WithFixedSize(pageSize))
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MonitoredResourceDescriptor item in page)
{
Console.WriteLine(item);
}
}
// End snippet
}
public async Task GetMonitoredResourceDescriptorAsync()
{
// Snippet: GetMonitoredResourceDescriptorAsync(string,CallSettings)
// Additional: GetMonitoredResourceDescriptorAsync(string,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
string formattedName = MetricServiceClient.FormatMonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]");
// Make the request
MonitoredResourceDescriptor response = await metricServiceClient.GetMonitoredResourceDescriptorAsync(formattedName);
// End snippet
}
public void GetMonitoredResourceDescriptor()
{
// Snippet: GetMonitoredResourceDescriptor(string,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
string formattedName = MetricServiceClient.FormatMonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]");
// Make the request
MonitoredResourceDescriptor response = metricServiceClient.GetMonitoredResourceDescriptor(formattedName);
// End snippet
}
public async Task ListMetricDescriptorsAsync()
{
// Snippet: ListMetricDescriptorsAsync(string,string,int?,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
string formattedName = MetricServiceClient.FormatProjectName("[PROJECT]");
// Make the request
IPagedAsyncEnumerable<ListMetricDescriptorsResponse,MetricDescriptor> response =
metricServiceClient.ListMetricDescriptorsAsync(formattedName);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((MetricDescriptor item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over fixed-sized pages, lazily performing RPCs as required
int pageSize = 10;
IAsyncEnumerable<FixedSizePage<MetricDescriptor>> fixedSizePages = response.AsPages().WithFixedSize(pageSize);
await fixedSizePages.ForEachAsync((FixedSizePage<MetricDescriptor> page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MetricDescriptor item in page)
{
Console.WriteLine(item);
}
});
// End snippet
}
public void ListMetricDescriptors()
{
// Snippet: ListMetricDescriptors(string,string,int?,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
string formattedName = MetricServiceClient.FormatProjectName("[PROJECT]");
// Make the request
IPagedEnumerable<ListMetricDescriptorsResponse,MetricDescriptor> response =
metricServiceClient.ListMetricDescriptors(formattedName);
// Iterate over all response items, lazily performing RPCs as required
foreach (MetricDescriptor item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over fixed-sized pages, lazily performing RPCs as required
int pageSize = 10;
foreach (FixedSizePage<MetricDescriptor> page in response.AsPages().WithFixedSize(pageSize))
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MetricDescriptor item in page)
{
Console.WriteLine(item);
}
}
// End snippet
}
public async Task GetMetricDescriptorAsync()
{
// Snippet: GetMetricDescriptorAsync(string,CallSettings)
// Additional: GetMetricDescriptorAsync(string,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
string formattedName = MetricServiceClient.FormatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]");
// Make the request
MetricDescriptor response = await metricServiceClient.GetMetricDescriptorAsync(formattedName);
// End snippet
}
public void GetMetricDescriptor()
{
// Snippet: GetMetricDescriptor(string,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
string formattedName = MetricServiceClient.FormatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]");
// Make the request
MetricDescriptor response = metricServiceClient.GetMetricDescriptor(formattedName);
// End snippet
}
public async Task CreateMetricDescriptorAsync()
{
// Snippet: CreateMetricDescriptorAsync(string,MetricDescriptor,CallSettings)
// Additional: CreateMetricDescriptorAsync(string,MetricDescriptor,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
string formattedName = MetricServiceClient.FormatProjectName("[PROJECT]");
MetricDescriptor metricDescriptor = new MetricDescriptor();
// Make the request
MetricDescriptor response = await metricServiceClient.CreateMetricDescriptorAsync(formattedName, metricDescriptor);
// End snippet
}
public void CreateMetricDescriptor()
{
// Snippet: CreateMetricDescriptor(string,MetricDescriptor,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
string formattedName = MetricServiceClient.FormatProjectName("[PROJECT]");
MetricDescriptor metricDescriptor = new MetricDescriptor();
// Make the request
MetricDescriptor response = metricServiceClient.CreateMetricDescriptor(formattedName, metricDescriptor);
// End snippet
}
public async Task DeleteMetricDescriptorAsync()
{
// Snippet: DeleteMetricDescriptorAsync(string,CallSettings)
// Additional: DeleteMetricDescriptorAsync(string,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
string formattedName = MetricServiceClient.FormatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]");
// Make the request
await metricServiceClient.DeleteMetricDescriptorAsync(formattedName);
// End snippet
}
public void DeleteMetricDescriptor()
{
// Snippet: DeleteMetricDescriptor(string,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
string formattedName = MetricServiceClient.FormatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]");
// Make the request
metricServiceClient.DeleteMetricDescriptor(formattedName);
// End snippet
}
public async Task ListTimeSeriesAsync()
{
// Snippet: ListTimeSeriesAsync(string,string,TimeInterval,ListTimeSeriesRequest.Types.TimeSeriesView,string,int?,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
string formattedName = MetricServiceClient.FormatProjectName("[PROJECT]");
string filter = "";
TimeInterval interval = new TimeInterval();
ListTimeSeriesRequest.Types.TimeSeriesView view = ListTimeSeriesRequest.Types.TimeSeriesView.Full;
// Make the request
IPagedAsyncEnumerable<ListTimeSeriesResponse,TimeSeries> response =
metricServiceClient.ListTimeSeriesAsync(formattedName, filter, interval, view);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TimeSeries item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over fixed-sized pages, lazily performing RPCs as required
int pageSize = 10;
IAsyncEnumerable<FixedSizePage<TimeSeries>> fixedSizePages = response.AsPages().WithFixedSize(pageSize);
await fixedSizePages.ForEachAsync((FixedSizePage<TimeSeries> page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TimeSeries item in page)
{
Console.WriteLine(item);
}
});
// End snippet
}
public void ListTimeSeries()
{
// Snippet: ListTimeSeries(string,string,TimeInterval,ListTimeSeriesRequest.Types.TimeSeriesView,string,int?,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
string formattedName = MetricServiceClient.FormatProjectName("[PROJECT]");
string filter = "";
TimeInterval interval = new TimeInterval();
ListTimeSeriesRequest.Types.TimeSeriesView view = ListTimeSeriesRequest.Types.TimeSeriesView.Full;
// Make the request
IPagedEnumerable<ListTimeSeriesResponse,TimeSeries> response =
metricServiceClient.ListTimeSeries(formattedName, filter, interval, view);
// Iterate over all response items, lazily performing RPCs as required
foreach (TimeSeries item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over fixed-sized pages, lazily performing RPCs as required
int pageSize = 10;
foreach (FixedSizePage<TimeSeries> page in response.AsPages().WithFixedSize(pageSize))
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TimeSeries item in page)
{
Console.WriteLine(item);
}
}
// End snippet
}
public async Task CreateTimeSeriesAsync()
{
// Snippet: CreateTimeSeriesAsync(string,IEnumerable<TimeSeries>,CallSettings)
// Additional: CreateTimeSeriesAsync(string,IEnumerable<TimeSeries>,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
string formattedName = MetricServiceClient.FormatProjectName("[PROJECT]");
IEnumerable<TimeSeries> timeSeries = new List<TimeSeries>();
// Make the request
await metricServiceClient.CreateTimeSeriesAsync(formattedName, timeSeries);
// End snippet
}
public void CreateTimeSeries()
{
// Snippet: CreateTimeSeries(string,IEnumerable<TimeSeries>,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
string formattedName = MetricServiceClient.FormatProjectName("[PROJECT]");
IEnumerable<TimeSeries> timeSeries = new List<TimeSeries>();
// Make the request
metricServiceClient.CreateTimeSeries(formattedName, timeSeries);
// End snippet
}
}
}
| |
/*
* Copyright (c) 2015, iLearnRW. Licensed under Modified BSD Licence. See licence.txt for details.
*/using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
public class WordDBCreator
{
static public string getLevel(string app){
Debug.LogError("Offline word creator");
switch(app){
case "DROP_CHOPS": return "M0-A2-S0-B10-W0-F0-T1";
case "SERENADE_HERO": return "M0-A3-S0-B10-W0-F3-T0";
case "MAIL_SORTER": return "M1-A2-S0-B5-W0-F3-T0";
case "MOVING_PATHWAYS": return "M1-A1-S0-B10-W0-F3-T0";
case "WHAK_A_MOLE": return "M3-A10-S0-B10-W0-F3-T0";
case "HARVEST": return "M0-A0-S0-B5-W1-F1-T0";
case "TRAIN_DISPATCHER": return "M0-A0-S0-B5-W1-F0-T0";
case "EYE_EXAM": return "M0-A3-S0-B10-W1-F0-T0";
case "ENDLESS_RUNNER": return "M0-A0-S2-B5-W1-F0-T0";
}
return "M0-A0-S2-B5-W1-F0-T0";
}
static public List<PackagedNextWord> createListPackagedNextWords(string app){
/*if(lan == LanguageCode.GR){
return WordDBCreatorGR.createListPackagedNextWords(app, 0,0,0,"",0,"")
}*/
string file = "Localisation_Files/EN/Offline_";
switch(app){
case "DROP_CHOPS": file+="SJ_EN";break;
case "SERENADE_HERO": file+="SH_EN";break;
case "MAIL_SORTER": file+="MS_EN";break;
case "MOVING_PATHWAYS": file+="MP_EN";break;
case "WHAK_A_MOLE": file+="WAM_EN";break;
case "HARVEST": file+="HARVEST_EN";break;
case "TRAIN_DISPATCHER": file+="TD_EN";break;
case "EYE_EXAM": file+="BB_EN";break;
case "ENDLESS_RUNNER": file+="PD_EN";break;
default: Debug.Log("Hard Coded for " +app+" not available");break;
}
TextAsset ta = (TextAsset) Resources.Load(file,typeof(TextAsset));
return JsonHelper.deserialiseObject<List<PackagedNextWord>>(ta.text);
}
static public List<PackagedNextWord> createListPackagedNextWords(string app, int number_words,int difficultyID,int languageArea,string userID,int evaluation_mode,string challenge)
{
return createListPackagedNextWords(app);
/*
switch(app){
case "DROP_CHOPS":
return SJwords();
case "SERENADE_HERO":
return SHsentences();
case "MAIL_SORTER":
return MSwords();
case "MOVING_PATHWAYS":
return MPwords();
case "WHAK_A_MOLE":
return WAMwords();
case "HARVEST":
return Harvestwords();
case "TRAIN_DISPATCHER":
return TDwords();
case "EYE_EXAM":
return BBwords();
case "ENDLESS_RUNNER":
return PDwords();
default:
Debug.Log("Hard Coded for " +app+" not available");
return new List<PackagedNextWord>();
}*/
}
static public List<PackagedNextWord> PDwords(){
return new List<PackagedNextWord>{
new PackagedNextWord( new AnnotatedWord("teacher",new List<int>{2} ),false),
new PackagedNextWord( new AnnotatedWord("item",new List<int>{0} ),false),
new PackagedNextWord( new AnnotatedWord("watermelon",new List<int>{1,4,6} ),false),
new PackagedNextWord( new AnnotatedWord("acorn",new List<int>{0} ),false),
new PackagedNextWord( new AnnotatedWord("computer",new List<int>{2,4} ),false),
new PackagedNextWord( new AnnotatedWord("table",new List<int>{1} ),false),
new PackagedNextWord( new AnnotatedWord("bicycle",new List<int>{1,3} ),false),
new PackagedNextWord( new AnnotatedWord("helicopter",new List<int>{1,3,6} ),false),
new PackagedNextWord( new AnnotatedWord("laptop",new List<int>{2} ),false)
};
}
static public List<PackagedNextWord> TDwords(){
return new List<PackagedNextWord>{
new PackagedNextWord( new AnnotatedWord("teacher",new List<int>{2} ),false),
new PackagedNextWord( new AnnotatedWord("helicopter",new List<int>{1,3,6} ),false),
new PackagedNextWord( new AnnotatedWord("small",new List<int>{} ),false),
new PackagedNextWord( new AnnotatedWord("item",new List<int>{0} ),false),
new PackagedNextWord( new AnnotatedWord("meant",new List<int>{} ),false),
new PackagedNextWord( new AnnotatedWord("watermelon",new List<int>{1,4,6} ),false),
new PackagedNextWord( new AnnotatedWord("acorn",new List<int>{0} ),false),
new PackagedNextWord( new AnnotatedWord("computer",new List<int>{2,4} ),false),
new PackagedNextWord( new AnnotatedWord("table",new List<int>{1} ),false),
new PackagedNextWord( new AnnotatedWord("bicycle",new List<int>{1,3} ),false),
new PackagedNextWord( new AnnotatedWord("laptop",new List<int>{2} ),false)
};
}
static public List<PackagedNextWord> BBwords(){
return new List<PackagedNextWord>{
new PackagedNextWord( new AnnotatedWord("decoder",new List<int>{1,4} ),false),
new PackagedNextWord( new AnnotatedWord("preordered",new List<int>{2,4,7} ),false),
new PackagedNextWord( new AnnotatedWord("incoming",new List<int>{1,4} ),false),
new PackagedNextWord( new AnnotatedWord("misunderstanding",new List<int>{2,4,7,12} ),false)
};
}
static public List<PackagedNextWord> MPwords(){
return new List<PackagedNextWord>{
new PackagedNextWord( new AnnotatedWord("b","single letter") , false ),
new PackagedNextWord( new AnnotatedWord("d","single letter") , false ),
new PackagedNextWord( new AnnotatedWord("q","single letter") , false ),
new PackagedNextWord( new AnnotatedWord("p","single letter") , false )
};
}
static public List<PackagedNextWord> Harvestwords(){
return new List<PackagedNextWord>{
new PackagedNextWord( new AnnotatedWord("calling","-ing",new string[]{"call","ing"}) , false ),
new PackagedNextWord( new AnnotatedWord("caring","-ing",new string[]{"caring"}) , false ),
new PackagedNextWord( new AnnotatedWord("beginner","-er",new string[]{"be","gin","ner"}) , false ),
new PackagedNextWord( new AnnotatedWord("taking","-ing",new string[]{"tak","ing"}) , false ),
new PackagedNextWord( new AnnotatedWord("caller","-er",new string[]{"call","er"}) , false )
};
}
static public List<PackagedNextWord> WAMwords(){
return new List<PackagedNextWord>{
new PackagedNextWord( new AnnotatedWord("jumped","Suffix 'ed'") , false ),
new PackagedNextWord( new AnnotatedWord("chased","Suffix 'ed'") , false ),
new PackagedNextWord( new AnnotatedWord("pushed","Suffix 'ed'") , false ),
new PackagedNextWord( new AnnotatedWord("climbed","Suffix 'ed'") , false ),
new PackagedNextWord( new AnnotatedWord("called","Suffix 'ed'") , false ),
new PackagedNextWord( new AnnotatedWord("danced","Suffix 'ed'") , false ),
new PackagedNextWord( new AnnotatedWord("jumper","Suffix 'ed'") , true ),
new PackagedNextWord( new AnnotatedWord("chaser","Suffix 'ed'") , true ),
new PackagedNextWord( new AnnotatedWord("pusher","Suffix 'ed'") , true ),
new PackagedNextWord( new AnnotatedWord("climber","Suffix 'ed'") , true ),
new PackagedNextWord( new AnnotatedWord("caller","Suffix 'ed'") , true ),
new PackagedNextWord( new AnnotatedWord("dancer","Suffix 'ed'") , true ),
new PackagedNextWord( new AnnotatedWord("redo","Prefix 're'") , false ),
new PackagedNextWord( new AnnotatedWord("rerun","Prefix 're'") , false ),
new PackagedNextWord( new AnnotatedWord("remake","Prefix 're'") , false ),
new PackagedNextWord( new AnnotatedWord("reorganise","Prefix 're'") , false ),
new PackagedNextWord( new AnnotatedWord("resell","Prefix 're'") , false ),
new PackagedNextWord( new AnnotatedWord("reopen","Prefix 're'") , false ),
new PackagedNextWord( new AnnotatedWord("doer","Prefix 're'") , true ),
new PackagedNextWord( new AnnotatedWord("runner","Prefix 're'") , true ),
new PackagedNextWord( new AnnotatedWord("maker","Prefix 're'") , true ),
new PackagedNextWord( new AnnotatedWord("organiser","Prefix 're'") , true ),
new PackagedNextWord( new AnnotatedWord("seller","Prefix 're'") , true ),
new PackagedNextWord( new AnnotatedWord("opener","Prefix 're'") , true )
};
}
static public List<PackagedNextWord> MSwords(){
return new List<PackagedNextWord>{
new PackagedNextWord( new AnnotatedWord("calling","-ing",new string[]{"call","ing"}) , false ),
new PackagedNextWord( new AnnotatedWord("caller","-er",new string[]{"call","er"}) , false ),
new PackagedNextWord( new AnnotatedWord("called","-ed",new string[]{"called"}) , false ),
new PackagedNextWord( new AnnotatedWord("caring","-ing",new string[]{"caring"}) , false ),
new PackagedNextWord( new AnnotatedWord("careless","-less",new string[]{"care","less"}) , false ),
new PackagedNextWord( new AnnotatedWord("carefull","-full",new string[]{"care","full"}) , false ),
new PackagedNextWord( new AnnotatedWord("taken","-en",new string[]{"tak","en"}) , false ),
new PackagedNextWord( new AnnotatedWord("taking","-ing",new string[]{"tak","ing"}) , false ),
new PackagedNextWord( new AnnotatedWord("takes"," -s ",new string[]{"takes"}) , false ),
};
}
static public List<PackagedNextWord> SHsentences(){
return new List<PackagedNextWord>{
new PackagedNextWord( new AnnotatedSentence("You have to complete this {sentence}",new List<string>{"write","read"} ) , false ),
new PackagedNextWord( new AnnotatedSentence("I don't think {you're} right",new List<string>{"your","you"} ) , false ),
new PackagedNextWord( new AnnotatedSentence("It was {their} idea",new List<string>{ "they're","they" }) , false ),
new PackagedNextWord( new AnnotatedSentence("The dog {ran} after the cat",new List<string>{ "run","ruin" }) , false ),
new PackagedNextWord( new AnnotatedSentence("Superman does {good} , you are doing {well}",new List<string>{"goodness"}) , false ),
new PackagedNextWord( new AnnotatedSentence("We all {thought} the same thing",new List<string>{ "though","through" }) , false ),
new PackagedNextWord( new AnnotatedSentence("Leave the book {on} the table",new List<string>{ "in","onto" }) , false ),
new PackagedNextWord( new AnnotatedSentence("Last month we {read} two books",new List<string>{ "red","bread" }) , false )
};
}
//static public List<PackagedNextWord> createListPackagedNextWords()
static public List<PackagedNextWord> SJwords()
{
return new List<PackagedNextWord>{
new PackagedNextWord( new AnnotatedWord("helicopter",new List<int>{1,3,6} ),false),
new PackagedNextWord( new AnnotatedWord("misunderstanding",new List<int>{2,4,7,12} ),false),
new PackagedNextWord( new AnnotatedWord("theory",new List<int>{2,3} ),false),
new PackagedNextWord( new AnnotatedWord("thermometer",new List<int>{3,5,7} ),false),
new PackagedNextWord( new AnnotatedWord("computer",new List<int>{2,4} ),false),
new PackagedNextWord( new AnnotatedWord("table",new List<int>{1} ),false),
new PackagedNextWord( new AnnotatedWord("watermelon",new List<int>{1,4,6} ),false),
new PackagedNextWord( new AnnotatedWord("laptop",new List<int>{2} ),false)
};
/*TextAsset ta = (TextAsset) Resources.Load("SegmentationWords",typeof(TextAsset));
string[] lines = ta.text.Split(new string[] { "\r\n" },System.StringSplitOptions.None);
int currDiffIndicator = 1;
List<PackagedNextWord> list = new List<PackagedNextWord>();
bool nwSetComplete = false;
for(int k=0; k<lines.Length; k++)
{
string readData = lines[k];
int tmpInt = 0;
if(int.TryParse(readData,out tmpInt))
{
if(nwSetComplete)
{
// We have a complete word set.
return list;//single difficulty
}
currDiffIndicator = tmpInt;
nwSetComplete = true;
}
else
{
// Parse and add a new word to the current word set.
string[] splitStrs = readData.Split(':');
string nwWordTextRep = splitStrs[0];
string[] syllableSplitPos = splitStrs[1].Split(',');
List<int> ssPosIntList = new List<int>();
for(int i=0; i<syllableSplitPos.Length; i++)
{
ssPosIntList.Add(int.Parse(syllableSplitPos[i]));
}
AnnotatedWord reqW = new AnnotatedWord(nwWordTextRep,ssPosIntList);
list.Add ( new PackagedNextWord( reqW , false) );
}
}
return list;//single difficulty
*/
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using Hydra.Framework;
using Hydra.Framework.Helpers;
using Hydra.Framework.Java;
using Hydra.Framework.Mapping.CoordinateSystems;
using Hydra.Framework.Conversions;
namespace Hydra.DomainModel
{
//
//**********************************************************************
/// <summary>
/// Network Design (Interface) Information Details
/// </summary>
//**********************************************************************
//
[Serializable]
[DataContract(Namespace = CommonConstants.DATA_NAMESPACE)]
[KnownType(typeof(InternalAntenna))]
public class InternalAPInterface
: AbstractInternalData
{
#region Member Variables
//
//**********************************************************************
/// <summary>
/// Antenna Diveristy
/// </summary>
//**********************************************************************
//
[DataMember(Name = "AntennaDiversity")]
public int AntennaDiversity
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// Antenna Mode
/// </summary>
//**********************************************************************
//
[DataMember(Name = "AntennaMode")]
public int AntennaMode
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// Antenna Type
/// </summary>
//**********************************************************************
//
[DataMember(Name = "AntennaType")]
public int AntennaType
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// Channel Assignment
/// </summary>
//**********************************************************************
//
[DataMember(Name = "ChannelAssignment")]
public int ChannelAssignment
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// Channel Number
/// </summary>
//**********************************************************************
//
[DataMember(Name = "ChannelNumber")]
public int ChannelNumber
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// Interface Slot Identifier
/// </summary>
//**********************************************************************
//
[DataMember(Name = "IfSlotId")]
public int IfSlotId
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// Interface Slot Type
/// </summary>
//**********************************************************************
//
[DataMember(Name = "IfSlotType")]
public int IfSlotType
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// Transmission Power Control
/// </summary>
//**********************************************************************
//
[DataMember(Name = "TxPowerControl")]
public int TxPowerControl
{
get;
set;
}
//
//**********************************************************************
/// <summary>
/// Transmission Power Level
/// </summary>
//**********************************************************************
//
[DataMember(Name = "TxPowerLevel")]
public int TxPowerLevel
{
get;
set;
}
//
// **********************************************************************
/// <summary>
/// Antenna Gain
/// </summary>
// **********************************************************************
//
[DataMember(Name = "Gain")]
public int Gain
{
get;
set;
}
//
// **********************************************************************
/// <summary>
/// Antenna Angle
/// </summary>
// **********************************************************************
//
[DataMember(Name = "Angle")]
public float Angle
{
get;
set;
}
//
// **********************************************************************
/// <summary>
/// List of Antennas Linked to this interface
/// </summary>
// **********************************************************************
//
[DataMember(Name = "AntennaList")]
public List<InternalAntenna> AntennaList
{
get;
set;
}
//
// **********************************************************************
/// <summary>
/// Access Point Identifier
/// </summary>
// **********************************************************************
//
[DataMember(Name = "AccessPointId")]
public int AccessPointId
{
get;
set;
}
#endregion
#region Constructors
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="InternalAPInterface"/> class.
/// </summary>
// **********************************************************************
//
public InternalAPInterface()
: base(InternalLocationServiceType.Internal)
{
Log.Entry();
Log.Exit();
}
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="InternalAPInterface"/> class.
/// </summary>
/// <param name="accessPointId">The access point id.</param>
/// <param name="name">The name.</param>
/// <param name="description">The description.</param>
/// <param name="antennaDiversity">The antenna diversity.</param>
/// <param name="antennaMode">The antenna mode.</param>
/// <param name="antennaType">Type of the antenna.</param>
/// <param name="changedOn">The changed on.</param>
/// <param name="channelAssignment">The channel assignment.</param>
/// <param name="channelNumber">The channel number.</param>
/// <param name="ifSlotId">If slot id.</param>
/// <param name="ifSlotType">Type of if slot.</param>
/// <param name="objectId">The object id.</param>
/// <param name="parentId">The parent id.</param>
/// <param name="txPowerControl">The tx power control.</param>
/// <param name="txPowerLevel">The tx power level.</param>
/// <param name="angle">The angle.</param>
/// <param name="gain">The gain.</param>
// **********************************************************************
//
public InternalAPInterface(int accessPointId, string name, string description, int antennaDiversity, int antennaMode, int antennaType,
DateTime changedOn, int channelAssignment, int channelNumber, int ifSlotId, int ifSlotType, int objectId, int parentId,
int txPowerControl, int txPowerLevel, float angle, int gain)
: base(InternalLocationServiceType.Internal, objectId, parentId, changedOn)
{
Log.Entry(antennaDiversity, antennaMode, antennaType, changedOn, channelAssignment);
Name = name;
Description = description;
AntennaDiversity = antennaDiversity;
AntennaMode = antennaMode;
AntennaType = antennaType;
ChannelAssignment = channelAssignment;
ChannelNumber = channelNumber;
IfSlotId = ifSlotId;
IfSlotType = ifSlotType;
TxPowerControl = txPowerControl;
TxPowerLevel = txPowerLevel;
Angle = angle;
Gain = gain;
AccessPointId = accessPointId;
AntennaList = new List<InternalAntenna>();
Log.Exit();
}
//
//**********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="T:InternalAPInterface"/> class.
/// </summary>
/// <param name="accessPointId">The access point id.</param>
/// <param name="name">The name.</param>
/// <param name="description">The description.</param>
/// <param name="antennaDiversity">The antenna diversity.</param>
/// <param name="antennaMode">The antenna mode.</param>
/// <param name="antennaType">Type of the antenna.</param>
/// <param name="changedOn">The changed on.</param>
/// <param name="channelAssignment">The channel assignment.</param>
/// <param name="channelNumber">The channel number.</param>
/// <param name="ifSlotId">If slot id.</param>
/// <param name="ifSlotType">Type of if slot.</param>
/// <param name="objectId">The object id.</param>
/// <param name="parentId">The parent id.</param>
/// <param name="txPowerControl">The tx power control.</param>
/// <param name="txPowerLevel">The tx power level.</param>
/// <param name="angle">The angle.</param>
/// <param name="gain">The gain.</param>
/// <param name="antennaList">The antenna list.</param>
//**********************************************************************
//
public InternalAPInterface(int accessPointId, string name, string description, int antennaDiversity, int antennaMode, int antennaType,
DateTime changedOn, int channelAssignment, int channelNumber, int ifSlotId, int ifSlotType, int objectId, int parentId,
int txPowerControl, int txPowerLevel, float angle, int gain, List<InternalAntenna> antennaList)
: base(InternalLocationServiceType.Internal, objectId, parentId, changedOn)
{
Log.Entry(antennaDiversity, antennaMode, antennaType, changedOn, channelAssignment);
name = name;
Description = description;
AntennaDiversity = antennaDiversity;
AntennaMode = antennaMode;
AntennaType = antennaType;
ChannelAssignment = channelAssignment;
ChannelNumber = channelNumber;
IfSlotId = ifSlotId;
IfSlotType = ifSlotType;
TxPowerControl = txPowerControl;
TxPowerLevel = txPowerLevel;
Angle = angle;
Gain = gain;
AccessPointId = accessPointId;
AntennaList = antennaList;
Log.Exit();
}
#endregion
#region Properties
#endregion
#region Static Methods
#endregion
}
}
| |
/*
* 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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenSim.Framework;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework.Monitoring
{
/// <summary>
/// Static class used to register/deregister/fetch statistics
/// </summary>
public static class StatsManager
{
// Subcommand used to list other stats.
public const string AllSubCommand = "all";
// Subcommand used to list other stats.
public const string ListSubCommand = "list";
// All subcommands
public static HashSet<string> SubCommands = new HashSet<string> { AllSubCommand, ListSubCommand };
/// <summary>
/// Registered stats categorized by category/container/shortname
/// </summary>
/// <remarks>
/// Do not add or remove directly from this dictionary.
/// </remarks>
public static SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Stat>>> RegisteredStats
= new SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Stat>>>();
// private static AssetStatsCollector assetStats;
// private static UserStatsCollector userStats;
// private static SimExtraStatsCollector simExtraStats = new SimExtraStatsCollector();
// public static AssetStatsCollector AssetStats { get { return assetStats; } }
// public static UserStatsCollector UserStats { get { return userStats; } }
public static SimExtraStatsCollector SimExtraStats { get; set; }
public static void RegisterConsoleCommands(ICommandConsole console)
{
console.Commands.AddCommand(
"General",
false,
"stats show",
"stats show [list|all|(<category>[.<container>])+",
"Show statistical information for this server",
"If no final argument is specified then legacy statistics information is currently shown.\n"
+ "'list' argument will show statistic categories.\n"
+ "'all' will show all statistics.\n"
+ "A <category> name will show statistics from that category.\n"
+ "A <category>.<container> name will show statistics from that category in that container.\n"
+ "More than one name can be given separated by spaces.\n"
+ "THIS STATS FACILITY IS EXPERIMENTAL AND DOES NOT YET CONTAIN ALL STATS",
HandleShowStatsCommand);
console.Commands.AddCommand(
"General",
false,
"show stats",
"show stats [list|all|(<category>[.<container>])+",
"Alias for 'stats show' command",
HandleShowStatsCommand);
StatsLogger.RegisterConsoleCommands(console);
}
public static void HandleShowStatsCommand(string module, string[] cmd)
{
ICommandConsole con = MainConsole.Instance;
if (cmd.Length > 2)
{
foreach (string name in cmd.Skip(2))
{
string[] components = name.Split('.');
string categoryName = components[0];
string containerName = components.Length > 1 ? components[1] : null;
string statName = components.Length > 2 ? components[2] : null;
if (categoryName == AllSubCommand)
{
OutputAllStatsToConsole(con);
}
else if (categoryName == ListSubCommand)
{
con.Output("Statistic categories available are:");
foreach (string category in RegisteredStats.Keys)
con.OutputFormat(" {0}", category);
}
else
{
SortedDictionary<string, SortedDictionary<string, Stat>> category;
if (!RegisteredStats.TryGetValue(categoryName, out category))
{
con.OutputFormat("No such category as {0}", categoryName);
}
else
{
if (String.IsNullOrEmpty(containerName))
{
OutputCategoryStatsToConsole(con, category);
}
else
{
SortedDictionary<string, Stat> container;
if (category.TryGetValue(containerName, out container))
{
if (String.IsNullOrEmpty(statName))
{
OutputContainerStatsToConsole(con, container);
}
else
{
Stat stat;
if (container.TryGetValue(statName, out stat))
{
OutputStatToConsole(con, stat);
}
else
{
con.OutputFormat(
"No such stat {0} in {1}.{2}", statName, categoryName, containerName);
}
}
}
else
{
con.OutputFormat("No such container {0} in category {1}", containerName, categoryName);
}
}
}
}
}
}
else
{
// Legacy
if (SimExtraStats != null)
con.Output(SimExtraStats.Report());
else
OutputAllStatsToConsole(con);
}
}
public static List<string> GetAllStatsReports()
{
List<string> reports = new List<string>();
foreach (var category in RegisteredStats.Values)
reports.AddRange(GetCategoryStatsReports(category));
return reports;
}
private static void OutputAllStatsToConsole(ICommandConsole con)
{
foreach (string report in GetAllStatsReports())
con.Output(report);
}
private static List<string> GetCategoryStatsReports(
SortedDictionary<string, SortedDictionary<string, Stat>> category)
{
List<string> reports = new List<string>();
foreach (var container in category.Values)
reports.AddRange(GetContainerStatsReports(container));
return reports;
}
private static void OutputCategoryStatsToConsole(
ICommandConsole con, SortedDictionary<string, SortedDictionary<string, Stat>> category)
{
foreach (string report in GetCategoryStatsReports(category))
con.Output(report);
}
private static List<string> GetContainerStatsReports(SortedDictionary<string, Stat> container)
{
List<string> reports = new List<string>();
foreach (Stat stat in container.Values)
reports.Add(stat.ToConsoleString());
return reports;
}
private static void OutputContainerStatsToConsole(
ICommandConsole con, SortedDictionary<string, Stat> container)
{
foreach (string report in GetContainerStatsReports(container))
con.Output(report);
}
private static void OutputStatToConsole(ICommandConsole con, Stat stat)
{
con.Output(stat.ToConsoleString());
}
// Creates an OSDMap of the format:
// { categoryName: {
// containerName: {
// statName: {
// "Name": name,
// "ShortName": shortName,
// ...
// },
// statName: {
// "Name": name,
// "ShortName": shortName,
// ...
// },
// ...
// },
// containerName: {
// ...
// },
// ...
// },
// categoryName: {
// ...
// },
// ...
// }
// The passed in parameters will filter the categories, containers and stats returned. If any of the
// parameters are either EmptyOrNull or the AllSubCommand value, all of that type will be returned.
// Case matters.
public static OSDMap GetStatsAsOSDMap(string pCategoryName, string pContainerName, string pStatName)
{
OSDMap map = new OSDMap();
foreach (string catName in RegisteredStats.Keys)
{
// Do this category if null spec, "all" subcommand or category name matches passed parameter.
// Skip category if none of the above.
if (!(String.IsNullOrEmpty(pCategoryName) || pCategoryName == AllSubCommand || pCategoryName == catName))
continue;
OSDMap contMap = new OSDMap();
foreach (string contName in RegisteredStats[catName].Keys)
{
if (!(string.IsNullOrEmpty(pContainerName) || pContainerName == AllSubCommand || pContainerName == contName))
continue;
OSDMap statMap = new OSDMap();
SortedDictionary<string, Stat> theStats = RegisteredStats[catName][contName];
foreach (string statName in theStats.Keys)
{
if (!(String.IsNullOrEmpty(pStatName) || pStatName == AllSubCommand || pStatName == statName))
continue;
statMap.Add(statName, theStats[statName].ToOSDMap());
}
contMap.Add(contName, statMap);
}
map.Add(catName, contMap);
}
return map;
}
public static Hashtable HandleStatsRequest(Hashtable request)
{
Hashtable responsedata = new Hashtable();
// string regpath = request["uri"].ToString();
int response_code = 200;
string contenttype = "text/json";
string pCategoryName = StatsManager.AllSubCommand;
string pContainerName = StatsManager.AllSubCommand;
string pStatName = StatsManager.AllSubCommand;
if (request.ContainsKey("cat")) pCategoryName = request["cat"].ToString();
if (request.ContainsKey("cont")) pContainerName = request["cat"].ToString();
if (request.ContainsKey("stat")) pStatName = request["stat"].ToString();
string strOut = StatsManager.GetStatsAsOSDMap(pCategoryName, pContainerName, pStatName).ToString();
// If requestor wants it as a callback function, build response as a function rather than just the JSON string.
if (request.ContainsKey("callback"))
{
strOut = request["callback"].ToString() + "(" + strOut + ");";
}
// m_log.DebugFormat("{0} StatFetch: uri={1}, cat={2}, cont={3}, stat={4}, resp={5}",
// LogHeader, regpath, pCategoryName, pContainerName, pStatName, strOut);
responsedata["int_response_code"] = response_code;
responsedata["content_type"] = contenttype;
responsedata["keepalive"] = false;
responsedata["str_response_string"] = strOut;
responsedata["access_control_allow_origin"] = "*";
return responsedata;
}
// /// <summary>
// /// Start collecting statistics related to assets.
// /// Should only be called once.
// /// </summary>
// public static AssetStatsCollector StartCollectingAssetStats()
// {
// assetStats = new AssetStatsCollector();
//
// return assetStats;
// }
//
// /// <summary>
// /// Start collecting statistics related to users.
// /// Should only be called once.
// /// </summary>
// public static UserStatsCollector StartCollectingUserStats()
// {
// userStats = new UserStatsCollector();
//
// return userStats;
// }
/// <summary>
/// Register a statistic.
/// </summary>
/// <param name='stat'></param>
/// <returns></returns>
public static bool RegisterStat(Stat stat)
{
SortedDictionary<string, SortedDictionary<string, Stat>> category = null, newCategory;
SortedDictionary<string, Stat> container = null, newContainer;
lock (RegisteredStats)
{
// Stat name is not unique across category/container/shortname key.
// XXX: For now just return false. This is to avoid problems in regression tests where all tests
// in a class are run in the same instance of the VM.
if (TryGetStatParents(stat, out category, out container))
return false;
// We take a copy-on-write approach here of replacing dictionaries when keys are added or removed.
// This means that we don't need to lock or copy them on iteration, which will be a much more
// common operation after startup.
if (container != null)
newContainer = new SortedDictionary<string, Stat>(container);
else
newContainer = new SortedDictionary<string, Stat>();
if (category != null)
newCategory = new SortedDictionary<string, SortedDictionary<string, Stat>>(category);
else
newCategory = new SortedDictionary<string, SortedDictionary<string, Stat>>();
newContainer[stat.ShortName] = stat;
newCategory[stat.Container] = newContainer;
RegisteredStats[stat.Category] = newCategory;
}
return true;
}
/// <summary>
/// Deregister a statistic
/// </summary>>
/// <param name='stat'></param>
/// <returns></returns>
public static bool DeregisterStat(Stat stat)
{
SortedDictionary<string, SortedDictionary<string, Stat>> category = null, newCategory;
SortedDictionary<string, Stat> container = null, newContainer;
lock (RegisteredStats)
{
if (!TryGetStatParents(stat, out category, out container))
return false;
newContainer = new SortedDictionary<string, Stat>(container);
newContainer.Remove(stat.ShortName);
newCategory = new SortedDictionary<string, SortedDictionary<string, Stat>>(category);
newCategory.Remove(stat.Container);
newCategory[stat.Container] = newContainer;
RegisteredStats[stat.Category] = newCategory;
return true;
}
}
public static bool TryGetStat(string category, string container, string statShortName, out Stat stat)
{
stat = null;
SortedDictionary<string, SortedDictionary<string, Stat>> categoryStats;
lock (RegisteredStats)
{
if (!TryGetStatsForCategory(category, out categoryStats))
return false;
SortedDictionary<string, Stat> containerStats;
if (!categoryStats.TryGetValue(container, out containerStats))
return false;
return containerStats.TryGetValue(statShortName, out stat);
}
}
public static bool TryGetStatsForCategory(
string category, out SortedDictionary<string, SortedDictionary<string, Stat>> stats)
{
lock (RegisteredStats)
return RegisteredStats.TryGetValue(category, out stats);
}
/// <summary>
/// Get the same stat for each container in a given category.
/// </summary>
/// <returns>
/// The stats if there were any to fetch. Otherwise null.
/// </returns>
/// <param name='category'></param>
/// <param name='statShortName'></param>
public static List<Stat> GetStatsFromEachContainer(string category, string statShortName)
{
SortedDictionary<string, SortedDictionary<string, Stat>> categoryStats;
lock (RegisteredStats)
{
if (!RegisteredStats.TryGetValue(category, out categoryStats))
return null;
List<Stat> stats = null;
foreach (SortedDictionary<string, Stat> containerStats in categoryStats.Values)
{
if (containerStats.ContainsKey(statShortName))
{
if (stats == null)
stats = new List<Stat>();
stats.Add(containerStats[statShortName]);
}
}
return stats;
}
}
public static bool TryGetStatParents(
Stat stat,
out SortedDictionary<string, SortedDictionary<string, Stat>> category,
out SortedDictionary<string, Stat> container)
{
category = null;
container = null;
lock (RegisteredStats)
{
if (RegisteredStats.TryGetValue(stat.Category, out category))
{
if (category.TryGetValue(stat.Container, out container))
{
if (container.ContainsKey(stat.ShortName))
return true;
}
}
}
return false;
}
public static void RecordStats()
{
lock (RegisteredStats)
{
foreach (SortedDictionary<string, SortedDictionary<string, Stat>> category in RegisteredStats.Values)
{
foreach (SortedDictionary<string, Stat> container in category.Values)
{
foreach (Stat stat in container.Values)
{
if (stat.MeasuresOfInterest != MeasuresOfInterest.None)
stat.RecordValue();
}
}
}
}
}
}
/// <summary>
/// Stat type.
/// </summary>
/// <remarks>
/// A push stat is one which is continually updated and so it's value can simply by read.
/// A pull stat is one where reading the value triggers a collection method - the stat is not continually updated.
/// </remarks>
public enum StatType
{
Push,
Pull
}
/// <summary>
/// Measures of interest for this stat.
/// </summary>
[Flags]
public enum MeasuresOfInterest
{
None,
AverageChangeOverTime
}
/// <summary>
/// Verbosity of stat.
/// </summary>
/// <remarks>
/// Info will always be displayed.
/// </remarks>
public enum StatVerbosity
{
Debug,
Info
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.Linq;
using bv.common;
using bv.common.Core;
using EIDSS.RAM.Presenters.Base;
using EIDSS.RAM_DB.Common.CommandProcessing.Commands;
using EIDSS.RAM_DB.Common.CommandProcessing.Commands.Layout;
using EIDSS.RAM_DB.Common.EventHandlers;
using EIDSS.RAM_DB.Components;
using EIDSS.RAM_DB.DBService;
using EIDSS.RAM_DB.DBService.DataSource;
using EIDSS.RAM_DB.DBService.Models;
using EIDSS.RAM_DB.Views;
using bv.common.db;
namespace EIDSS.RAM.Presenters
{
public class LayoutDetailPresenter : RelatedObjectPresenter
{
private readonly ILayoutDetailView m_LayoutDetailView;
private bool m_NewClicked;
private readonly Layout_DB m_LayoutDbService;
private readonly LayoutMediator m_LayoutMediator;
public LayoutDetailPresenter(SharedPresenter sharedPresenter, ILayoutDetailView view)
: base(sharedPresenter, view)
{
m_LayoutDbService = new Layout_DB(m_SharedPresenter.SharedModel);
m_LayoutDetailView = view;
m_LayoutDetailView.DBService = m_LayoutDbService;
m_LayoutMediator = new LayoutMediator(this);
m_LayoutDetailView.CopyLayoutCreating += m_LayoutDetailView_CopyLayoutCreating;
m_SharedPresenter.SharedModel.PropertyChanged += SharedModel_PropertyChanged;
}
public bool StandardReports
{
get { return m_SharedPresenter.SharedModel.StandardReports; }
}
public Layout_DB LayoutDbService
{
get { return m_LayoutDbService; }
}
public bool LayoutAccessible
{
get { return m_NewClicked || !IsNewObject; }
}
public bool NewClicked
{
get { return m_NewClicked; }
set { m_NewClicked = value; }
}
public void SetPivotAccessible(bool value)
{
m_SharedPresenter.SharedModel.PivotAccessible = value;
}
private void m_LayoutDetailView_CopyLayoutCreating(object sender, CopyLayoutEventArgs e)
{
Dictionary<long, long> changedIds = LayoutDbService.CreateCopyLayout(m_LayoutMediator.LayoutDataSet);
//Rename DataSource tables layout according to new idfLayoutSearchField
if (e.PivotGrid.DataSource != null)
{
DataTable dataSource = e.PivotGrid.DataSource.Copy();
foreach (DataColumn column in dataSource.Columns)
{
long oldId = RamPivotGridHelper.GetIdFromFieldName(column.ColumnName);
if (!changedIds.ContainsKey(oldId))
throw new RamException(string.Format("Pivot DataSource column with Id {0} not found", oldId));
long newId = changedIds[oldId];
column.ColumnName = ReplaceIdInString(column.ColumnName, oldId, newId);
}
e.PivotGrid.DataSource = dataSource;
}
//Rename fields in layout according to new idfLayoutSearchField
foreach (WinPivotGridField field in e.PivotGrid.BaseFields)
{
long oldId = field.Id;
if (!changedIds.ContainsKey(oldId))
throw new RamException(string.Format("Field with Id {0} not found", oldId));
long newId = changedIds[oldId];
field.Name = ReplaceIdInString(field.Name, oldId, newId);
field.FieldName = ReplaceIdInString(field.FieldName, oldId, newId);
}
//chage filters of layout according to new idfLayoutSearchField
string criteriaString = e.PivotGrid.CriteriaString;
if (!string.IsNullOrEmpty(criteriaString))
{
foreach (KeyValuePair<long, long> pair in changedIds)
{
criteriaString = ReplaceIdInString(criteriaString, pair.Key, pair.Value);
e.DisabledCriteria = ReplaceIdInString(criteriaString, pair.Key, pair.Value);
}
e.PivotGrid.CriteriaString = criteriaString;
}
if (!string.IsNullOrEmpty(e.DisabledCriteria))
{
foreach (KeyValuePair<long, long> pair in changedIds)
{
e.DisabledCriteria = ReplaceIdInString(e.DisabledCriteria, pair.Key, pair.Value);
}
}
}
private static string ReplaceIdInString(string oldString, long oldId, long newId)
{
Utils.CheckNotNullOrEmpty(oldString, "oldString");
return oldString.Replace(oldId.ToString(CultureInfo.InvariantCulture), newId.ToString(CultureInfo.InvariantCulture));
}
public override void Process(Command cmd)
{
if ((cmd is LayoutCommand))
{
var layoutCommand = (cmd as LayoutCommand);
m_LayoutDetailView.ProcessLayoutCommand(layoutCommand);
}
if (cmd is ReportViewCommand)
{
var viewCommand = (cmd as ReportViewCommand);
m_LayoutDetailView.ProcessReportViewCommand(viewCommand);
}
if ((cmd is PrintCommand))
{
var printCommand = (cmd as PrintCommand);
m_LayoutDetailView.ProcessPrintCommand(printCommand);
}
if ((cmd is RefreshCommand))
{
var refreshCommand = (cmd as RefreshCommand);
m_LayoutDetailView.ProcessRefreshCommand(refreshCommand);
}
}
private void SharedModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
var property = (SharedProperty) (Enum.Parse(typeof (SharedProperty), e.PropertyName));
switch (property)
{
case SharedProperty.SelectedQueryId:
long queryId = m_SharedPresenter.SharedModel.SelectedQueryId;
m_LayoutDbService.QueryID = queryId;
break;
case SharedProperty.SelectedLayoutId:
long layoutId = (m_SharedPresenter.SharedModel.SelectedLayoutId !=
m_SharedPresenter.SharedModel.SelectedFolderId)
? m_SharedPresenter.SharedModel.SelectedLayoutId
: -1L;
m_LayoutDetailView.OnLayoutSelected(new LayoutEventArgs(layoutId));
break;
case SharedProperty.ChartDataVertical:
bool vertical = m_SharedPresenter.SharedModel.ChartDataVertical;
m_LayoutDetailView.OnChangeOrientation(new ChartChangeOrientationEventArgs(vertical));
break;
}
}
public bool ParentHasChanges()
{
return m_SharedPresenter.SharedModel.ParentForm.HasChanges();
}
public bool Post(PostType postType)
{
try
{
return m_SharedPresenter.SharedModel.ParentForm.Post(postType);
}
catch (Exception ex)
{
Trace.WriteLine(ex);
return false;
}
}
internal void PrepareAggregateList(IList<WinPivotGridField> fields)
{
LayoutDetailDataSet.AggregateDataTable aggregateTable = m_LayoutMediator.LayoutDataSet.Aggregate;
var rowsToRemove = new List<LayoutDetailDataSet.AggregateRow>();
List<string> originalFieldnames = fields.Select(field => field.OriginalName).ToList();
foreach (LayoutDetailDataSet.AggregateRow row in aggregateTable.Rows)
{
LayoutDetailDataSet.AggregateRow localRow = row;
if (!originalFieldnames.Contains(localRow.SearchFieldAlias))
rowsToRemove.Add(localRow);
}
foreach (LayoutDetailDataSet.AggregateRow row in rowsToRemove)
{
aggregateTable.RemoveAggregateRow(row);
}
int length = 0;
foreach (WinPivotGridField field in fields)
{
string filter = string.Format("{0}='{1}'", aggregateTable.SearchFieldAliasColumn.ColumnName, field.OriginalName);
if (aggregateTable.Select(filter).Length == 0)
{
length++;
}
}
var ids = BaseDbService.NewListIntID(length);
int count = 0;
foreach (WinPivotGridField field in fields)
{
string filter = string.Format("{0}='{1}'", aggregateTable.SearchFieldAliasColumn.ColumnName,field.OriginalName);
if (aggregateTable.Select(filter).Length == 0)
{
AddNewAggregateRow(aggregateTable, m_LayoutMediator.LayoutRow.idflQuery, m_LayoutMediator.LayoutRow.idflLayout,
field.OriginalName, (long)field.GetSummaryType, ids[count]);
count++;
}
}
}
}
}
| |
using System;
using System.IO;
using System.Runtime.InteropServices;
using SQLite.Net.Interop;
using System.Reflection;
namespace SQLite.Net.Platform.Win32
{
internal static class SQLiteApiWin32Internal
{
static SQLiteApiWin32Internal()
{
int ptrSize = IntPtr.Size;
var architectureDirectory = (ptrSize == 8 ? "x64" : "x86");
var interopFilename = "SQLite.Interop.dll";
string interopPath = null;
if (!string.IsNullOrWhiteSpace(SQLiteApiWin32InternalConfiguration.NativeInteropSearchPath))
{
// a NativeInteropSearchPath is given, so we try to find the file name there
var fileInSearchPath = Path.Combine(SQLiteApiWin32InternalConfiguration.NativeInteropSearchPath, interopFilename);
if (File.Exists(fileInSearchPath))
{
interopPath = fileInSearchPath;
}
else
{
var fileInSearchPathWithArchitecture = Path.Combine(SQLiteApiWin32InternalConfiguration.NativeInteropSearchPath, architectureDirectory, interopFilename);
if (File.Exists(fileInSearchPathWithArchitecture))
interopPath = fileInSearchPathWithArchitecture;
}
}
if (interopPath == null)
{
// no NativeInteropSearchPath given (or nothing found using this path) so load native library from assembly execution direcotry
string assemblyCurrentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string relativePath = architectureDirectory + "\\" + interopFilename;
string assemblyInteropPath = Path.Combine(assemblyCurrentPath, architectureDirectory, interopFilename);
// try relative to assembly first, if that does not exist try relative to working dir
interopPath = File.Exists(assemblyInteropPath) ? assemblyInteropPath : relativePath;
}
IntPtr ret = LoadLibrary(interopPath);
if (ret == IntPtr.Zero)
{
throw new Exception("Failed to load native sqlite library from " + interopPath);
}
}
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_open", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_open([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_open_v2", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_open([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db,
int flags,
IntPtr zvfs);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_open16", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_open16([MarshalAs(UnmanagedType.LPWStr)] string filename, out IntPtr db);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_enable_load_extension",
CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_enable_load_extension(IntPtr db, int onoff);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_close", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_close(IntPtr db);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_initialize", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_initialize();
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_shutdown", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_shutdown();
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_config", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_config(ConfigOption option);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_win32_set_directory",
CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
public static extern int sqlite3_win32_set_directory(uint directoryType, string directoryPath);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_busy_timeout",
CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_busy_timeout(IntPtr db, int milliseconds);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_changes", CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_changes(IntPtr db);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_prepare_v2", CallingConvention = CallingConvention.Cdecl)
]
public static extern Result sqlite3_prepare_v2(IntPtr db, [MarshalAs(UnmanagedType.LPStr)] string sql,
int numBytes,
out IntPtr stmt, IntPtr pzTail);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_step", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_step(IntPtr stmt);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_reset", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_reset(IntPtr stmt);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_finalize", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_finalize(IntPtr stmt);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_last_insert_rowid",
CallingConvention = CallingConvention.Cdecl)]
public static extern long sqlite3_last_insert_rowid(IntPtr db);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_errmsg16", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr sqlite3_errmsg16(IntPtr db);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_bind_parameter_index",
CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_bind_parameter_index(IntPtr stmt, [MarshalAs(UnmanagedType.LPStr)] string name);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_bind_null", CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_bind_null(IntPtr stmt, int index);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_bind_int", CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_bind_int(IntPtr stmt, int index, int val);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_bind_int64", CallingConvention = CallingConvention.Cdecl)
]
public static extern int sqlite3_bind_int64(IntPtr stmt, int index, long val);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_bind_double", CallingConvention = CallingConvention.Cdecl
)]
public static extern int sqlite3_bind_double(IntPtr stmt, int index, double val);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_bind_text16", CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Unicode)]
public static extern int sqlite3_bind_text16(IntPtr stmt, int index,
[MarshalAs(UnmanagedType.LPWStr)] string val,
int n,
IntPtr free);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_bind_blob", CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_bind_blob(IntPtr stmt, int index, byte[] val, int n, IntPtr free);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_column_count",
CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_column_count(IntPtr stmt);
// [DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_column_name", CallingConvention = CallingConvention.Cdecl)]
// private extern IntPtr ColumnNameInternal(IntPtr stmt, int index);
// [DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_column_name", CallingConvention = CallingConvention.Cdecl)]
// public string ColumnName(IntPtr stmt, int index)
// {
// return ColumnNameInternal(stmt, index);
// }
public static string ColumnName16(IntPtr stmt, int index)
{
return Marshal.PtrToStringUni(sqlite3_column_name16(stmt, index));
}
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_column_type", CallingConvention = CallingConvention.Cdecl
)]
public static extern ColType sqlite3_column_type(IntPtr stmt, int index);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_column_int", CallingConvention = CallingConvention.Cdecl)
]
public static extern int sqlite3_column_int(IntPtr stmt, int index);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_column_int64",
CallingConvention = CallingConvention.Cdecl)]
public static extern long sqlite3_column_int64(IntPtr stmt, int index);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_column_double",
CallingConvention = CallingConvention.Cdecl)]
public static extern double sqlite3_column_double(IntPtr stmt, int index);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_column_text16",
CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr sqlite3_column_text16(IntPtr stmt, int index);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_column_blob", CallingConvention = CallingConvention.Cdecl
)]
public static extern byte[] ColumnBlob(IntPtr stmt, int index);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_column_blob", CallingConvention = CallingConvention.Cdecl
)]
public static extern IntPtr sqlite3_column_blob(IntPtr stmt, int index);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_column_bytes",
CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_column_bytes(IntPtr stmt, int index);
public static byte[] ColumnByteArray(IntPtr stmt, int index)
{
int length = sqlite3_column_bytes(stmt, index);
var result = new byte[length];
if (length > 0)
{
Marshal.Copy(sqlite3_column_blob(stmt, index), result, 0, length);
}
return result;
}
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_open_v2", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_open_v2(byte[] filename, out IntPtr db, int flags, IntPtr zvfs);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_column_name16",
CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr sqlite3_column_name16(IntPtr stmt, int index);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_extended_errcode", CallingConvention = CallingConvention.Cdecl)]
public static extern ExtendedResult sqlite3_extended_errcode(IntPtr db);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_libversion_number", CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_libversion_number();
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_sourceid", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr sqlite3_sourceid();
#region Backup
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_backup_init", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr sqlite3_backup_init(IntPtr destDB,
[MarshalAs(UnmanagedType.LPStr)] string destName,
IntPtr srcDB,
[MarshalAs(UnmanagedType.LPStr)] string srcName);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_backup_step", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_backup_step(IntPtr backup, int pageCount);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_backup_finish", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_backup_finish(IntPtr backup);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_backup_remaining", CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_backup_remaining(IntPtr backup);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_backup_pagecount", CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_backup_pagecount(IntPtr backup);
[DllImport("SQLite.Interop.dll", EntryPoint = "sqlite3_sleep", CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_sleep(int millis);
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using Xunit;
using System.Reflection;
namespace System.Diagnostics.TraceSourceTests
{
public sealed class TraceListenerCollectionClassTests
: ListBaseTests<TraceListenerCollection>
{
public override TraceListenerCollection Create(int count = 0)
{
// TraceListenerCollection has an internal constructor
// so we use a TraceSource to create one for us.
var list = new TraceSource("Test").Listeners;
list.Clear();
for (int i = 0; i < count; i++)
{
list.Add(CreateListener());
}
return list;
}
public TraceListener CreateListener()
{
return new TestTraceListener();
}
public override object CreateItem()
{
return CreateListener();
}
public override bool IsReadOnly
{
get { return false; }
}
public override bool IsFixedSize
{
get { return false; }
}
public override bool IsSynchronized
{
get { return true; }
}
[Fact]
public void TraceListenerIndexerTest()
{
var list = Create();
var item = CreateListener();
list.Add(item);
Assert.Equal(item, list[0]);
item = CreateListener();
list[0] = item;
Assert.Equal(item, list[0]);
}
[Fact]
public void TraceListenerNameIndexerTest()
{
var list = Create();
var item = CreateListener();
item.Name = "TestListener";
list.Add(item);
Assert.Equal(item, list["TestListener"]);
Assert.Equal(null, list["NO_EXIST"]);
}
[Fact]
public void AddListenerTest()
{
var list = Create();
var item = CreateListener();
list.Add(item);
Assert.Equal(item, list[0]);
Assert.Throws<ArgumentNullException>(() => list.Add(null));
Assert.Equal(1, list.Count);
}
[Fact]
public void AddRangeArrayTest()
{
var list = Create();
Assert.Throws<ArgumentNullException>(() => list.AddRange((TraceListener[])null));
var items =
new TraceListener[] {
CreateListener(),
CreateListener(),
};
list.AddRange(items);
Assert.Equal(items[0], list[0]);
Assert.Equal(items[1], list[1]);
}
[Fact]
public void AddRangeCollectionTest()
{
var list = Create();
Assert.Throws<ArgumentNullException>(() => list.AddRange((TraceListenerCollection)null));
var items = Create();
var item0 = CreateListener();
var item1 = CreateListener();
items.Add(item0);
items.Add(item1);
list.AddRange(items);
Assert.Equal(item0, list[0]);
Assert.Equal(item1, list[1]);
}
[Fact]
public void ContainsTest()
{
var list = Create();
var item = CreateListener();
list.Add(item);
Assert.True(list.Contains(item));
item = CreateListener();
Assert.False(list.Contains(item));
Assert.False(list.Contains(null));
}
[Fact]
public void CopyToListenerTest()
{
var list = Create(2);
var arr = new TraceListener[4];
list.CopyTo(arr, 1);
Assert.Null(arr[0]);
Assert.Equal(arr[1], list[0]);
Assert.Equal(arr[2], list[1]);
Assert.Null(arr[3]);
}
[Fact]
public void IndexOfListenerTest()
{
var list = Create(2);
var item = CreateListener();
list.Insert(1, item);
var idx = list.IndexOf(item);
Assert.Equal(1, idx);
idx = list.IndexOf(null);
Assert.Equal(-1, idx);
item = CreateListener();
idx = list.IndexOf(item);
Assert.Equal(-1, idx);
}
[Fact]
public void InsertListenerTest()
{
var list = Create(2);
var item = CreateListener();
list.Insert(1, item);
Assert.Equal(3, list.Count);
Assert.Equal(item, list[1]);
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(5, item));
}
[Fact]
public void RemoveListenerTest()
{
var list = Create();
var item = new TestTraceListener("Test1");
list.Add(item);
Assert.Equal(1, list.Count);
list.Remove(item);
Assert.Equal(0, list.Count);
}
[Fact]
public void RemoveAtTest()
{
var list = Create();
var item = new TestTraceListener("Test1");
list.Add(item);
list.RemoveAt(0);
Assert.False(list.Contains(item));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(-1));
}
[Fact]
public void RemoveByNameTest()
{
var list = Create();
var item = new TestTraceListener("Test1");
list.Add(item);
Assert.Equal(1, list.Count);
list.Remove("NO_EXIST");
Assert.Equal(1, list.Count);
list.Remove("Test1");
Assert.Equal(0, list.Count);
}
}
public abstract class ListBaseTests<T> : CollectionBaseTests<T>
where T : IList
{
public abstract bool IsReadOnly { get; }
public abstract bool IsFixedSize { get; }
public virtual Object CreateNonItem()
{
return new Object();
}
[Fact]
public virtual void AddTest()
{
var list = Create();
var item = CreateItem();
if (IsReadOnly || IsFixedSize)
{
Assert.Throws<NotSupportedException>(() => list.Add(item));
}
else
{
list.Add(item);
Assert.Equal(item, list[0]);
}
}
[Fact]
public virtual void AddExceptionTest()
{
var list = Create();
var item = CreateNonItem();
if (IsReadOnly || IsFixedSize)
{
Assert.Throws<NotSupportedException>(() => list.Add(item));
}
else
{
AssertExtensions.Throws<ArgumentException>("value", () => list.Add(item));
}
}
[Fact]
public virtual void IndexerGetTest()
{
var list = Create();
var item = CreateItem();
list.Add(item);
Assert.Equal(item, list[0]);
var item2 = CreateItem();
list[0] = item2;
Assert.Equal(item2, list[0]);
}
[Fact]
public virtual void IndexerSetTest()
{
var list = Create(3);
var item = CreateItem();
if (IsReadOnly)
{
Assert.Throws<NotSupportedException>(() => list[1] = item);
}
else
{
list[1] = item;
Assert.Equal(item, list[1]);
var nonItem = CreateNonItem();
AssertExtensions.Throws<ArgumentException>("value", () => list[1] = nonItem);
}
}
[Fact]
public virtual void IndexOfTest()
{
var list = Create();
var item0 = CreateItem();
list.Add(item0);
var item1 = CreateItem();
list.Add(item1);
Assert.Equal(0, list.IndexOf(item0));
Assert.Equal(1, list.IndexOf(item1));
var itemN = CreateItem();
Assert.Equal(-1, list.IndexOf(itemN));
}
[Fact]
public virtual void InsertTest()
{
var list = Create(2);
var item = CreateItem();
list.Insert(1, item);
Assert.Equal(3, list.Count);
Assert.Equal(item, list[1]);
}
[Fact]
public virtual void InsertExceptionTest()
{
var list = Create(2);
AssertExtensions.Throws<ArgumentException>("value", () => list.Insert(1, null));
}
[Fact]
public virtual void InsertExceptionTest2()
{
var list = Create(2);
var item = CreateItem();
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, item));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(4, item));
}
[Fact]
public virtual void RemoveTest()
{
var list = Create();
var item = CreateItem();
list.Add(item);
Assert.True(list.Contains(item));
list.Remove(item);
Assert.False(list.Contains(item));
}
[Fact]
public virtual void IsReadOnlyTest()
{
var list = Create();
Assert.Equal(IsReadOnly, list.IsReadOnly);
}
[Fact]
public virtual void IsFixedSizeTest()
{
var list = Create();
Assert.Equal(IsFixedSize, list.IsFixedSize);
}
}
public abstract class CollectionBaseTests<T>
: EnumerableBaseTests<T>
where T : ICollection
{
public abstract bool IsSynchronized { get; }
[Fact]
public virtual void CountTest()
{
var list = Create();
Assert.Equal(0, list.Count);
}
[Fact]
public virtual void SyncRootTest()
{
var list = Create();
var sync1 = list.SyncRoot;
Assert.NotNull(sync1);
var sync2 = list.SyncRoot;
Assert.NotNull(sync2);
Assert.Equal(sync1, sync2);
}
[Fact]
public virtual void IsSynchronizedTest()
{
var list = Create();
var value = list.IsSynchronized;
var expected = IsSynchronized;
Assert.Equal(expected, value);
}
[Fact]
public virtual void CopyToTest()
{
var list = Create(4);
var arr = new Object[4];
list.CopyTo(arr, 0);
}
[Fact]
public virtual void CopyToTest2()
{
var list = Create(4);
var arr = new Object[6];
list.CopyTo(arr, 2);
Assert.Null(arr[0]);
Assert.Null(arr[1]);
}
[Fact]
public virtual void CopyToExceptionTest()
{
var list = Create(4);
var arr = new Object[2];
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => list.CopyTo(arr, 0));
}
}
public abstract class EnumerableBaseTests<T>
where T : IEnumerable
{
public abstract T Create(int count = 0);
public abstract Object CreateItem();
[Fact]
public virtual void GetEnumeratorEmptyTest()
{
var list = Create();
var enumerator = list.GetEnumerator();
Assert.NotNull(enumerator);
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
var more = enumerator.MoveNext();
Assert.False(more);
more = enumerator.MoveNext();
Assert.False(more);
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
[Fact]
public virtual void GetEnumeratorTest()
{
var list = Create(2);
var enumerator = list.GetEnumerator();
Assert.NotNull(enumerator);
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
var more = enumerator.MoveNext();
Assert.True(more);
var item = enumerator.Current;
more = enumerator.MoveNext();
Assert.True(more);
more = enumerator.MoveNext();
Assert.False(more);
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
}
}
| |
/*++
Copyright (c) Microsoft Corporation
Module Name:
_CacheStreams.cs
Abstract:
The file contains two streams used in conjunction with caching.
The first class will combine two streams for reading into just one continued stream.
The second class will forward (as writes) to external stream all reads issued on a "this" stream.
Author:
Alexei Vopilov 21-Dec-2002
Revision History:
--*/
namespace System.Net.Cache {
using System;
using System.Net;
using System.IO;
using System.Threading;
using System.Collections.Specialized;
using System.Diagnostics;
internal abstract class BaseWrapperStream : Stream, IRequestLifetimeTracker
{
private Stream m_WrappedStream;
protected Stream WrappedStream
{
get { return m_WrappedStream; }
}
public BaseWrapperStream(Stream wrappedStream)
{
Debug.Assert(wrappedStream != null);
m_WrappedStream = wrappedStream;
}
public void TrackRequestLifetime(long requestStartTimestamp)
{
IRequestLifetimeTracker stream = m_WrappedStream as IRequestLifetimeTracker;
Debug.Assert(stream != null, "Wrapped stream must implement IRequestLifetimeTracker interface");
stream.TrackRequestLifetime(requestStartTimestamp);
}
}
//
// This stream will take two Streams (head and tail) and combine them into a single stream
// Only read IO is supported!
//
internal class CombinedReadStream : BaseWrapperStream, ICloseEx {
private Stream m_HeadStream;
private bool m_HeadEOF;
private long m_HeadLength;
private int m_ReadNesting;
private AsyncCallback m_ReadCallback; //lazy initialized
internal CombinedReadStream(Stream headStream, Stream tailStream)
: base(tailStream)
{
m_HeadStream = headStream;
m_HeadEOF = headStream == Stream.Null;
}
public override bool CanRead {
get {return m_HeadEOF? WrappedStream.CanRead: m_HeadStream.CanRead;}
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
public override bool CanSeek {
get {return false;}
}
public override bool CanWrite {
get {return false;}
}
public override long Length {
get {
return WrappedStream.Length + (m_HeadEOF? m_HeadLength: m_HeadStream.Length);
}
}
public override long Position {
get {
return WrappedStream.Position + (m_HeadEOF? m_HeadLength: m_HeadStream.Position);
}
set {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
}
public override long Seek(long offset, SeekOrigin origin) {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
public override void SetLength(long value) {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
public override void Write(byte[] buffer, int offset, int count) {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
public override void EndWrite(IAsyncResult asyncResult) {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
public override void Flush() {
}
public override int Read(byte[] buffer, int offset, int count) {
try {
if (Interlocked.Increment(ref m_ReadNesting) != 1) {
throw new NotSupportedException(SR.GetString(SR.net_io_invalidnestedcall, "Read", "read"));
}
if (m_HeadEOF) {
return WrappedStream.Read(buffer, offset, count);
}
else {
int result = m_HeadStream.Read(buffer, offset, count);
m_HeadLength += result;
if (result == 0 && count != 0) {
m_HeadEOF = true;
m_HeadStream.Close();
result = WrappedStream.Read(buffer, offset, count);
}
return result;
}
}
finally {
Interlocked.Decrement(ref m_ReadNesting);
}
}
//
// This is a wrapper result used to substitue the AsyncResult returned from m_HeadStream IO
// Note that once seen a EOF on m_HeadStream we will stop using this wrapper.
//
private class InnerAsyncResult: LazyAsyncResult {
public byte[] Buffer;
public int Offset;
public int Count;
public InnerAsyncResult(object userState, AsyncCallback userCallback, byte[] buffer, int offset, int count)
:base (null, userState, userCallback) {
Buffer = buffer;
Offset = offset;
Count = count;
}
}
private void ReadCallback(IAsyncResult transportResult) {
GlobalLog.Assert(transportResult.AsyncState is InnerAsyncResult, "InnerAsyncResult::ReadCallback|The state expected to be of type InnerAsyncResult, received {0}.", transportResult.GetType().FullName);
if (transportResult.CompletedSynchronously)
{
return;
}
InnerAsyncResult userResult = transportResult.AsyncState as InnerAsyncResult;
try {
// Complete transport IO, in this callback that is always the head stream
int count;
if (!m_HeadEOF) {
count = m_HeadStream.EndRead(transportResult);
m_HeadLength += count;
}
else {
count = WrappedStream.EndRead(transportResult);
}
//check on EOF condition
if (!m_HeadEOF && count == 0 && userResult.Count != 0) {
//Got a first stream EOF
m_HeadEOF = true;
m_HeadStream.Close();
IAsyncResult ar = WrappedStream.BeginRead(userResult.Buffer, userResult.Offset, userResult.Count, m_ReadCallback, userResult);
if (!ar.CompletedSynchronously) {
return;
}
count = WrappedStream.EndRead(ar);
}
// just complete user IO
userResult.Buffer = null;
userResult.InvokeCallback(count);
}
catch (Exception e) {
//ASYNC: try to ignore even serious exceptions (nothing to loose?)
if (userResult.InternalPeekCompleted)
throw;
userResult.InvokeCallback(e);
}
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) {
try {
if (Interlocked.Increment(ref m_ReadNesting) != 1) {
throw new NotSupportedException(SR.GetString(SR.net_io_invalidnestedcall, "BeginRead", "read"));
}
if (m_ReadCallback == null) {
m_ReadCallback = new AsyncCallback(ReadCallback);
}
if (m_HeadEOF) {
return WrappedStream.BeginRead(buffer, offset, count, callback, state);
}
else {
InnerAsyncResult userResult = new InnerAsyncResult(state, callback, buffer, offset, count);
IAsyncResult ar = m_HeadStream.BeginRead(buffer, offset, count, m_ReadCallback, userResult);
if (!ar.CompletedSynchronously)
{
return userResult;
}
int bytes = m_HeadStream.EndRead(ar);
m_HeadLength += bytes;
//check on EOF condition
if (bytes == 0 && userResult.Count != 0) {
//Got a first stream EOF
m_HeadEOF = true;
m_HeadStream.Close();
return WrappedStream.BeginRead(buffer, offset, count, callback, state);
}
else {
// just complete user IO
userResult.Buffer = null;
userResult.InvokeCallback(count);
return userResult;
}
}
}
catch {
Interlocked.Decrement(ref m_ReadNesting);
throw;
}
}
public override int EndRead(IAsyncResult asyncResult) {
if (Interlocked.Decrement(ref m_ReadNesting) != 0) {
Interlocked.Increment(ref m_ReadNesting);
throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndRead"));
}
if (asyncResult == null) {
throw new ArgumentNullException("asyncResult");
}
InnerAsyncResult myResult = asyncResult as InnerAsyncResult;
if (myResult == null) {
// We are just passing IO down, although m_HeadEOF should be always true here.
GlobalLog.Assert(m_HeadEOF, "CombinedReadStream::EndRead|m_HeadEOF is false and asyncResult is not of InnerAsyncResult type {0).", asyncResult.GetType().FullName);
return m_HeadEOF? WrappedStream.EndRead(asyncResult): m_HeadStream.EndRead(asyncResult);
}
// this is our wrapped AsyncResult
myResult.InternalWaitForCompletion();
// Exception?
if (myResult.Result is Exception) {
throw (Exception)(myResult.Result);
}
// Report the count read
return (int)myResult.Result;
}
// Subclasses should use Dispose(bool, CloseExState)
protected override sealed void Dispose(bool disposing) {
Dispose(disposing, CloseExState.Normal);
}
void ICloseEx.CloseEx(CloseExState closeState) {
Dispose(true, closeState);
}
protected virtual void Dispose(bool disposing, CloseExState closeState) {
// All below calls should already be idempotent
try {
if (disposing) {
try {
if (!m_HeadEOF) {
ICloseEx icloseEx = m_HeadStream as ICloseEx;
if (icloseEx != null) {
icloseEx.CloseEx(closeState);
}
else {
m_HeadStream.Close();
}
}
}
finally {
ICloseEx icloseEx = WrappedStream as ICloseEx;
if (icloseEx != null) {
icloseEx.CloseEx(closeState);
}
else {
WrappedStream.Close();
}
}
}
}
finally {
base.Dispose(disposing);
}
}
public override bool CanTimeout {
get {
return WrappedStream.CanTimeout && m_HeadStream.CanTimeout;
}
}
public override int ReadTimeout {
get {
return (m_HeadEOF) ? WrappedStream.ReadTimeout : m_HeadStream.ReadTimeout;
}
set {
WrappedStream.ReadTimeout = m_HeadStream.ReadTimeout = value;
}
}
public override int WriteTimeout {
get {
return (m_HeadEOF) ? WrappedStream.WriteTimeout : m_HeadStream.WriteTimeout;
}
set {
WrappedStream.WriteTimeout = m_HeadStream.WriteTimeout = value;
}
}
}
//
// This stream will plug into a stream and listen for all reads on it
// It is also constructed with yet another stream used for multiplexing IO to
//
// When it sees a read on this stream the result gets forwarded as write to a shadow stream.
// ONLY READ IO is supported!
//
internal class ForwardingReadStream : BaseWrapperStream, ICloseEx {
private Stream m_ShadowStream;
private int m_ReadNesting;
private bool m_ShadowStreamIsDead;
private AsyncCallback m_ReadCallback; // lazy initialized
private long m_BytesToSkip; // suppress from the read first number of bytes
private bool m_ThrowOnWriteError;
private bool m_SeenReadEOF;
internal ForwardingReadStream(Stream originalStream, Stream shadowStream, long bytesToSkip, bool throwOnWriteError)
: base(originalStream)
{
if (!shadowStream.CanWrite) {
throw new ArgumentException(SR.GetString(SR.net_cache_shadowstream_not_writable), "shadowStream");
}
m_ShadowStream = shadowStream;
m_BytesToSkip = bytesToSkip;
m_ThrowOnWriteError = throwOnWriteError;
}
public override bool CanRead {
get {return WrappedStream.CanRead;}
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
public override bool CanSeek {
get {return false;}
}
public override bool CanWrite {
get {return false;}
}
public override long Length {
get {
return WrappedStream.Length - m_BytesToSkip;
}
}
public override long Position {
get {
return WrappedStream.Position - m_BytesToSkip;
}
set {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
}
public override long Seek(long offset, SeekOrigin origin) {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
public override void SetLength(long value) {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
public override void Write(byte[] buffer, int offset, int count) {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
public override void EndWrite(IAsyncResult asyncResult) {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
public override void Flush() {
}
public override int Read(byte[] buffer, int offset, int count) {
bool isDoingWrite = false;
int result = -1;
if (Interlocked.Increment(ref m_ReadNesting) != 1) {
throw new NotSupportedException(SR.GetString(SR.net_io_invalidnestedcall, "Read", "read"));
}
try {
if (m_BytesToSkip != 0L) {
// Sometime we want to combine cached + live stream AND the user requested explicit range starts from not 0
byte[] tempBuffer = new byte[4096];
while (m_BytesToSkip != 0L) {
int bytes = WrappedStream.Read(tempBuffer, 0, (m_BytesToSkip < (long)tempBuffer.Length? (int)m_BytesToSkip: tempBuffer.Length));
if (bytes == 0)
m_SeenReadEOF = true;
m_BytesToSkip -= bytes;
if (!m_ShadowStreamIsDead)
m_ShadowStream.Write(tempBuffer, 0, bytes);
}
}
result = WrappedStream.Read(buffer, offset, count);
if (result == 0)
m_SeenReadEOF = true;
if (m_ShadowStreamIsDead) {
return result;
}
isDoingWrite = true;
m_ShadowStream.Write(buffer, offset, result);
return result;
}
catch (Exception e) {
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
throw;
GlobalLog.Print("ShadowReadStream::Read() Got Exception, disabling the shadow stream, stack trace = " + e.ToString());
if (!m_ShadowStreamIsDead) {
// try to ignore even serious exception, since got nothing to loose?
m_ShadowStreamIsDead = true;
try {
if (m_ShadowStream is ICloseEx)
((ICloseEx)m_ShadowStream).CloseEx(CloseExState.Abort | CloseExState.Silent);
else
m_ShadowStream.Close();
}
catch (Exception ee) {
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
throw;
GlobalLog.Print("ShadowReadStream::Read() Got (ignoring) Exception, on shadow stream.Close, stack trace = " + ee.ToString());
}
}
if (!isDoingWrite || m_ThrowOnWriteError)
throw;
return result;
}
finally {
Interlocked.Decrement(ref m_ReadNesting);
}
}
//
// This is a wrapper result used to substitue the AsyncResult returned from WrappedStream IO
// Note that once seen a m_ShadowStream error we will stop using this wrapper.
//
private class InnerAsyncResult: LazyAsyncResult {
public byte[] Buffer;
public int Offset;
public int Count;
public bool IsWriteCompletion;
public InnerAsyncResult(object userState, AsyncCallback userCallback, byte[] buffer, int offset, int count)
:base (null, userState, userCallback) {
Buffer = buffer;
Offset = offset;
Count = count;
}
}
private void ReadCallback(IAsyncResult transportResult) {
GlobalLog.Assert(transportResult.AsyncState is InnerAsyncResult, "InnerAsyncResult::ReadCallback|The state expected to be of type InnerAsyncResult, received {0}.", transportResult.GetType().FullName);
if (transportResult.CompletedSynchronously)
{
return;
}
// Recover our asyncResult
InnerAsyncResult userResult = transportResult.AsyncState as InnerAsyncResult;
ReadComplete(transportResult);
}
private void ReadComplete(IAsyncResult transportResult)
{
while(true)
{
// Recover our asyncResult
InnerAsyncResult userResult = transportResult.AsyncState as InnerAsyncResult;
try
{
if (!userResult.IsWriteCompletion)
{
userResult.Count = WrappedStream.EndRead(transportResult);
if (userResult.Count == 0)
m_SeenReadEOF = true;
if (!m_ShadowStreamIsDead) {
userResult.IsWriteCompletion = true;
//Optionally charge notification write IO
transportResult = m_ShadowStream.BeginWrite(userResult.Buffer, userResult.Offset, userResult.Count, m_ReadCallback, userResult);
if (transportResult.CompletedSynchronously)
{
continue;
}
return;
}
}
else
{
GlobalLog.Assert(!m_ShadowStreamIsDead, "ForwardingReadStream::ReadComplete|ERROR: IsWriteCompletion && m_ShadowStreamIsDead");
m_ShadowStream.EndWrite(transportResult);
userResult.IsWriteCompletion = false;
}
}
catch (Exception e)
{
//ASYNC: try to ignore even serious exceptions (nothing to loose?)
if (userResult.InternalPeekCompleted)
{
GlobalLog.Print("ShadowReadStream::ReadComplete() Rethrowing Exception (end), userResult.IsCompleted, stack trace = " + e.ToString());
throw;
}
try
{
m_ShadowStreamIsDead = true;
if (m_ShadowStream is ICloseEx)
((ICloseEx)m_ShadowStream).CloseEx(CloseExState.Abort | CloseExState.Silent);
else
m_ShadowStream.Close();
}
catch (Exception ee)
{
//ASYNC: Again try to ignore even serious exceptions
GlobalLog.Print("ShadowReadStream::ReadComplete() Got (ignoring) Exception, on shadow stream.Close, stack trace = " + ee.ToString());
}
if (!userResult.IsWriteCompletion || m_ThrowOnWriteError)
{
if (transportResult.CompletedSynchronously)
{
throw;
}
userResult.InvokeCallback(e);
return;
}
}
// Need to process, re-issue the read.
try
{
if (m_BytesToSkip != 0L) {
m_BytesToSkip -= userResult.Count;
userResult.Count = m_BytesToSkip < (long)userResult.Buffer.Length? (int)m_BytesToSkip: userResult.Buffer.Length;
if (m_BytesToSkip == 0L) {
// we did hide the original IO request in the outer iaresult state.
// charge the real user operation now
transportResult = userResult;
userResult = userResult.AsyncState as InnerAsyncResult;
GlobalLog.Assert(userResult != null, "ForwardingReadStream::ReadComplete|ERROR: Inner IAResult is null after stream FastForwarding.");
}
transportResult = WrappedStream.BeginRead(userResult.Buffer, userResult.Offset, userResult.Count, m_ReadCallback, userResult);
if (transportResult.CompletedSynchronously)
{
continue;
}
return;
}
//if came to here, complete original user IO
userResult.InvokeCallback(userResult.Count);
return;
}
catch (Exception e)
{
//ASYNC: try to ignore even serious exceptions (nothing to loose?)
if (userResult.InternalPeekCompleted)
{
GlobalLog.Print("ShadowReadStream::ReadComplete() Rethrowing Exception (begin), userResult.IsCompleted, stack trace = " + e.ToString());
throw;
}
try
{
m_ShadowStreamIsDead = true;
if (m_ShadowStream is ICloseEx)
((ICloseEx)m_ShadowStream).CloseEx(CloseExState.Abort | CloseExState.Silent);
else
m_ShadowStream.Close();
}
catch (Exception ee)
{
//ASYNC: Again try to ignore even serious exceptions
GlobalLog.Print("ShadowReadStream::ReadComplete() Got (ignoring) Exception, on shadow stream.Close (after begin), stack trace = " + ee.ToString());
}
if (transportResult.CompletedSynchronously)
{
throw;
}
// This will set the exception result first then try to execute a user callback
userResult.InvokeCallback(e);
return;
}
}
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) {
if (Interlocked.Increment(ref m_ReadNesting) != 1) {
throw new NotSupportedException(SR.GetString(SR.net_io_invalidnestedcall, "BeginRead", "read"));
}
try {
if (m_ReadCallback == null) {
m_ReadCallback = new AsyncCallback(ReadCallback);
}
if (m_ShadowStreamIsDead && m_BytesToSkip == 0L) {
return WrappedStream.BeginRead(buffer, offset, count, callback, state);
}
else {
InnerAsyncResult userResult = new InnerAsyncResult(state, callback, buffer, offset, count);
if (m_BytesToSkip != 0L) {
InnerAsyncResult temp = userResult;
userResult = new InnerAsyncResult(temp, null, new byte[4096],
0, m_BytesToSkip < (long) buffer.Length? (int)m_BytesToSkip: buffer.Length);
}
IAsyncResult result = WrappedStream.BeginRead(userResult.Buffer, userResult.Offset, userResult.Count, m_ReadCallback, userResult);
if (result.CompletedSynchronously)
{
ReadComplete(result);
}
return userResult;
}
}
catch {
Interlocked.Decrement(ref m_ReadNesting);
throw;
}
}
public override int EndRead(IAsyncResult asyncResult) {
if (Interlocked.Decrement(ref m_ReadNesting) != 0) {
Interlocked.Increment(ref m_ReadNesting);
throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndRead"));
}
if (asyncResult == null) {
throw new ArgumentNullException("asyncResult");
}
InnerAsyncResult myResult = asyncResult as InnerAsyncResult;
if (myResult == null) {
// We are just passing IO down, although the shadow stream should be dead for now.
GlobalLog.Assert(m_ShadowStreamIsDead, "ForwardingReadStream::EndRead|m_ShadowStreamIsDead is false and asyncResult is not of InnerAsyncResult type {0}.", asyncResult.GetType().FullName);
int bytes = WrappedStream.EndRead(asyncResult);
if (bytes == 0)
m_SeenReadEOF = true;
}
// this is our wrapped AsyncResult
bool suceess = false;
try {
myResult.InternalWaitForCompletion();
// Exception?
if (myResult.Result is Exception)
throw (Exception)(myResult.Result);
suceess = true;
}
finally {
if (!suceess && !m_ShadowStreamIsDead) {
m_ShadowStreamIsDead = true;
if (m_ShadowStream is ICloseEx)
((ICloseEx)m_ShadowStream).CloseEx(CloseExState.Abort | CloseExState.Silent);
else
m_ShadowStream.Close();
}
}
// Report the read count
return (int)myResult.Result;
}
// Subclasses should use Dispose(bool, CloseExState)
protected sealed override void Dispose(bool disposing) {
Dispose(disposing, CloseExState.Normal);
}
private int _Disposed;
void ICloseEx.CloseEx(CloseExState closeState) {
if (Interlocked.Increment(ref _Disposed) == 1) {
// This would allow us to cache the response stream that user throws away
// Next time the cached version could save us from an extra roundtrip
if (closeState == CloseExState.Silent) {
try {
int total = 0;
int bytesRead;
while (total < ConnectStream.s_DrainingBuffer.Length && (bytesRead = Read(ConnectStream.s_DrainingBuffer, 0, ConnectStream.s_DrainingBuffer.Length)) > 0) {
total += bytesRead;
}
}
catch (Exception exception) {
//ATTN: this path will swalow errors regardless of m_IsThrowOnWriteError setting
// A "Silent" close is for an intermediate response that is to be ignored anyway
if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException) {
throw;
}
}
}
Dispose(true, closeState);
}
}
protected virtual void Dispose(bool disposing, CloseExState closeState) {
// All below calls should already be idempotent
try {
if (disposing) {
try {
ICloseEx icloseEx = WrappedStream as ICloseEx;
if (icloseEx != null) {
icloseEx.CloseEx(closeState);
}
else {
WrappedStream.Close();
}
}
finally {
// Notify the wirte stream on a partial response if did not see EOF on read
if (!m_SeenReadEOF)
closeState |= CloseExState.Abort;
//
// We don't want to touch m_ShadowStreamIsDead because Close() can be called from other thread while IO is in progress.
// We assume that all streams used by this class are thread safe on Close().
// m_ShadowStreamIsDead = true;
if (m_ShadowStream is ICloseEx)
((ICloseEx)m_ShadowStream).CloseEx(closeState);
else
m_ShadowStream.Close();
}
}
}
finally {
base.Dispose(disposing);
}
}
public override bool CanTimeout {
get {
return WrappedStream.CanTimeout && m_ShadowStream.CanTimeout;
}
}
public override int ReadTimeout {
get {
return WrappedStream.ReadTimeout;
}
set {
WrappedStream.ReadTimeout = m_ShadowStream.ReadTimeout = value;
}
}
public override int WriteTimeout {
get {
return m_ShadowStream.WriteTimeout;
}
set {
WrappedStream.WriteTimeout = m_ShadowStream.WriteTimeout = value;
}
}
}
//
// This stream will listen on the parent stream Close.
// Assuming the parent stream represents a READ stream such as CombinedReadStream or a response stream.
// When the paretn stream is closed this wrapper will update the metadata associated with the entry.
internal class MetadataUpdateStream : BaseWrapperStream, ICloseEx {
private RequestCache m_Cache;
private string m_Key;
private DateTime m_Expires;
private DateTime m_LastModified;
private DateTime m_LastSynchronized;
private TimeSpan m_MaxStale;
private StringCollection m_EntryMetadata;
private StringCollection m_SystemMetadata;
private bool m_CacheDestroy;
private bool m_IsStrictCacheErrors;
internal MetadataUpdateStream( Stream parentStream,
RequestCache cache,
string key,
DateTime expiresGMT,
DateTime lastModifiedGMT,
DateTime lastSynchronizedGMT,
TimeSpan maxStale,
StringCollection entryMetadata,
StringCollection systemMetadata,
bool isStrictCacheErrors)
: base(parentStream)
{
m_Cache = cache;
m_Key = key;
m_Expires = expiresGMT;
m_LastModified = lastModifiedGMT;
m_LastSynchronized = lastSynchronizedGMT;
m_MaxStale = maxStale;
m_EntryMetadata = entryMetadata;
m_SystemMetadata = systemMetadata;
m_IsStrictCacheErrors = isStrictCacheErrors;
}
//
// This constructor will result in removing a cache entry upon closure
//
private MetadataUpdateStream(Stream parentStream, RequestCache cache, string key, bool isStrictCacheErrors)
: base(parentStream)
{
m_Cache = cache;
m_Key = key;
m_CacheDestroy = true;
m_IsStrictCacheErrors = isStrictCacheErrors;
}
//
//
//
/*
// Consider removing.
public static Stream CreateEntryRemovalStream( Stream parentStream, RequestCache cache, string key, bool isStrictCacheErrors)
{
return new MetadataUpdateStream(parentStream, cache, key, isStrictCacheErrors);
}
*/
//
public override bool CanRead {
get {return WrappedStream.CanRead;}
}
//
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
public override bool CanSeek {
get {return WrappedStream.CanSeek;}
}
//
public override bool CanWrite {
get {return WrappedStream.CanWrite;}
}
//
public override long Length {
get {return WrappedStream.Length;}
}
//
public override long Position {
get {return WrappedStream.Position;}
set {WrappedStream.Position = value;}
}
public override long Seek(long offset, SeekOrigin origin) {
return WrappedStream.Seek(offset, origin);
}
public override void SetLength(long value) {
WrappedStream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count) {
WrappedStream.Write(buffer, offset, count);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) {
return WrappedStream.BeginWrite(buffer, offset, count, callback, state);
}
public override void EndWrite(IAsyncResult asyncResult) {
WrappedStream.EndWrite(asyncResult);
}
public override void Flush() {
WrappedStream.Flush();
}
public override int Read(byte[] buffer, int offset, int count) {
return WrappedStream.Read(buffer, offset, count);
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) {
return WrappedStream.BeginRead(buffer, offset, count, callback, state);
}
public override int EndRead(IAsyncResult asyncResult) {
return WrappedStream.EndRead(asyncResult);
}
// Subclasses should use Dispose(bool, CloseExState)
protected sealed override void Dispose(bool disposing) {
Dispose(disposing, CloseExState.Normal);
}
void ICloseEx.CloseEx(CloseExState closeState) {
Dispose(true, closeState);
}
public override bool CanTimeout {
get {
return WrappedStream.CanTimeout;
}
}
public override int ReadTimeout {
get {
return WrappedStream.ReadTimeout;
}
set {
WrappedStream.ReadTimeout = value;
}
}
public override int WriteTimeout {
get {
return WrappedStream.WriteTimeout;
}
set {
WrappedStream.WriteTimeout = value;
}
}
private int _Disposed;
protected virtual void Dispose(bool disposing, CloseExState closeState) {
try {
if (Interlocked.Increment(ref _Disposed) == 1) {
if (disposing) {
ICloseEx icloseEx = WrappedStream as ICloseEx;
if (icloseEx != null) {
icloseEx.CloseEx(closeState);
}
else {
WrappedStream.Close();
}
if (m_CacheDestroy)
{
if (m_IsStrictCacheErrors)
{
m_Cache.Remove(m_Key);
}
else
{
m_Cache.TryRemove(m_Key);
}
}
else
{
if (m_IsStrictCacheErrors)
{
m_Cache.Update(m_Key, m_Expires, m_LastModified, m_LastSynchronized, m_MaxStale, m_EntryMetadata, m_SystemMetadata);
}
else
{
m_Cache.TryUpdate(m_Key, m_Expires, m_LastModified, m_LastSynchronized, m_MaxStale, m_EntryMetadata, m_SystemMetadata);
}
}
}
}
}
finally {
base.Dispose(disposing);
}
}
}
//
// This stream is for Partial responses.
// It will scroll to the given position and limit the original stream windows to given size
internal class RangeStream : BaseWrapperStream, ICloseEx {
long m_Offset;
long m_Size;
long m_Position;
internal RangeStream (Stream parentStream, long offset, long size)
: base(parentStream)
{
m_Offset = offset;
m_Size = size;
if (WrappedStream.CanSeek) {
WrappedStream.Position = offset;
m_Position = offset;
}
else {
// for now we expect a FileStream that is seekable.
throw new NotSupportedException(SR.GetString(SR.net_cache_non_seekable_stream_not_supported));
}
}
public override bool CanRead {
get {return WrappedStream.CanRead;}
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
public override bool CanSeek {
get {return WrappedStream.CanSeek;}
}
public override bool CanWrite {
get {return WrappedStream.CanWrite;}
}
public override long Length {
get {
long dummy = WrappedStream.Length;
return m_Size;
}
}
public override long Position {
get {return WrappedStream.Position-m_Offset;}
set {
value += m_Offset;
if (value > m_Offset + m_Size) {
value = m_Offset + m_Size;
}
WrappedStream.Position = value;
}
}
public override long Seek(long offset, SeekOrigin origin) {
switch (origin) {
case SeekOrigin.Begin:
offset += m_Offset;
if (offset > m_Offset+m_Size) {
offset = m_Offset+m_Size;
}
if (offset < m_Offset) {
offset = m_Offset;
}
break;
case SeekOrigin.End:
offset -= (m_Offset+m_Size);
if (offset > 0) {
offset = 0;
}
if (offset < -m_Size) {
offset = -m_Size;
}
break;
default:
if (m_Position+offset > m_Offset+m_Size) {
offset = (m_Offset+m_Size) - m_Position;
}
if (m_Position+offset < m_Offset) {
offset = m_Offset-m_Position;
}
break;
}
m_Position=WrappedStream.Seek(offset, origin);
return m_Position-m_Offset;
}
public override void SetLength(long value) {
throw new NotSupportedException(SR.GetString(SR.net_cache_unsupported_partial_stream));
}
public override void Write(byte[] buffer, int offset, int count) {
if (m_Position + count > m_Offset+m_Size) {
throw new NotSupportedException(SR.GetString(SR.net_cache_unsupported_partial_stream));
}
WrappedStream.Write(buffer, offset, count);
m_Position += count;
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) {
if (m_Position+offset > m_Offset+m_Size) {
throw new NotSupportedException(SR.GetString(SR.net_cache_unsupported_partial_stream));
}
return WrappedStream.BeginWrite(buffer, offset, count, callback, state);
}
public override void EndWrite(IAsyncResult asyncResult) {
WrappedStream.EndWrite(asyncResult);
m_Position = WrappedStream.Position;
}
public override void Flush() {
WrappedStream.Flush();
}
public override int Read(byte[] buffer, int offset, int count) {
if (m_Position >= m_Offset+m_Size) {
return 0;
}
if (m_Position + count > m_Offset+m_Size) {
count = (int)(m_Offset + m_Size - m_Position);
}
int result = WrappedStream.Read(buffer, offset, count);
m_Position += result;
return result;
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) {
if (m_Position >= m_Offset+m_Size) {
count = 0;
}
else if (m_Position + count > m_Offset+m_Size) {
count = (int)(m_Offset + m_Size - m_Position);
}
return WrappedStream.BeginRead(buffer, offset, count, callback, state);
}
public override int EndRead(IAsyncResult asyncResult) {
int result = WrappedStream.EndRead(asyncResult);
m_Position += result;
return result;
}
// Subclasses should use Dispose(bool, CloseExState)
protected sealed override void Dispose(bool disposing) {
Dispose(disposing, CloseExState.Normal);
}
void ICloseEx.CloseEx(CloseExState closeState) {
Dispose(true, closeState);
}
public override bool CanTimeout {
get {
return WrappedStream.CanTimeout;
}
}
public override int ReadTimeout {
get {
return WrappedStream.ReadTimeout;
}
set {
WrappedStream.ReadTimeout = value;
}
}
public override int WriteTimeout {
get {
return WrappedStream.WriteTimeout;
}
set {
WrappedStream.WriteTimeout = value;
}
}
protected virtual void Dispose(bool disposing, CloseExState closeState) {
// All calls below should already be idempotent.
try
{
if (disposing) {
ICloseEx icloseEx = WrappedStream as ICloseEx;
if (icloseEx != null) {
icloseEx.CloseEx(closeState);
}
else {
WrappedStream.Close();
}
}
}
finally
{
base.Dispose(disposing);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.Win32.SafeHandles
{
public sealed partial class SafeProcessHandle : System.Runtime.InteropServices.SafeHandle
{
public SafeProcessHandle(System.IntPtr existingHandle, bool ownsHandle) : base(default(System.IntPtr), default(bool)) { }
protected override bool ReleaseHandle() { return default(bool); }
}
}
namespace System.Diagnostics
{
public partial class DataReceivedEventArgs : System.EventArgs
{
internal DataReceivedEventArgs() { }
public string Data { get { return default(string); } }
}
public delegate void DataReceivedEventHandler(object sender, System.Diagnostics.DataReceivedEventArgs e);
public partial class Process
{
public Process() { }
public int BasePriority { get { return default(int); } }
[System.ComponentModel.DefaultValueAttribute(false)]
public bool EnableRaisingEvents { get { return default(bool); } set { } }
public int ExitCode { get { return default(int); } }
public System.DateTime ExitTime { get { return default(System.DateTime); } }
public bool HasExited { get { return default(bool); } }
public int Id { get { return default(int); } }
public string MachineName { get { return default(string); } }
public System.Diagnostics.ProcessModule MainModule { get { return default(System.Diagnostics.ProcessModule); } }
public System.IntPtr MaxWorkingSet { get { return default(System.IntPtr); } set { } }
public System.IntPtr MinWorkingSet { get { return default(System.IntPtr); } set { } }
public System.Diagnostics.ProcessModuleCollection Modules { get { return default(System.Diagnostics.ProcessModuleCollection); } }
public long NonpagedSystemMemorySize64 { get { return default(long); } }
public long PagedMemorySize64 { get { return default(long); } }
public long PagedSystemMemorySize64 { get { return default(long); } }
public long PeakPagedMemorySize64 { get { return default(long); } }
public long PeakVirtualMemorySize64 { get { return default(long); } }
public long PeakWorkingSet64 { get { return default(long); } }
public bool PriorityBoostEnabled { get { return default(bool); } set { } }
public System.Diagnostics.ProcessPriorityClass PriorityClass { get { return default(System.Diagnostics.ProcessPriorityClass); } set { } }
public long PrivateMemorySize64 { get { return default(long); } }
public System.TimeSpan PrivilegedProcessorTime { get { return default(System.TimeSpan); } }
public string ProcessName { get { return default(string); } }
public System.IntPtr ProcessorAffinity { get { return default(System.IntPtr); } set { } }
public Microsoft.Win32.SafeHandles.SafeProcessHandle SafeHandle { get { return default(Microsoft.Win32.SafeHandles.SafeProcessHandle); } }
public int SessionId { get { return default(int); } }
public System.IO.StreamReader StandardError { get { return default(System.IO.StreamReader); } }
public System.IO.StreamWriter StandardInput { get { return default(System.IO.StreamWriter); } }
public System.IO.StreamReader StandardOutput { get { return default(System.IO.StreamReader); } }
public System.Diagnostics.ProcessStartInfo StartInfo { get { return default(System.Diagnostics.ProcessStartInfo); } set { } }
public System.DateTime StartTime { get { return default(System.DateTime); } }
public System.Diagnostics.ProcessThreadCollection Threads { get { return default(System.Diagnostics.ProcessThreadCollection); } }
public System.TimeSpan TotalProcessorTime { get { return default(System.TimeSpan); } }
public System.TimeSpan UserProcessorTime { get { return default(System.TimeSpan); } }
public long VirtualMemorySize64 { get { return default(long); } }
public long WorkingSet64 { get { return default(long); } }
public event System.Diagnostics.DataReceivedEventHandler ErrorDataReceived { add { } remove { } }
public event System.EventHandler Exited { add { } remove { } }
public event System.Diagnostics.DataReceivedEventHandler OutputDataReceived { add { } remove { } }
public void BeginErrorReadLine() { }
public void BeginOutputReadLine() { }
public void CancelErrorRead() { }
public void CancelOutputRead() { }
public static void EnterDebugMode() { }
public static System.Diagnostics.Process GetCurrentProcess() { return default(System.Diagnostics.Process); }
public static System.Diagnostics.Process GetProcessById(int processId) { return default(System.Diagnostics.Process); }
public static System.Diagnostics.Process GetProcessById(int processId, string machineName) { return default(System.Diagnostics.Process); }
public static System.Diagnostics.Process[] GetProcesses() { return default(System.Diagnostics.Process[]); }
public static System.Diagnostics.Process[] GetProcesses(string machineName) { return default(System.Diagnostics.Process[]); }
public static System.Diagnostics.Process[] GetProcessesByName(string processName) { return default(System.Diagnostics.Process[]); }
public static System.Diagnostics.Process[] GetProcessesByName(string processName, string machineName) { return default(System.Diagnostics.Process[]); }
public void Kill() { }
public static void LeaveDebugMode() { }
protected void OnExited() { }
public void Refresh() { }
public bool Start() { return default(bool); }
public static System.Diagnostics.Process Start(System.Diagnostics.ProcessStartInfo startInfo) { return default(System.Diagnostics.Process); }
public static System.Diagnostics.Process Start(string fileName) { return default(System.Diagnostics.Process); }
public static System.Diagnostics.Process Start(string fileName, string arguments) { return default(System.Diagnostics.Process); }
public void WaitForExit() { }
public bool WaitForExit(int milliseconds) { return default(bool); }
}
public partial class ProcessModule
{
internal ProcessModule() { }
public System.IntPtr BaseAddress { get { return default(System.IntPtr); } }
public System.IntPtr EntryPointAddress { get { return default(System.IntPtr); } }
public string FileName { get { return default(string); } }
public int ModuleMemorySize { get { return default(int); } }
public string ModuleName { get { return default(string); } }
public override string ToString() { return default(string); }
}
public partial class ProcessModuleCollection
{
protected ProcessModuleCollection() { }
public ProcessModuleCollection(System.Diagnostics.ProcessModule[] processModules) { }
public System.Diagnostics.ProcessModule this[int index] { get { return default(System.Diagnostics.ProcessModule); } }
public bool Contains(System.Diagnostics.ProcessModule module) { return default(bool); }
public void CopyTo(System.Diagnostics.ProcessModule[] array, int index) { }
public int IndexOf(System.Diagnostics.ProcessModule module) { return default(int); }
}
public enum ProcessPriorityClass
{
AboveNormal = 32768,
BelowNormal = 16384,
High = 128,
Idle = 64,
Normal = 32,
RealTime = 256,
}
public sealed partial class ProcessStartInfo
{
public ProcessStartInfo() { }
public ProcessStartInfo(string fileName) { }
public ProcessStartInfo(string fileName, string arguments) { }
public string Arguments { get { return default(string); } set { } }
public bool CreateNoWindow { get { return default(bool); } set { } }
public string Domain { get { return default(string); } set { } }
[System.ComponentModel.DefaultValueAttribute(null)]
public System.Collections.Generic.IDictionary<string, string> Environment { get { return default(System.Collections.Generic.IDictionary<string, string>); } }
public string FileName { get { return default(string); } set { } }
public bool LoadUserProfile { get { return default(bool); } set { } }
public bool RedirectStandardError { get { return default(bool); } set { } }
public bool RedirectStandardInput { get { return default(bool); } set { } }
public bool RedirectStandardOutput { get { return default(bool); } set { } }
public System.Text.Encoding StandardErrorEncoding { get { return default(System.Text.Encoding); } set { } }
public System.Text.Encoding StandardOutputEncoding { get { return default(System.Text.Encoding); } set { } }
public string UserName { get { return default(string); } set { } }
public bool UseShellExecute { get { return default(bool); } set { } }
public string WorkingDirectory { get { return default(string); } set { } }
}
public partial class ProcessThread
{
internal ProcessThread() { }
public int BasePriority { get { return default(int); } }
public int CurrentPriority { get { return default(int); } }
public int Id { get { return default(int); } }
public int IdealProcessor { set { } }
public bool PriorityBoostEnabled { get { return default(bool); } set { } }
public System.Diagnostics.ThreadPriorityLevel PriorityLevel { get { return default(System.Diagnostics.ThreadPriorityLevel); } set { } }
public System.TimeSpan PrivilegedProcessorTime { get { return default(System.TimeSpan); } }
public System.IntPtr ProcessorAffinity { set { } }
public System.IntPtr StartAddress { get { return default(System.IntPtr); } }
public System.DateTime StartTime { get { return default(System.DateTime); } }
public System.Diagnostics.ThreadState ThreadState { get { return default(System.Diagnostics.ThreadState); } }
public System.TimeSpan TotalProcessorTime { get { return default(System.TimeSpan); } }
public System.TimeSpan UserProcessorTime { get { return default(System.TimeSpan); } }
public System.Diagnostics.ThreadWaitReason WaitReason { get { return default(System.Diagnostics.ThreadWaitReason); } }
public void ResetIdealProcessor() { }
}
public partial class ProcessThreadCollection
{
protected ProcessThreadCollection() { }
public ProcessThreadCollection(System.Diagnostics.ProcessThread[] processThreads) { }
public System.Diagnostics.ProcessThread this[int index] { get { return default(System.Diagnostics.ProcessThread); } }
public int Add(System.Diagnostics.ProcessThread thread) { return default(int); }
public bool Contains(System.Diagnostics.ProcessThread thread) { return default(bool); }
public void CopyTo(System.Diagnostics.ProcessThread[] array, int index) { }
public int IndexOf(System.Diagnostics.ProcessThread thread) { return default(int); }
public void Insert(int index, System.Diagnostics.ProcessThread thread) { }
public void Remove(System.Diagnostics.ProcessThread thread) { }
}
public enum ThreadPriorityLevel
{
AboveNormal = 1,
BelowNormal = -1,
Highest = 2,
Idle = -15,
Lowest = -2,
Normal = 0,
TimeCritical = 15,
}
public enum ThreadState
{
Initialized = 0,
Ready = 1,
Running = 2,
Standby = 3,
Terminated = 4,
Transition = 6,
Unknown = 7,
Wait = 5,
}
public enum ThreadWaitReason
{
EventPairHigh = 7,
EventPairLow = 8,
ExecutionDelay = 4,
Executive = 0,
FreePage = 1,
LpcReceive = 9,
LpcReply = 10,
PageIn = 2,
PageOut = 12,
Suspended = 5,
SystemAllocation = 3,
Unknown = 13,
UserRequest = 6,
VirtualMemory = 11,
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
namespace System.Collections.Immutable
{
/// <summary>
/// An immutable sorted dictionary implementation.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableDictionaryDebuggerProxy<,>))]
public sealed partial class ImmutableSortedDictionary<TKey, TValue> : IImmutableDictionary<TKey, TValue>, ISortKeyCollection<TKey>, IDictionary<TKey, TValue>, IDictionary
{
/// <summary>
/// An empty sorted dictionary with default sort and equality comparers.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly ImmutableSortedDictionary<TKey, TValue> Empty = new ImmutableSortedDictionary<TKey, TValue>();
/// <summary>
/// The root node of the AVL tree that stores this map.
/// </summary>
private readonly Node _root;
/// <summary>
/// The number of elements in the set.
/// </summary>
private readonly int _count;
/// <summary>
/// The comparer used to sort keys in this map.
/// </summary>
private readonly IComparer<TKey> _keyComparer;
/// <summary>
/// The comparer used to detect equivalent values in this map.
/// </summary>
private readonly IEqualityComparer<TValue> _valueComparer;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedDictionary{TKey, TValue}"/> class.
/// </summary>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
internal ImmutableSortedDictionary(IComparer<TKey> keyComparer = null, IEqualityComparer<TValue> valueComparer = null)
{
_keyComparer = keyComparer ?? Comparer<TKey>.Default;
_valueComparer = valueComparer ?? EqualityComparer<TValue>.Default;
_root = Node.EmptyNode;
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedDictionary{TKey, TValue}"/> class.
/// </summary>
/// <param name="root">The root of the tree containing the contents of the map.</param>
/// <param name="count">The number of elements in this map.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
private ImmutableSortedDictionary(Node root, int count, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
Requires.NotNull(root, nameof(root));
Requires.Range(count >= 0, nameof(count));
Requires.NotNull(keyComparer, nameof(keyComparer));
Requires.NotNull(valueComparer, nameof(valueComparer));
root.Freeze();
_root = root;
_count = count;
_keyComparer = keyComparer;
_valueComparer = valueComparer;
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public ImmutableSortedDictionary<TKey, TValue> Clear()
{
return _root.IsEmpty ? this : Empty.WithComparers(_keyComparer, _valueComparer);
}
#region IImmutableMap<TKey, TValue> Properties
/// <summary>
/// Gets the value comparer used to determine whether values are equal.
/// </summary>
public IEqualityComparer<TValue> ValueComparer
{
get { return _valueComparer; }
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public bool IsEmpty
{
get { return _root.IsEmpty; }
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public int Count
{
get { return _count; }
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public IEnumerable<TKey> Keys
{
get { return _root.Keys; }
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public IEnumerable<TValue> Values
{
get { return _root.Values; }
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Clear()
{
return this.Clear();
}
#endregion
#region IDictionary<TKey, TValue> Properties
/// <summary>
/// Gets the keys.
/// </summary>
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get { return new KeysCollectionAccessor<TKey, TValue>(this); }
}
/// <summary>
/// Gets the values.
/// </summary>
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get { return new ValuesCollectionAccessor<TKey, TValue>(this); }
}
#endregion
#region ICollection<KeyValuePair<TKey, TValue>> Properties
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return true; }
}
#endregion
#region ISortKeyCollection<TKey> Properties
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public IComparer<TKey> KeyComparer
{
get { return _keyComparer; }
}
#endregion
/// <summary>
/// Gets the root node (for testing purposes).
/// </summary>
internal Node Root
{
get { return _root; }
}
#region IImmutableMap<TKey, TValue> Indexers
/// <summary>
/// Gets the <typeparamref name="TValue"/> with the specified key.
/// </summary>
public TValue this[TKey key]
{
get
{
Requires.NotNullAllowStructs(key, nameof(key));
TValue value;
if (this.TryGetValue(key, out value))
{
return value;
}
throw new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString()));
}
}
#if !NETSTANDARD10
/// <summary>
/// Returns a read-only reference to the value associated with the provided key.
/// </summary>
/// <exception cref="KeyNotFoundException">If the key is not present.</exception>
public ref readonly TValue ValueRef(TKey key)
{
Requires.NotNullAllowStructs(key, nameof(key));
return ref _root.ValueRef(key, _keyComparer);
}
#endif
#endregion
/// <summary>
/// Gets or sets the <typeparamref name="TValue"/> with the specified key.
/// </summary>
TValue IDictionary<TKey, TValue>.this[TKey key]
{
get { return this[key]; }
set { throw new NotSupportedException(); }
}
#region Public methods
/// <summary>
/// Creates a collection with the same contents as this collection that
/// can be efficiently mutated across multiple operations using standard
/// mutable interfaces.
/// </summary>
/// <remarks>
/// This is an O(1) operation and results in only a single (small) memory allocation.
/// The mutable collection that is returned is *not* thread-safe.
/// </remarks>
[Pure]
public Builder ToBuilder()
{
// We must not cache the instance created here and return it to various callers.
// Those who request a mutable collection must get references to the collection
// that version independently of each other.
return new Builder(this);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[Pure]
public ImmutableSortedDictionary<TKey, TValue> Add(TKey key, TValue value)
{
Requires.NotNullAllowStructs(key, nameof(key));
bool mutated;
var result = _root.Add(key, value, _keyComparer, _valueComparer, out mutated);
return this.Wrap(result, _count + 1);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[Pure]
public ImmutableSortedDictionary<TKey, TValue> SetItem(TKey key, TValue value)
{
Requires.NotNullAllowStructs(key, nameof(key));
bool replacedExistingValue, mutated;
var result = _root.SetItem(key, value, _keyComparer, _valueComparer, out replacedExistingValue, out mutated);
return this.Wrap(result, replacedExistingValue ? _count : _count + 1);
}
/// <summary>
/// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary.
/// </summary>
/// <param name="items">The key=value pairs to set on the map. Any keys that conflict with existing keys will overwrite the previous values.</param>
/// <returns>An immutable dictionary.</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
[Pure]
public ImmutableSortedDictionary<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
Requires.NotNull(items, nameof(items));
return this.AddRange(items, overwriteOnCollision: true, avoidToSortedMap: false);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
[Pure]
public ImmutableSortedDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
Requires.NotNull(items, nameof(items));
return this.AddRange(items, overwriteOnCollision: false, avoidToSortedMap: false);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[Pure]
public ImmutableSortedDictionary<TKey, TValue> Remove(TKey value)
{
Requires.NotNullAllowStructs(value, nameof(value));
bool mutated;
var result = _root.Remove(value, _keyComparer, out mutated);
return this.Wrap(result, _count - 1);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[Pure]
public ImmutableSortedDictionary<TKey, TValue> RemoveRange(IEnumerable<TKey> keys)
{
Requires.NotNull(keys, nameof(keys));
var result = _root;
int count = _count;
foreach (TKey key in keys)
{
bool mutated;
var newResult = result.Remove(key, _keyComparer, out mutated);
if (mutated)
{
result = newResult;
count--;
}
}
return this.Wrap(result, count);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[Pure]
public ImmutableSortedDictionary<TKey, TValue> WithComparers(IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
if (keyComparer == null)
{
keyComparer = Comparer<TKey>.Default;
}
if (valueComparer == null)
{
valueComparer = EqualityComparer<TValue>.Default;
}
if (keyComparer == _keyComparer)
{
if (valueComparer == _valueComparer)
{
return this;
}
else
{
// When the key comparer is the same but the value comparer is different, we don't need a whole new tree
// because the structure of the tree does not depend on the value comparer.
// We just need a new root node to store the new value comparer.
return new ImmutableSortedDictionary<TKey, TValue>(_root, _count, _keyComparer, valueComparer);
}
}
else
{
// A new key comparer means the whole tree structure could change. We must build a new one.
var result = new ImmutableSortedDictionary<TKey, TValue>(Node.EmptyNode, 0, keyComparer, valueComparer);
result = result.AddRange(this, overwriteOnCollision: false, avoidToSortedMap: true);
return result;
}
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[Pure]
public ImmutableSortedDictionary<TKey, TValue> WithComparers(IComparer<TKey> keyComparer)
{
return this.WithComparers(keyComparer, _valueComparer);
}
/// <summary>
/// Determines whether the <see cref="ImmutableSortedDictionary{TKey, TValue}"/>
/// contains an element with the specified value.
/// </summary>
/// <param name="value">
/// The value to locate in the <see cref="ImmutableSortedDictionary{TKey, TValue}"/>.
/// The value can be null for reference types.
/// </param>
/// <returns>
/// true if the <see cref="ImmutableSortedDictionary{TKey, TValue}"/> contains
/// an element with the specified value; otherwise, false.
/// </returns>
[Pure]
public bool ContainsValue(TValue value)
{
return _root.ContainsValue(value, _valueComparer);
}
#endregion
#region IImmutableDictionary<TKey, TValue> Methods
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
return this.Add(key, value);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItem(TKey key, TValue value)
{
return this.SetItem(key, value);
}
/// <summary>
/// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary.
/// </summary>
/// <param name="items">The key=value pairs to set on the map. Any keys that conflict with existing keys will overwrite the previous values.</param>
/// <returns>An immutable dictionary.</returns>
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
return this.SetItems(items);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
{
return this.AddRange(pairs);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.RemoveRange(IEnumerable<TKey> keys)
{
return this.RemoveRange(keys);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Remove(TKey key)
{
return this.Remove(key);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public bool ContainsKey(TKey key)
{
Requires.NotNullAllowStructs(key, nameof(key));
return _root.ContainsKey(key, _keyComparer);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public bool Contains(KeyValuePair<TKey, TValue> pair)
{
return _root.Contains(pair, _keyComparer, _valueComparer);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public bool TryGetValue(TKey key, out TValue value)
{
Requires.NotNullAllowStructs(key, nameof(key));
return _root.TryGetValue(key, _keyComparer, out value);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public bool TryGetKey(TKey equalKey, out TKey actualKey)
{
Requires.NotNullAllowStructs(equalKey, nameof(equalKey));
return _root.TryGetKey(equalKey, _keyComparer, out actualKey);
}
#endregion
#region IDictionary<TKey, TValue> Methods
/// <summary>
/// Adds an element with the provided key and value to the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="key">The object to use as the key of the element to add.</param>
/// <param name="value">The object to use as the value of the element to add.</param>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// An element with the same key already exists in the <see cref="IDictionary{TKey, TValue}"/>.
/// </exception>
/// <exception cref="NotSupportedException">
/// The <see cref="IDictionary{TKey, TValue}"/> is read-only.
/// </exception>
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
throw new NotSupportedException();
}
/// <summary>
/// Removes the element with the specified key from the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <returns>
/// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null.
/// </exception>
/// <exception cref="NotSupportedException">
/// The <see cref="IDictionary{TKey, TValue}"/> is read-only.
/// </exception>
bool IDictionary<TKey, TValue>.Remove(TKey key)
{
throw new NotSupportedException();
}
#endregion
#region ICollection<KeyValuePair<TKey, TValue>> Methods
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException();
}
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException();
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
Requires.NotNull(array, nameof(array));
Requires.Range(arrayIndex >= 0, nameof(arrayIndex));
Requires.Range(array.Length >= arrayIndex + this.Count, nameof(arrayIndex));
foreach (var item in this)
{
array[arrayIndex++] = item;
}
}
#endregion
#region IDictionary Properties
/// <summary>
/// Gets a value indicating whether the <see cref="IDictionary"/> object has a fixed size.
/// </summary>
/// <returns>true if the <see cref="IDictionary"/> object has a fixed size; otherwise, false.</returns>
bool IDictionary.IsFixedSize
{
get { return true; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only.
/// </summary>
/// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.
/// </returns>
bool IDictionary.IsReadOnly
{
get { return true; }
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>
/// An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
ICollection IDictionary.Keys
{
get { return new KeysCollectionAccessor<TKey, TValue>(this); }
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>
/// An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
ICollection IDictionary.Values
{
get { return new ValuesCollectionAccessor<TKey, TValue>(this); }
}
#endregion
#region IDictionary Methods
/// <summary>
/// Adds an element with the provided key and value to the <see cref="IDictionary"/> object.
/// </summary>
/// <param name="key">The <see cref="object"/> to use as the key of the element to add.</param>
/// <param name="value">The <see cref="object"/> to use as the value of the element to add.</param>
void IDictionary.Add(object key, object value)
{
throw new NotSupportedException();
}
/// <summary>
/// Determines whether the <see cref="IDictionary"/> object contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="IDictionary"/> object.</param>
/// <returns>
/// true if the <see cref="IDictionary"/> contains an element with the key; otherwise, false.
/// </returns>
bool IDictionary.Contains(object key)
{
return this.ContainsKey((TKey)key);
}
/// <summary>
/// Returns an <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object.
/// </summary>
/// <returns>
/// An <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object.
/// </returns>
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator());
}
/// <summary>
/// Removes the element with the specified key from the <see cref="IDictionary"/> object.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
void IDictionary.Remove(object key)
{
throw new NotSupportedException();
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
object IDictionary.this[object key]
{
get { return this[(TKey)key]; }
set { throw new NotSupportedException(); }
}
/// <summary>
/// Clears this instance.
/// </summary>
/// <exception cref="System.NotSupportedException"></exception>
void IDictionary.Clear()
{
throw new NotSupportedException();
}
#endregion
#region ICollection Methods
/// <summary>
/// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
void ICollection.CopyTo(Array array, int index)
{
_root.CopyTo(array, index, this.Count);
}
#endregion
#region ICollection Properties
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>.
/// </summary>
/// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get { return this; }
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe).
/// </summary>
/// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get
{
// This is immutable, so it is always thread-safe.
return true;
}
}
#endregion
#region IEnumerable<KeyValuePair<TKey, TValue>> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
[ExcludeFromCodeCoverage]
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return this.IsEmpty ?
Enumerable.Empty<KeyValuePair<TKey, TValue>>().GetEnumerator() :
this.GetEnumerator();
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
[ExcludeFromCodeCoverage]
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
public Enumerator GetEnumerator()
{
return _root.GetEnumerator();
}
/// <summary>
/// Creates a new sorted set wrapper for a node tree.
/// </summary>
/// <param name="root">The root of the collection.</param>
/// <param name="count">The number of elements in the map.</param>
/// <param name="keyComparer">The key comparer to use for the map.</param>
/// <param name="valueComparer">The value comparer to use for the map.</param>
/// <returns>The immutable sorted set instance.</returns>
[Pure]
private static ImmutableSortedDictionary<TKey, TValue> Wrap(Node root, int count, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
return root.IsEmpty
? Empty.WithComparers(keyComparer, valueComparer)
: new ImmutableSortedDictionary<TKey, TValue>(root, count, keyComparer, valueComparer);
}
/// <summary>
/// Attempts to discover an <see cref="ImmutableSortedDictionary{TKey, TValue}"/> instance beneath some enumerable sequence
/// if one exists.
/// </summary>
/// <param name="sequence">The sequence that may have come from an immutable map.</param>
/// <param name="other">Receives the concrete <see cref="ImmutableSortedDictionary{TKey, TValue}"/> typed value if one can be found.</param>
/// <returns><c>true</c> if the cast was successful; <c>false</c> otherwise.</returns>
private static bool TryCastToImmutableMap(IEnumerable<KeyValuePair<TKey, TValue>> sequence, out ImmutableSortedDictionary<TKey, TValue> other)
{
other = sequence as ImmutableSortedDictionary<TKey, TValue>;
if (other != null)
{
return true;
}
var builder = sequence as Builder;
if (builder != null)
{
other = builder.ToImmutable();
return true;
}
return false;
}
/// <summary>
/// Bulk adds entries to the map.
/// </summary>
/// <param name="items">The entries to add.</param>
/// <param name="overwriteOnCollision"><c>true</c> to allow the <paramref name="items"/> sequence to include duplicate keys and let the last one win; <c>false</c> to throw on collisions.</param>
/// <param name="avoidToSortedMap"><c>true</c> when being called from <see cref="WithComparers(IComparer{TKey}, IEqualityComparer{TValue})"/> to avoid <see cref="T:System.StackOverflowException"/>.</param>
[Pure]
private ImmutableSortedDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items, bool overwriteOnCollision, bool avoidToSortedMap)
{
Requires.NotNull(items, nameof(items));
// Some optimizations may apply if we're an empty set.
if (this.IsEmpty && !avoidToSortedMap)
{
return this.FillFromEmpty(items, overwriteOnCollision);
}
// Let's not implement in terms of ImmutableSortedMap.Add so that we're
// not unnecessarily generating a new wrapping map object for each item.
var result = _root;
var count = _count;
foreach (var item in items)
{
bool mutated;
bool replacedExistingValue = false;
var newResult = overwriteOnCollision
? result.SetItem(item.Key, item.Value, _keyComparer, _valueComparer, out replacedExistingValue, out mutated)
: result.Add(item.Key, item.Value, _keyComparer, _valueComparer, out mutated);
if (mutated)
{
result = newResult;
if (!replacedExistingValue)
{
count++;
}
}
}
return this.Wrap(result, count);
}
/// <summary>
/// Creates a wrapping collection type around a root node.
/// </summary>
/// <param name="root">The root node to wrap.</param>
/// <param name="adjustedCountIfDifferentRoot">The number of elements in the new tree, assuming it's different from the current tree.</param>
/// <returns>A wrapping collection type for the new tree.</returns>
[Pure]
private ImmutableSortedDictionary<TKey, TValue> Wrap(Node root, int adjustedCountIfDifferentRoot)
{
if (_root != root)
{
return root.IsEmpty ? this.Clear() : new ImmutableSortedDictionary<TKey, TValue>(root, adjustedCountIfDifferentRoot, _keyComparer, _valueComparer);
}
else
{
return this;
}
}
/// <summary>
/// Efficiently creates a new collection based on the contents of some sequence.
/// </summary>
[Pure]
private ImmutableSortedDictionary<TKey, TValue> FillFromEmpty(IEnumerable<KeyValuePair<TKey, TValue>> items, bool overwriteOnCollision)
{
Debug.Assert(this.IsEmpty);
Requires.NotNull(items, nameof(items));
// If the items being added actually come from an ImmutableSortedSet<T>,
// and the sort order is equivalent, then there is no value in reconstructing it.
ImmutableSortedDictionary<TKey, TValue> other;
if (TryCastToImmutableMap(items, out other))
{
return other.WithComparers(this.KeyComparer, this.ValueComparer);
}
var itemsAsDictionary = items as IDictionary<TKey, TValue>;
SortedDictionary<TKey, TValue> dictionary;
if (itemsAsDictionary != null)
{
dictionary = new SortedDictionary<TKey, TValue>(itemsAsDictionary, this.KeyComparer);
}
else
{
dictionary = new SortedDictionary<TKey, TValue>(this.KeyComparer);
foreach (var item in items)
{
if (overwriteOnCollision)
{
dictionary[item.Key] = item.Value;
}
else
{
TValue value;
if (dictionary.TryGetValue(item.Key, out value))
{
if (!_valueComparer.Equals(value, item.Value))
{
throw new ArgumentException(SR.Format(SR.DuplicateKey, item.Key));
}
}
else
{
dictionary.Add(item.Key, item.Value);
}
}
}
}
if (dictionary.Count == 0)
{
return this;
}
Node root = Node.NodeTreeFromSortedDictionary(dictionary);
return new ImmutableSortedDictionary<TKey, TValue>(root, dictionary.Count, this.KeyComparer, this.ValueComparer);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace pnp.api.contosoorders.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#pragma warning disable 1634 // Stops compiler from warning about unknown warnings (for Presharp)
using System.IO;
using System.Text;
using System.Xml;
using System.Security;
#if NET_NATIVE
namespace System.Runtime.Serialization.Json
{
// This wrapper does not support seek.
// Supports: UTF-8, Unicode, BigEndianUnicode
// ASSUMPTION (Microsoft): This class will only be used for EITHER reading OR writing. It can be done, it would just mean more buffers.
internal class JsonEncodingStreamWrapper : Stream
{
private static readonly UnicodeEncoding s_safeBEUTF16 = new UnicodeEncoding(true, false, false);
private static readonly UnicodeEncoding s_safeUTF16 = new UnicodeEncoding(false, false, false);
private static readonly UTF8Encoding s_safeUTF8 = new UTF8Encoding(false, false);
private static readonly UnicodeEncoding s_validatingBEUTF16 = new UnicodeEncoding(true, false, true);
private static readonly UnicodeEncoding s_validatingUTF16 = new UnicodeEncoding(false, false, true);
private static readonly UTF8Encoding s_validatingUTF8 = new UTF8Encoding(false, true);
private const int BufferLength = 128;
private byte[] _byteBuffer = new byte[1];
private int _byteCount;
private int _byteOffset;
private byte[] _bytes;
private char[] _chars;
private Decoder _dec;
private Encoder _enc;
private Encoding _encoding;
private SupportedEncoding _encodingCode;
private bool _isReading;
private Stream _stream;
public JsonEncodingStreamWrapper(Stream stream, Encoding encoding, bool isReader)
{
_isReading = isReader;
if (isReader)
{
InitForReading(stream, encoding);
}
else
{
if (encoding == null)
{
throw new ArgumentNullException("encoding");
}
InitForWriting(stream, encoding);
}
}
private enum SupportedEncoding
{
UTF8,
UTF16LE,
UTF16BE,
None
}
// This stream wrapper does not support duplex
public override bool CanRead
{
get
{
if (!_isReading)
{
return false;
}
return _stream.CanRead;
}
}
// The encoding conversion and buffering breaks seeking.
public override bool CanSeek
{
get { return false; }
}
// Delegate properties
public override bool CanTimeout
{
get { return _stream.CanTimeout; }
}
// This stream wrapper does not support duplex
public override bool CanWrite
{
get
{
if (_isReading)
{
return false;
}
return _stream.CanWrite;
}
}
public override long Length
{
get { return _stream.Length; }
}
// The encoding conversion and buffering breaks seeking.
public override long Position
{
get
{
#pragma warning suppress 56503 // The contract for non seekable stream is to throw exception
throw new NotSupportedException();
}
set { throw new NotSupportedException(); }
}
public override int ReadTimeout
{
get { return _stream.ReadTimeout; }
set { _stream.ReadTimeout = value; }
}
public override int WriteTimeout
{
get { return _stream.WriteTimeout; }
set { _stream.WriteTimeout = value; }
}
public static ArraySegment<byte> ProcessBuffer(byte[] buffer, int offset, int count, Encoding encoding)
{
try
{
SupportedEncoding expectedEnc = GetSupportedEncoding(encoding);
SupportedEncoding dataEnc;
if (count < 2)
{
dataEnc = SupportedEncoding.UTF8;
}
else
{
dataEnc = ReadEncoding(buffer[offset], buffer[offset + 1]);
}
if ((expectedEnc != SupportedEncoding.None) && (expectedEnc != dataEnc))
{
ThrowExpectedEncodingMismatch(expectedEnc, dataEnc);
}
// Fastpath: UTF-8
if (dataEnc == SupportedEncoding.UTF8)
{
return new ArraySegment<byte>(buffer, offset, count);
}
// Convert to UTF-8
return
new ArraySegment<byte>(s_validatingUTF8.GetBytes(GetEncoding(dataEnc).GetChars(buffer, offset, count)));
}
catch (DecoderFallbackException e)
{
throw new XmlException(SR.JsonInvalidBytes, e);
}
}
protected override void Dispose(bool disposing)
{
Flush();
_stream.Dispose();
base.Dispose(disposing);
}
public override void Flush()
{
_stream.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
try
{
if (_byteCount == 0)
{
if (_encodingCode == SupportedEncoding.UTF8)
{
return _stream.Read(buffer, offset, count);
}
// No more bytes than can be turned into characters
_byteOffset = 0;
_byteCount = _stream.Read(_bytes, _byteCount, (_chars.Length - 1) * 2);
// Check for end of stream
if (_byteCount == 0)
{
return 0;
}
// Fix up incomplete chars
CleanupCharBreak();
// Change encoding
int charCount = _encoding.GetChars(_bytes, 0, _byteCount, _chars, 0);
_byteCount = Encoding.UTF8.GetBytes(_chars, 0, charCount, _bytes, 0);
}
// Give them bytes
if (_byteCount < count)
{
count = _byteCount;
}
Buffer.BlockCopy(_bytes, _byteOffset, buffer, offset, count);
_byteOffset += count;
_byteCount -= count;
return count;
}
catch (DecoderFallbackException ex)
{
throw new XmlException(SR.JsonInvalidBytes, ex);
}
}
public override int ReadByte()
{
if (_byteCount == 0 && _encodingCode == SupportedEncoding.UTF8)
{
return _stream.ReadByte();
}
if (Read(_byteBuffer, 0, 1) == 0)
{
return -1;
}
return _byteBuffer[0];
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
// Delegate methods
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
// Optimize UTF-8 case
if (_encodingCode == SupportedEncoding.UTF8)
{
_stream.Write(buffer, offset, count);
return;
}
while (count > 0)
{
int size = _chars.Length < count ? _chars.Length : count;
int charCount = _dec.GetChars(buffer, offset, size, _chars, 0, false);
_byteCount = _enc.GetBytes(_chars, 0, charCount, _bytes, 0, false);
_stream.Write(_bytes, 0, _byteCount);
offset += size;
count -= size;
}
}
public override void WriteByte(byte b)
{
if (_encodingCode == SupportedEncoding.UTF8)
{
_stream.WriteByte(b);
return;
}
_byteBuffer[0] = b;
Write(_byteBuffer, 0, 1);
}
private static Encoding GetEncoding(SupportedEncoding e)
{
switch (e)
{
case SupportedEncoding.UTF8:
return s_validatingUTF8;
case SupportedEncoding.UTF16LE:
return s_validatingUTF16;
case SupportedEncoding.UTF16BE:
return s_validatingBEUTF16;
default:
throw new XmlException(SR.JsonEncodingNotSupported);
}
}
private static string GetEncodingName(SupportedEncoding enc)
{
switch (enc)
{
case SupportedEncoding.UTF8:
return "utf-8";
case SupportedEncoding.UTF16LE:
return "utf-16LE";
case SupportedEncoding.UTF16BE:
return "utf-16BE";
default:
throw new XmlException(SR.JsonEncodingNotSupported);
}
}
private static SupportedEncoding GetSupportedEncoding(Encoding encoding)
{
if (encoding == null)
{
return SupportedEncoding.None;
}
if (encoding.WebName == s_validatingUTF8.WebName)
{
return SupportedEncoding.UTF8;
}
else if (encoding.WebName == s_validatingUTF16.WebName)
{
return SupportedEncoding.UTF16LE;
}
else if (encoding.WebName == s_validatingBEUTF16.WebName)
{
return SupportedEncoding.UTF16BE;
}
else
{
throw new XmlException(SR.JsonEncodingNotSupported);
}
}
private static SupportedEncoding ReadEncoding(byte b1, byte b2)
{
if (b1 == 0x00 && b2 != 0x00)
{
return SupportedEncoding.UTF16BE;
}
else if (b1 != 0x00 && b2 == 0x00)
{
// 857 It's possible to misdetect UTF-32LE as UTF-16LE, but that's OK.
return SupportedEncoding.UTF16LE;
}
else if (b1 == 0x00 && b2 == 0x00)
{
// UTF-32BE not supported
throw new XmlException(SR.JsonInvalidBytes);
}
else
{
return SupportedEncoding.UTF8;
}
}
private static void ThrowExpectedEncodingMismatch(SupportedEncoding expEnc, SupportedEncoding actualEnc)
{
throw new XmlException(SR.Format(SR.JsonExpectedEncoding, GetEncodingName(expEnc), GetEncodingName(actualEnc)));
}
private void CleanupCharBreak()
{
int max = _byteOffset + _byteCount;
// Read on 2 byte boundaries
if ((_byteCount % 2) != 0)
{
int b = _stream.ReadByte();
if (b < 0)
{
throw new XmlException(SR.JsonUnexpectedEndOfFile);
}
_bytes[max++] = (byte)b;
_byteCount++;
}
// Don't cut off a surrogate character
int w;
if (_encodingCode == SupportedEncoding.UTF16LE)
{
w = _bytes[max - 2] + (_bytes[max - 1] << 8);
}
else
{
w = _bytes[max - 1] + (_bytes[max - 2] << 8);
}
if ((w & 0xDC00) != 0xDC00 && w >= 0xD800 && w <= 0xDBFF) // First 16-bit number of surrogate pair
{
int b1 = _stream.ReadByte();
int b2 = _stream.ReadByte();
if (b2 < 0)
{
throw new XmlException(SR.JsonUnexpectedEndOfFile);
}
_bytes[max++] = (byte)b1;
_bytes[max++] = (byte)b2;
_byteCount += 2;
}
}
private void EnsureBuffers()
{
EnsureByteBuffer();
if (_chars == null)
{
_chars = new char[BufferLength];
}
}
private void EnsureByteBuffer()
{
if (_bytes != null)
{
return;
}
_bytes = new byte[BufferLength * 4];
_byteOffset = 0;
_byteCount = 0;
}
private void FillBuffer(int count)
{
count -= _byteCount;
while (count > 0)
{
int read = _stream.Read(_bytes, _byteOffset + _byteCount, count);
if (read == 0)
{
break;
}
_byteCount += read;
count -= read;
}
}
private void InitForReading(Stream inputStream, Encoding expectedEncoding)
{
try
{
//this.stream = new BufferedStream(inputStream);
_stream = inputStream;
SupportedEncoding expectedEnc = GetSupportedEncoding(expectedEncoding);
SupportedEncoding dataEnc = ReadEncoding();
if ((expectedEnc != SupportedEncoding.None) && (expectedEnc != dataEnc))
{
ThrowExpectedEncodingMismatch(expectedEnc, dataEnc);
}
// Fastpath: UTF-8 (do nothing)
if (dataEnc != SupportedEncoding.UTF8)
{
// Convert to UTF-8
EnsureBuffers();
FillBuffer((BufferLength - 1) * 2);
_encodingCode = dataEnc;
_encoding = GetEncoding(dataEnc);
CleanupCharBreak();
int count = _encoding.GetChars(_bytes, _byteOffset, _byteCount, _chars, 0);
_byteOffset = 0;
_byteCount = s_validatingUTF8.GetBytes(_chars, 0, count, _bytes, 0);
}
}
catch (DecoderFallbackException ex)
{
throw new XmlException(SR.JsonInvalidBytes, ex);
}
}
private void InitForWriting(Stream outputStream, Encoding writeEncoding)
{
_encoding = writeEncoding;
//this.stream = new BufferedStream(outputStream);
_stream = outputStream;
// Set the encoding code
_encodingCode = GetSupportedEncoding(writeEncoding);
if (_encodingCode != SupportedEncoding.UTF8)
{
EnsureBuffers();
_dec = s_validatingUTF8.GetDecoder();
_enc = _encoding.GetEncoder();
}
}
private SupportedEncoding ReadEncoding()
{
int b1 = _stream.ReadByte();
int b2 = _stream.ReadByte();
EnsureByteBuffer();
SupportedEncoding e;
if (b1 == -1)
{
e = SupportedEncoding.UTF8;
_byteCount = 0;
}
else if (b2 == -1)
{
e = SupportedEncoding.UTF8;
_bytes[0] = (byte)b1;
_byteCount = 1;
}
else
{
e = ReadEncoding((byte)b1, (byte)b2);
_bytes[0] = (byte)b1;
_bytes[1] = (byte)b2;
_byteCount = 2;
}
return e;
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace System.ComponentModel
{
/// <summary>
/// <para>Converts the value of an object into a different data type.</para>
/// </summary>
public class TypeConverter
{
/// <summary>
/// <para>Gets a value indicating whether this converter can convert an object in the
/// given source type to the native type of the converter.</para>
/// </summary>
public bool CanConvertFrom(Type sourceType)
{
return CanConvertFrom(null, sourceType);
}
/// <summary>
/// <para>Gets a value indicating whether this converter can
/// convert an object in the given source type to the native type of the converter
/// using the context.</para>
/// </summary>
public virtual bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return false;
}
/// <summary>
/// <para>Gets a value indicating whether this converter can
/// convert an object to the given destination type using the context.</para>
/// </summary>
public bool CanConvertTo(Type destinationType)
{
return CanConvertTo(null, destinationType);
}
/// <summary>
/// <para>Gets a value indicating whether this converter can
/// convert an object to the given destination type using the context.</para>
/// </summary>
public virtual bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return (destinationType == typeof(string));
}
/// <summary>
/// <para>Converts the given value
/// to the converter's native type.</para>
/// </summary>
public object ConvertFrom(object value)
{
return ConvertFrom(null, CultureInfo.CurrentCulture, value);
}
/// <summary>
/// <para>Converts the given object to the converter's native type.</para>
/// </summary>
public virtual object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
throw GetConvertFromException(value);
}
/// <summary>
/// Converts the given string to the converter's native type using the invariant culture.
/// </summary>
public object ConvertFromInvariantString(string text)
{
return ConvertFromString(null, CultureInfo.InvariantCulture, text);
}
/// <summary>
/// Converts the given string to the converter's native type using the invariant culture.
/// </summary>
public object ConvertFromInvariantString(ITypeDescriptorContext context, string text)
{
return ConvertFromString(context, CultureInfo.InvariantCulture, text);
}
/// <summary>
/// <para>Converts the specified text into an object.</para>
/// </summary>
public object ConvertFromString(string text)
{
return ConvertFrom(null, null, text);
}
/// <summary>
/// <para>Converts the specified text into an object.</para>
/// </summary>
public object ConvertFromString(ITypeDescriptorContext context, string text)
{
return ConvertFrom(context, CultureInfo.CurrentCulture, text);
}
/// <summary>
/// <para>Converts the specified text into an object.</para>
/// </summary>
public object ConvertFromString(ITypeDescriptorContext context, CultureInfo culture, string text)
{
return ConvertFrom(context, culture, text);
}
/// <summary>
/// <para>Converts the given
/// value object to the specified destination type using the arguments.</para>
/// </summary>
public object ConvertTo(object value, Type destinationType)
{
return ConvertTo(null, null, value, destinationType);
}
/// <summary>
/// <para>Converts the given value object to
/// the specified destination type using the specified context and arguments.</para>
/// </summary>
public virtual object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == null)
{
throw new ArgumentNullException(nameof(destinationType));
}
if (destinationType == typeof(string))
{
if (value == null)
{
return string.Empty;
}
if (culture != null && culture != CultureInfo.CurrentCulture)
{
IFormattable formattable = value as IFormattable;
if (formattable != null)
{
return formattable.ToString(/* format = */ null, /* formatProvider = */ culture);
}
}
return value.ToString();
}
throw GetConvertToException(value, destinationType);
}
/// <summary>
/// <para>Converts the specified value to a culture-invariant string representation.</para>
/// </summary>
public string ConvertToInvariantString(object value)
{
return ConvertToString(null, CultureInfo.InvariantCulture, value);
}
/// <summary>
/// <para>Converts the specified value to a culture-invariant string representation.</para>
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
public string ConvertToInvariantString(ITypeDescriptorContext context, object value)
{
return ConvertToString(context, CultureInfo.InvariantCulture, value);
}
/// <summary>
/// <para>Converts the specified value to a string representation.</para>
/// </summary>
public string ConvertToString(object value)
{
return (string)ConvertTo(null, CultureInfo.CurrentCulture, value, typeof(string));
}
/// <summary>
/// <para>Converts the specified value to a string representation.</para>
/// </summary>
public string ConvertToString(ITypeDescriptorContext context, object value)
{
return (string)ConvertTo(context, CultureInfo.CurrentCulture, value, typeof(string));
}
/// <summary>
/// <para>Converts the specified value to a string representation.</para>
/// </summary>
public string ConvertToString(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return (string)ConvertTo(context, culture, value, typeof(string));
}
/// <summary>
/// <para>Re-creates an <see cref='System.Object'/> given a set of property values for the object.</para>
/// </summary>
public object CreateInstance(IDictionary propertyValues)
{
return CreateInstance(null, propertyValues);
}
/// <summary>
/// <para>Re-creates an <see cref='System.Object'/> given a set of property values for the object.</para>
/// </summary>
public virtual object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues)
{
return null;
}
/// <summary>
/// <para>Gets a suitable exception to throw when a conversion cannot be performed.</para>
/// </summary>
protected Exception GetConvertFromException(object value)
{
string valueTypeName;
valueTypeName = value == null ? SR.Null : value.GetType().FullName;
throw new NotSupportedException(SR.Format(SR.ConvertFromException, GetType().Name, valueTypeName));
}
/// <summary>
/// <para>Retrieves a suitable exception to throw when a conversion cannot
/// be performed.</para>
/// </summary>
protected Exception GetConvertToException(object value, Type destinationType)
{
string valueTypeName;
valueTypeName = value == null ? SR.Null : value.GetType().FullName;
throw new NotSupportedException(SR.Format(SR.ConvertToException, GetType().Name, valueTypeName, destinationType.FullName));
}
/// <summary>
/// <para>
/// Gets a value indicating whether changing a value on this object requires a call to
/// <see cref='System.ComponentModel.TypeConverter.CreateInstance'/> to create a new value.
/// </para>
/// </summary>
public bool GetCreateInstanceSupported()
{
return GetCreateInstanceSupported(null);
}
/// <summary>
/// <para>
/// Gets a value indicating whether changing a value on this object requires a call to
/// <see cref='System.ComponentModel.TypeConverter.CreateInstance'/> to create a new value,
/// using the specified context.
/// </para>
/// </summary>
public virtual bool GetCreateInstanceSupported(ITypeDescriptorContext context)
{
return false;
}
/// <summary>
/// <para>Gets a collection of properties for the type of array specified by the value parameter.</para>
/// </summary>
public PropertyDescriptorCollection GetProperties(object value)
{
return GetProperties(null, value);
}
/// <summary>
/// <para>
/// Gets a collection of properties for the type of array specified by the value parameter using
/// the specified context.
/// </para>
/// </summary>
public PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value)
{
return GetProperties(context, value, new Attribute[] { BrowsableAttribute.Yes });
}
/// <summary>
/// <para>
/// Gets a collection of properties for the type of array specified by the value parameter using
/// the specified context and attributes.
/// </para>
/// </summary>
public virtual PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
return null;
}
/// <summary>
/// <para>Gets a value indicating whether this object supports properties.</para>
/// </summary>
public bool GetPropertiesSupported()
{
return GetPropertiesSupported(null);
}
/// <summary>
/// <para>Gets a value indicating whether this object supports properties using the specified context.</para>
/// </summary>
public virtual bool GetPropertiesSupported(ITypeDescriptorContext context)
{
return false;
}
/// <summary>
/// <para>Gets a collection of standard values for the data type this type converter is designed for.</para>
/// </summary>
public ICollection GetStandardValues()
{
return GetStandardValues(null);
}
/// <summary>
/// <para>Gets a collection of standard values for the data type this type converter is designed for.</para>
/// </summary>
public virtual StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return null;
}
/// <summary>
/// <para>
/// Gets a value indicating whether the collection of standard values returned from
/// <see cref='System.ComponentModel.TypeConverter.GetStandardValues'/> is an exclusive list.
/// </para>
/// </summary>
public bool GetStandardValuesExclusive()
{
return GetStandardValuesExclusive(null);
}
/// <summary>
/// <para>
/// Gets a value indicating whether the collection of standard values returned from
/// <see cref='System.ComponentModel.TypeConverter.GetStandardValues'/> is an exclusive
/// list of possible values, using the specified context.
/// </para>
/// </summary>
public virtual bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false;
}
/// <summary>
/// <para>
/// Gets a value indicating whether this object supports a standard set of values
/// that can be picked from a list.
/// </para>
/// </summary>
public bool GetStandardValuesSupported()
{
return GetStandardValuesSupported(null);
}
/// <summary>
/// <para>
/// Gets a value indicating whether this object supports a standard set of values that can be picked
/// from a list using the specified context.
/// </para>
/// </summary>
public virtual bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return false;
}
/// <summary>
/// <para>Gets a value indicating whether the given value object is valid for this type.</para>
/// </summary>
public bool IsValid(object value)
{
return IsValid(null, value);
}
/// <summary>
/// <para>Gets a value indicating whether the given value object is valid for this type.</para>
/// </summary>
public virtual bool IsValid(ITypeDescriptorContext context, object value)
{
bool isValid = true;
try
{
// Because null doesn't have a type, so we couldn't pass this to CanConvertFrom.
// Meanwhile, we couldn't silence null value here, such as type converter like
// NullableConverter would consider null value as a valid value.
if (value == null || CanConvertFrom(context, value.GetType()))
{
ConvertFrom(context, CultureInfo.InvariantCulture, value);
}
else
{
isValid = false;
}
}
catch
{
isValid = false;
}
return isValid;
}
/// <summary>
/// <para>Sorts a collection of properties.</para>
/// </summary>
protected PropertyDescriptorCollection SortProperties(PropertyDescriptorCollection props, string[] names)
{
props.Sort(names);
return props;
}
/// <summary>
/// <para>
/// An <see langword='abstract '/> class that provides properties for objects that do not have properties.
/// </para>
/// </summary>
protected abstract class SimplePropertyDescriptor : PropertyDescriptor
{
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.ComponentModel.TypeConverter.SimplePropertyDescriptor'/> class.
/// </para>
/// </summary>
protected SimplePropertyDescriptor(Type componentType, string name, Type propertyType) : this(componentType, name, propertyType, Array.Empty<Attribute>())
{
}
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.ComponentModel.TypeConverter.SimplePropertyDescriptor'/> class.
/// </para>
/// </summary>
protected SimplePropertyDescriptor(Type componentType, string name, Type propertyType, Attribute[] attributes) : base(name, attributes)
{
ComponentType = componentType;
PropertyType = propertyType;
}
/// <summary>
/// <para>Gets the type of the component this property description is bound to.</para>
/// </summary>
public override Type ComponentType { get; }
/// <summary>
/// <para>Gets a value indicating whether this property is read-only.</para>
/// </summary>
public override bool IsReadOnly => Attributes.Contains(ReadOnlyAttribute.Yes);
/// <summary>
/// <para>Gets the type of the property.</para>
/// </summary>
public override Type PropertyType { get; }
/// <summary>
/// <para>
/// Gets a value indicating whether resetting the component will change the value of the component.
/// </para>
/// </summary>
public override bool CanResetValue(object component)
{
DefaultValueAttribute attr = (DefaultValueAttribute)Attributes[typeof(DefaultValueAttribute)];
if (attr == null)
{
return false;
}
return (attr.Value.Equals(GetValue(component)));
}
/// <summary>
/// <para>Resets the value for this property of the component.</para>
/// </summary>
public override void ResetValue(object component)
{
DefaultValueAttribute attr = (DefaultValueAttribute)Attributes[typeof(DefaultValueAttribute)];
if (attr != null)
{
SetValue(component, attr.Value);
}
}
/// <summary>
/// <para>Gets a value indicating whether the value of this property needs to be persisted.</para>
/// </summary>
public override bool ShouldSerializeValue(object component)
{
return false;
}
}
/// <summary>
/// <para>Represents a collection of values.</para>
/// </summary>
public class StandardValuesCollection : ICollection
{
private ICollection _values;
private Array _valueArray;
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.ComponentModel.TypeConverter.StandardValuesCollection'/> class.
/// </para>
/// </summary>
public StandardValuesCollection(ICollection values)
{
if (values == null)
{
values = Array.Empty<object>();
}
Array a = values as Array;
if (a != null)
{
_valueArray = a;
}
_values = values;
}
/// <summary>
/// <para>
/// Gets the number of objects in the collection.
/// </para>
/// </summary>
public int Count
{
get
{
if (_valueArray != null)
{
return _valueArray.Length;
}
else
{
return _values.Count;
}
}
}
/// <summary>
/// <para>Gets the object at the specified index number.</para>
/// </summary>
public object this[int index]
{
get
{
if (_valueArray != null)
{
return _valueArray.GetValue(index);
}
IList list = _values as IList;
if (list != null)
{
return list[index];
}
// No other choice but to enumerate the collection.
//
_valueArray = new object[_values.Count];
_values.CopyTo(_valueArray, 0);
return _valueArray.GetValue(index);
}
}
/// <summary>
/// <para>
/// Copies the contents of this collection to an array.
/// </para>
/// </summary>
public void CopyTo(Array array, int index)
{
_values.CopyTo(array, index);
}
/// <summary>
/// <para>
/// Gets an enumerator for this collection.
/// </para>
/// </summary>
public IEnumerator GetEnumerator()
{
return _values.GetEnumerator();
}
/// <internalonly/>
/// <summary>
/// Determines if this collection is synchronized. The ValidatorCollection is not synchronized for
/// speed. Also, since it is read-only, there is no need to synchronize it.
/// </summary>
bool ICollection.IsSynchronized => false;
/// <internalonly/>
/// <summary>
/// Retrieves the synchronization root for this collection. Because we are not synchronized,
/// this returns null.
/// </summary>
object ICollection.SyncRoot => null;
}
}
}
| |
// 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.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Tasks;
using Microsoft.Build.Utilities;
using Xunit;
namespace Microsoft.Build.UnitTests
{
sealed public class Touch_Tests
{
internal static Microsoft.Build.Shared.FileExists fileExists = new Microsoft.Build.Shared.FileExists(FileExists);
internal static Microsoft.Build.Shared.FileCreate fileCreate = new Microsoft.Build.Shared.FileCreate(FileCreate);
internal static Microsoft.Build.Tasks.GetAttributes fileGetAttributes = new Microsoft.Build.Tasks.GetAttributes(GetAttributes);
internal static Microsoft.Build.Tasks.SetAttributes fileSetAttributes = new Microsoft.Build.Tasks.SetAttributes(SetAttributes);
internal static Microsoft.Build.Tasks.SetLastAccessTime setLastAccessTime = new Microsoft.Build.Tasks.SetLastAccessTime(SetLastAccessTime);
internal static Microsoft.Build.Tasks.SetLastWriteTime setLastWriteTime = new Microsoft.Build.Tasks.SetLastWriteTime(SetLastWriteTime);
internal static string myexisting_txt = NativeMethodsShared.IsWindows ? @"c:\touch\myexisting.txt" : @"/touch/myexisting.txt";
internal static string mynonexisting_txt = NativeMethodsShared.IsWindows ? @"c:\touch\mynonexisting.txt" : @"/touch/mynonexisting.txt";
internal static string nonexisting_txt = NativeMethodsShared.IsWindows ? @"c:\touch-nonexistent\file.txt" : @"/touch-nonexistent/file.txt";
internal static string myreadonly_txt = NativeMethodsShared.IsWindows ? @"c:\touch\myreadonly.txt" : @"/touch/myreadonly.txt";
private bool Execute(Touch t)
{
return t.ExecuteImpl
(
fileExists,
fileCreate,
fileGetAttributes,
fileSetAttributes,
setLastAccessTime,
setLastWriteTime
);
}
/// <summary>
/// Mock file exists.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private static bool FileExists(string path)
{
if (path == myexisting_txt)
{
return true;
}
if (path == mynonexisting_txt)
{
return false;
}
if (path == nonexisting_txt)
{
return false;
}
if (path == myreadonly_txt)
{
return true;
}
Assert.True(false, "Unexpected file exists: " + path);
return true;
}
/// <summary>
/// Mock file create.
/// </summary>
/// <param name="path"></param>
private static FileStream FileCreate(string path)
{
if (path == mynonexisting_txt)
{
return null;
}
if (path == nonexisting_txt)
{
throw new DirectoryNotFoundException();
}
Assert.True(false, "Unexpected file create: " + path);
return null;
}
/// <summary>
/// Mock get attributes.
/// </summary>
/// <param name="path"></param>
private static FileAttributes GetAttributes(string path)
{
FileAttributes a = new FileAttributes();
if (path == myexisting_txt)
{
return a;
}
if (path == mynonexisting_txt)
{
// Has attributes because Touch created it.
return a;
}
if (path == myreadonly_txt)
{
return System.IO.FileAttributes.ReadOnly;
}
Assert.True(false, "Unexpected file attributes: " + path);
return a;
}
/// <summary>
/// Mock get attributes.
/// </summary>
/// <param name="path"></param>
private static void SetAttributes(string path, FileAttributes attributes)
{
if (path == myreadonly_txt)
{
return;
}
Assert.True(false, "Unexpected set file attributes: " + path);
}
/// <summary>
/// Mock SetLastAccessTime.
/// </summary>
/// <param name="path"></param>
private static void SetLastAccessTime(string path, DateTime timestamp)
{
if (path == myexisting_txt)
{
return;
}
if (path == mynonexisting_txt)
{
return;
}
if (path == myreadonly_txt)
{
// Read-only so throw an exception
throw new IOException();
}
Assert.True(false, "Unexpected set last access time: " + path);
}
/// <summary>
/// Mock SetLastWriteTime.
/// </summary>
/// <param name="path"></param>
private static void SetLastWriteTime(string path, DateTime timestamp)
{
if (path == myexisting_txt)
{
return;
}
if (path == mynonexisting_txt)
{
return;
}
if (path == myreadonly_txt)
{
return;
}
Assert.True(false, "Unexpected set last write time: " + path);
}
[Fact]
public void TouchExisting()
{
Touch t = new Touch();
MockEngine engine = new MockEngine();
t.BuildEngine = engine;
t.Files = new ITaskItem[]
{
new TaskItem(myexisting_txt)
};
bool success = Execute(t);
Assert.True(success);
Assert.Single(t.TouchedFiles);
Assert.Contains(
String.Format(AssemblyResources.GetString("Touch.Touching"), myexisting_txt),
engine.Log
);
}
[Fact]
public void TouchNonExisting()
{
Touch t = new Touch();
MockEngine engine = new MockEngine();
t.BuildEngine = engine;
t.Files = new ITaskItem[]
{
new TaskItem(mynonexisting_txt)
};
bool success = Execute(t);
// Not success because the file doesn't exist
Assert.False(success);
Assert.Contains(
String.Format(AssemblyResources.GetString("Touch.FileDoesNotExist"), mynonexisting_txt),
engine.Log
);
}
[Fact]
public void TouchNonExistingAlwaysCreate()
{
Touch t = new Touch();
MockEngine engine = new MockEngine();
t.BuildEngine = engine;
t.AlwaysCreate = true;
t.Files = new ITaskItem[]
{
new TaskItem(mynonexisting_txt)
};
bool success = Execute(t);
// Success because the file was created.
Assert.True(success);
Assert.Contains(
String.Format(AssemblyResources.GetString("Touch.CreatingFile"), mynonexisting_txt, "AlwaysCreate"),
engine.Log
);
}
[Fact]
public void TouchNonExistingAlwaysCreateAndBadlyFormedTimestamp()
{
Touch t = new Touch();
MockEngine engine = new MockEngine();
t.BuildEngine = engine;
t.AlwaysCreate = true;
t.ForceTouch = false;
t.Time = "Badly formed time String.";
t.Files = new ITaskItem[]
{
new TaskItem(mynonexisting_txt)
};
bool success = Execute(t);
// Failed because of badly formed time string.
Assert.False(success);
Assert.Contains("MSB3376", engine.Log);
}
[Fact]
public void TouchReadonly()
{
Touch t = new Touch();
MockEngine engine = new MockEngine();
t.BuildEngine = engine;
t.AlwaysCreate = true;
t.Files = new ITaskItem[]
{
new TaskItem(myreadonly_txt)
};
bool success = Execute(t);
// Failed because file is readonly.
Assert.False(success);
Assert.Contains("MSB3374", engine.Log);
Assert.Contains(myreadonly_txt, engine.Log);
}
[Fact]
public void TouchReadonlyForce()
{
Touch t = new Touch();
MockEngine engine = new MockEngine();
t.BuildEngine = engine;
t.ForceTouch = true;
t.AlwaysCreate = true;
t.Files = new ITaskItem[]
{
new TaskItem(myreadonly_txt)
};
Execute(t);
}
[Fact]
public void TouchNonExistingDirectoryDoesntExist()
{
Touch t = new Touch();
MockEngine engine = new MockEngine();
t.BuildEngine = engine;
t.AlwaysCreate = true;
t.Files = new ITaskItem[]
{
new TaskItem(nonexisting_txt)
};
bool success = Execute(t);
// Failed because the target directory didn't exist.
Assert.False(success);
Assert.Contains("MSB3371", engine.Log);
Assert.Contains(nonexisting_txt, engine.Log);
}
}
}
| |
//---------------------------------------------------------------------
// File: HostConductorStep.cs
//
// Summary:
//
//---------------------------------------------------------------------
// Copyright (c) 2004-2011, Kevin B. Smith. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
//---------------------------------------------------------------------
using BizUnit.Xaml;
namespace BizUnit.TestSteps.BizTalk.Host
{
using System;
using System.Management;
/// <summary>
/// The HostConductorStep test step maybe used to start or stop a BizTalk host
/// </summary>
///
/// <remarks>
/// The following shows an example of the Xml representation of this test step.
///
/// <code escaped="true">
/// <TestStep assemblyPath="" typeName="BizUnit.BizTalkSteps.HostConductorStep, BizUnit.BizTalkSteps, Version=3.1.0.0, Culture=neutral, PublicKeyToken=7eb7d82981ae5162">
/// <Action>start|stop</Action>
/// <HostInstanceName>BizTalkServerApplication</HostInstanceName>
/// <Server>RecvHost</Server>
/// <Logon>zeus\\administrator</Logon>
/// <PassWord>appollo*1</PassWord>
/// <GrantLogOnAsService>true</GrantLogOnAsService>
/// </TestStep>
/// </code>
///
/// <list type="table">
/// <listheader>
/// <term>Tag</term>
/// <description>Description</description>
/// </listheader>
/// <item>
/// <term>HostInstanceName</term>
/// <description>The name of the host instance to start|stop</description>
/// </item>
/// <item>
/// <term>Action</term>
/// <description>A value of start or stop<para>(start|stop)</para></description>
/// </item>
/// <item>
/// <term>Server</term>
/// <description>The server(s) where the Biztalk host instance is running, a commer delimeted list of servers may be supplied (optional)</description>
/// </item>
/// <item>
/// <term>Logon</term>
/// <description>String containing the logon information used by the host instance (optional - unless Server is supplied)</description>
/// </item>
/// <item>
/// <term>PassWord</term>
/// <description>String containing the password for the host (optional - unless Logon is supplied)</description>
/// </item>
/// <item>
/// <term>GrantLogOnAsService (optional - unless Logon is supplied)</term>
/// <description>Boolean determining whether the 'Log On As Service' privilege should be automatically granted to the specified logon user or not. This flag only has effect when the HostType property is set to In-process</description>
/// </item>
/// </list>
/// </remarks>
public class HostConductorStep : TestStepBase
{
private string _action;
private string _hostName;
private string _servers;
private string _logon;
private string _passWord;
private bool _grantLogOnAsService;
public string Action
{
get { return _action; }
set { _action = value; }
}
public string HostInstanceName
{
get { return _hostName; }
set { _hostName = value; }
}
public string Servers
{
get { return _servers; }
set { _servers = value; }
}
public string Logon
{
get { return _logon; }
set { _logon = value; }
}
public string PassWord
{
get { return _passWord; }
set { _passWord = value; }
}
public bool GrantLogOnAsService
{
get { return _grantLogOnAsService; }
set { _grantLogOnAsService = value; }
}
public override void Execute(Context context)
{
var listofServers = _servers.Split(',');
foreach (var server in listofServers)
{
var mo = GetHostInstanceWmiObject(server, _hostName);
using (mo)
{
if (_action.ToLower() == "start")
{
if (!string.IsNullOrEmpty(_logon))
{
var creds = new object[3];
creds[0] = _logon;
creds[1] = _passWord;
creds[2] = _grantLogOnAsService;
mo.InvokeMethod("Install", creds);
}
if (mo["ServiceState"].ToString() == "1")
{
mo.InvokeMethod("Start", null);
context.LogInfo("BizTalk Host Started.");
}
else
{
context.LogInfo("BizTalk Host is Started.");
}
}
if (_action.ToLower() == "stop")
{
if (mo["ServiceState"].ToString() != "0")
{
mo.InvokeMethod("Stop", null);
context.LogInfo("BizTalk Host Stopped.");
}
else
{
context.LogInfo("BizTalk Host is Stopped.");
}
}
}
}
}
public override void Validate(Context context)
{
if (string.IsNullOrEmpty(_action))
{
throw new ArgumentNullException("Action is either null or an empty string");
}
if (string.IsNullOrEmpty(_hostName))
{
throw new ArgumentNullException("HostName is either null or an empty string");
}
if (string.IsNullOrEmpty(_servers))
{
throw new ArgumentNullException("Servers is either null or an empty string");
}
if (null != _logon && 0 < _servers.Length)
{
if (string.IsNullOrEmpty(_passWord))
{
throw new ArgumentNullException("PassWord is either null or an empty string");
}
}
}
private static ManagementObject GetHostInstanceWmiObject(string server, string hostName)
{
// 2 represents an isolated host and 1 represents an in-process hosts, only an in-process
// can be stopped...
const int hostType = 1;
var options = new ConnectionOptions
{
Impersonation = ImpersonationLevel.Impersonate,
EnablePrivileges = true
};
var searcher = new ManagementObjectSearcher();
ManagementScope scope = null == server ? new ManagementScope("root\\MicrosoftBizTalkServer", options) : new ManagementScope("\\\\" + server + "\\root\\MicrosoftBizTalkServer", options);
searcher.Scope = scope;
// Build a Query to enumerate the MSBTS_hostInstance instances
var query = new SelectQuery
{
QueryString =
String.Format("SELECT * FROM MSBTS_HostInstance where HostName='" + hostName +
"' AND HostType=" + hostType.ToString())
};
// Set the query for the searcher.
searcher.Query = query;
// Execute the query and determine if any results were obtained.
var queryCol = searcher.Get();
var me = queryCol.GetEnumerator();
me.Reset();
if ( me.MoveNext() )
{
return (ManagementObject)me.Current;
}
throw new ApplicationException(string.Format("The WMI object for the Host Instance:{0} could not be retrieved.", hostName ));
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// SMS Retries Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class SPRETRYDataSet : EduHubDataSet<SPRETRY>
{
/// <inheritdoc />
public override string Name { get { return "SPRETRY"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal SPRETRYDataSet(EduHubContext Context)
: base(Context)
{
Index_CODE = new Lazy<Dictionary<int, IReadOnlyList<SPRETRY>>>(() => this.ToGroupedDictionary(i => i.CODE));
Index_TID = new Lazy<Dictionary<int, SPRETRY>>(() => this.ToDictionary(i => i.TID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="SPRETRY" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="SPRETRY" /> fields for each CSV column header</returns>
internal override Action<SPRETRY, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<SPRETRY, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "CODE":
mapper[i] = (e, v) => e.CODE = int.Parse(v);
break;
case "SPRECIP":
mapper[i] = (e, v) => e.SPRECIP = v == null ? (int?)null : int.Parse(v);
break;
case "RETRY":
mapper[i] = (e, v) => e.RETRY = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "STATUS_MESSAGE":
mapper[i] = (e, v) => e.STATUS_MESSAGE = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="SPRETRY" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="SPRETRY" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="SPRETRY" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{SPRETRY}"/> of entities</returns>
internal override IEnumerable<SPRETRY> ApplyDeltaEntities(IEnumerable<SPRETRY> Entities, List<SPRETRY> DeltaEntities)
{
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.CODE;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.CODE.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<int, IReadOnlyList<SPRETRY>>> Index_CODE;
private Lazy<Dictionary<int, SPRETRY>> Index_TID;
#endregion
#region Index Methods
/// <summary>
/// Find SPRETRY by CODE field
/// </summary>
/// <param name="CODE">CODE value used to find SPRETRY</param>
/// <returns>List of related SPRETRY entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SPRETRY> FindByCODE(int CODE)
{
return Index_CODE.Value[CODE];
}
/// <summary>
/// Attempt to find SPRETRY by CODE field
/// </summary>
/// <param name="CODE">CODE value used to find SPRETRY</param>
/// <param name="Value">List of related SPRETRY entities</param>
/// <returns>True if the list of related SPRETRY entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByCODE(int CODE, out IReadOnlyList<SPRETRY> Value)
{
return Index_CODE.Value.TryGetValue(CODE, out Value);
}
/// <summary>
/// Attempt to find SPRETRY by CODE field
/// </summary>
/// <param name="CODE">CODE value used to find SPRETRY</param>
/// <returns>List of related SPRETRY entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SPRETRY> TryFindByCODE(int CODE)
{
IReadOnlyList<SPRETRY> value;
if (Index_CODE.Value.TryGetValue(CODE, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find SPRETRY by TID field
/// </summary>
/// <param name="TID">TID value used to find SPRETRY</param>
/// <returns>Related SPRETRY entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SPRETRY FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find SPRETRY by TID field
/// </summary>
/// <param name="TID">TID value used to find SPRETRY</param>
/// <param name="Value">Related SPRETRY entity</param>
/// <returns>True if the related SPRETRY entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out SPRETRY Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find SPRETRY by TID field
/// </summary>
/// <param name="TID">TID value used to find SPRETRY</param>
/// <returns>Related SPRETRY entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SPRETRY TryFindByTID(int TID)
{
SPRETRY value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a SPRETRY table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SPRETRY]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[SPRETRY](
[TID] int IDENTITY NOT NULL,
[CODE] int NOT NULL,
[SPRECIP] int NULL,
[RETRY] datetime NULL,
[STATUS_MESSAGE] varchar(100) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [SPRETRY_Index_TID] PRIMARY KEY NONCLUSTERED (
[TID] ASC
)
);
CREATE CLUSTERED INDEX [SPRETRY_Index_CODE] ON [dbo].[SPRETRY]
(
[CODE] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SPRETRY]') AND name = N'SPRETRY_Index_TID')
ALTER INDEX [SPRETRY_Index_TID] ON [dbo].[SPRETRY] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SPRETRY]') AND name = N'SPRETRY_Index_TID')
ALTER INDEX [SPRETRY_Index_TID] ON [dbo].[SPRETRY] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SPRETRY"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="SPRETRY"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SPRETRY> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[SPRETRY] WHERE");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SPRETRY data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SPRETRY data set</returns>
public override EduHubDataSetDataReader<SPRETRY> GetDataSetDataReader()
{
return new SPRETRYDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SPRETRY data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SPRETRY data set</returns>
public override EduHubDataSetDataReader<SPRETRY> GetDataSetDataReader(List<SPRETRY> Entities)
{
return new SPRETRYDataReader(new EduHubDataSetLoadedReader<SPRETRY>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class SPRETRYDataReader : EduHubDataSetDataReader<SPRETRY>
{
public SPRETRYDataReader(IEduHubDataSetReader<SPRETRY> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 8; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // CODE
return Current.CODE;
case 2: // SPRECIP
return Current.SPRECIP;
case 3: // RETRY
return Current.RETRY;
case 4: // STATUS_MESSAGE
return Current.STATUS_MESSAGE;
case 5: // LW_DATE
return Current.LW_DATE;
case 6: // LW_TIME
return Current.LW_TIME;
case 7: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 2: // SPRECIP
return Current.SPRECIP == null;
case 3: // RETRY
return Current.RETRY == null;
case 4: // STATUS_MESSAGE
return Current.STATUS_MESSAGE == null;
case 5: // LW_DATE
return Current.LW_DATE == null;
case 6: // LW_TIME
return Current.LW_TIME == null;
case 7: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // CODE
return "CODE";
case 2: // SPRECIP
return "SPRECIP";
case 3: // RETRY
return "RETRY";
case 4: // STATUS_MESSAGE
return "STATUS_MESSAGE";
case 5: // LW_DATE
return "LW_DATE";
case 6: // LW_TIME
return "LW_TIME";
case 7: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "CODE":
return 1;
case "SPRECIP":
return 2;
case "RETRY":
return 3;
case "STATUS_MESSAGE":
return 4;
case "LW_DATE":
return 5;
case "LW_TIME":
return 6;
case "LW_USER":
return 7;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// Event type: Children's event.
/// </summary>
public class ChildrensEvent_Core : TypeCore, IEvent
{
public ChildrensEvent_Core()
{
this._TypeId = 58;
this._Id = "ChildrensEvent";
this._Schema_Org_Url = "http://schema.org/ChildrensEvent";
string label = "";
GetLabel(out label, "ChildrensEvent", typeof(ChildrensEvent_Core));
this._Label = label;
this._Ancestors = new int[]{266,98};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{98};
this._Properties = new int[]{67,108,143,229,19,71,82,130,151,158,214,216,218};
}
/// <summary>
/// A person attending the event.
/// </summary>
private Attendees_Core attendees;
public Attendees_Core Attendees
{
get
{
return attendees;
}
set
{
attendees = value;
SetPropertyInstance(attendees);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// The duration of the item (movie, audio recording, event, etc.) in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>.
/// </summary>
private Properties.Duration_Core duration;
public Properties.Duration_Core Duration
{
get
{
return duration;
}
set
{
duration = value;
SetPropertyInstance(duration);
}
}
/// <summary>
/// The end date and time of the event (in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>).
/// </summary>
private EndDate_Core endDate;
public EndDate_Core EndDate
{
get
{
return endDate;
}
set
{
endDate = value;
SetPropertyInstance(endDate);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event.
/// </summary>
private Offers_Core offers;
public Offers_Core Offers
{
get
{
return offers;
}
set
{
offers = value;
SetPropertyInstance(offers);
}
}
/// <summary>
/// The main performer or performers of the event\u2014for example, a presenter, musician, or actor.
/// </summary>
private Performers_Core performers;
public Performers_Core Performers
{
get
{
return performers;
}
set
{
performers = value;
SetPropertyInstance(performers);
}
}
/// <summary>
/// The start date and time of the event (in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>).
/// </summary>
private StartDate_Core startDate;
public StartDate_Core StartDate
{
get
{
return startDate;
}
set
{
startDate = value;
SetPropertyInstance(startDate);
}
}
/// <summary>
/// Events that are a part of this event. For example, a conference event includes many presentations, each are subEvents of the conference.
/// </summary>
private SubEvents_Core subEvents;
public SubEvents_Core SubEvents
{
get
{
return subEvents;
}
set
{
subEvents = value;
SetPropertyInstance(subEvents);
}
}
/// <summary>
/// An event that this event is a part of. For example, a collection of individual music performances might each have a music festival as their superEvent.
/// </summary>
private SuperEvent_Core superEvent;
public SuperEvent_Core SuperEvent
{
get
{
return superEvent;
}
set
{
superEvent = value;
SetPropertyInstance(superEvent);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Text;
using DNXServer.Action;
using System.Data;
using System.Reflection;
using System.Collections.Specialized;
namespace DNXServer.Net
{
public class DNXSocket
{
protected Socket mainSock;
public DNXSocket ()
{
Log.Info ("Loading Skill Data");
new SkillManager ().Initialize();
Log.Info ("Loading Sudden Death Data");
new SuddenDeathManager ().Initialize();
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 3697);
Log.Info("Create new socket");
mainSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
Log.Info("Bind the socket");
mainSock.Bind(endPoint);
Log.Info("Listening to socket");
mainSock.Listen(10);
Log.Info("Waiting for connection");
mainSock.BeginAccept(new AsyncCallback(AcceptConnection), null);
}
public Socket MainSock
{
set
{
mainSock = value;
}
get
{
return mainSock;
}
}
protected void ProcessData(int x, string processedString, SessionData so)
{
if(x < SessionData.BYTE_SIZE)
{
processedString = processedString.Trim();
if(processedString == "")
return;
string bufferData = "";
DNXMessage message = new DNXMessage(processedString);
CommandEnum command = (CommandEnum) Convert.ToInt32(message.GetValue(0));
// check server condition every time user send a request
string server = new ServerStatus().StatsCheck();
var split = server.Split ('~');
string status_desc = split[0];
bool isOffline = Convert.ToBoolean (split[1]);
if(isOffline == false)
{
switch(command)
{
case CommandEnum.SendBattleData:
bufferData = new BattleAction().LocalBattleResult(so, message[1].GetValue(0), message[1].GetValue(1), message[1].GetValue(2), message[1].GetValue(3));
break;
case CommandEnum.SendUserData:
bufferData = new LoginAction().Login(so, message[1].GetValue(0), message[1].GetValue(1), message[1].GetValue(2), message[1].GetValue(3));
break;
case CommandEnum.PettingAction:
bufferData = new PettingAction().PettingResult(so, message[1].GetValue(0), message[1].GetValue(1));
break;
case CommandEnum.DropPettingStat:
bufferData = new DropPettingAction().DropMonsterStat(so, message[1].GetValue(0));
break;
case CommandEnum.UpdateMonsterEquipment:
bufferData = new UpdateMonsterEquipment ().UpdateMonster (so, message [1].GetValue (0), message [1].GetValue (1), message [1].GetValue (2), message [1].GetValue (3), message [1].GetValue (4), message [1].GetValue (5), message [1].GetValue (6));
break;
case CommandEnum.RetrieveMonsterInventory:
bufferData = new InventoryAction().GetInventory(so, message [1].GetValue(0));
break;
case CommandEnum.RegisterCard:
bufferData = new CardAction().RegisterCard(so, message [1].GetValue(0));
break;
case CommandEnum.UnregisterCard:
bufferData = new CardAction().UnregisterCard(so, message [1].GetValue(0));
break;
case CommandEnum.UpgradeMonster:
bufferData = new CardAction().RegisterUpgradeCard(so, message [1].GetValue(0), message [1].GetValue(1));
break;
case CommandEnum.RetrieveUserCards:
bufferData = new CardAction().GetUserMonsterCards(so);
break;
case CommandEnum.Logout:
new LoginAction ().Logout (so);
DeleteThisSessionFromList (so);
break;
case CommandEnum.CreateRoom:
bufferData = new BattleAction ().CreateRoom (so, message [1].GetValue(0));
break;
case CommandEnum.RoomList:
bufferData = new BattleAction ().GetRoomList ();
break;
case CommandEnum.JoinRoom:
bufferData = new BattleAction ().JoinRoom (so, message [1].GetValue(0), message [1].GetValue(1));
break;
case CommandEnum.SetBattleItem:
bufferData = new BattleAction ().SetPlayerItems (so, message [1].GetValue(0),message [1].GetValue(1),message [1].GetValue(2));
break;
case CommandEnum.BattleReady:
if(message [1].GetValue(0)=="1")
{
bufferData = new BattleAction ().SetPlayerReady (so);
}
else if(message [1].GetValue(0)=="0")
{
bufferData = new BattleAction ().UnsetPlayerReady (so);
}
break;
case CommandEnum.StartOnlineBattle:
bufferData = new BattleAction ().StartOnlineBattle (so);
break;
case CommandEnum.BattleAction:
bufferData = new BattleAction ().OnlineBattleAction(so, message [1].GetValue(0),message [1].GetValue(1));
break;
case CommandEnum.SuddenDeath:
bufferData = new BattleAction ().SuddenDeath (so);
break;
case CommandEnum.VerifyPurchase:
bufferData = new PurchaseAction ().GooglePurchase (so, message [1].GetValue (0), message [1].GetValue (1));
break;
case CommandEnum.RetrieveShopItems:
bufferData = new ShopAction ().RetrieveShopItems (so);
break;
case CommandEnum.BuyShopItem:
bufferData = new ShopAction ().BuyCardPacks (so, message [1].GetValue (0));
break;
case CommandEnum.KickOpponent:
bufferData = new BattleAction ().KickGuest (so);
break;
case CommandEnum.FinishBattle:
bufferData = new BattleAction ().OnlineBattleResult (so);
break;
case CommandEnum.BuyBattleSlot:
bufferData = new ShopAction ().BuyBattleItemSlot (so);
break;
case CommandEnum.QuitRoom:
bufferData = new BattleAction ().QuitRoom (so);
break;
case CommandEnum.None:
break;
}
}
else
{
bufferData = (int)CommandResponseEnum.Maintenance + "`" + status_desc + "`";
}
if(bufferData != "" || bufferData != string.Empty)
{
SendData(so, bufferData);
}
}
}
protected void SendData(SessionData so, string sendData)
{
try
{
List<byte> temp = new List<byte> ();
temp.AddRange (Encoding.ASCII.GetBytes (sendData));
temp.Add (0x03);
byte[] data = temp.ToArray();
so.WriteLine(sendData);
//Log.Info(sendData);
so.Sock.Send(data);
}
catch(Exception e)
{
StringBuilder str = new StringBuilder();
str.AppendLine("\n----------------------------------\n\nUnable to send message to client because error occured at " + DateTime.Now);
str.AppendLine("Message: " + e.Message);
str.AppendLine("Source: " + e.Source);
str.AppendLine("Stack Trace:");
str.AppendLine(e.StackTrace);
Log.Error(str.ToString());
}
}
protected int i = 0;
protected void AcceptConnection(IAsyncResult ar)
{
Socket acc = mainSock.EndAccept(ar);
SessionData so = new SessionData(acc);
try
{
i++;
so.WriteLine("Connection accepted, waiting for data");
Log.Info("Waiting for new connection");
mainSock.BeginAccept(new AsyncCallback(AcceptConnection), null);
try
{
so.Sock.BeginReceive(so.data, 0, SessionData.BYTE_SIZE, SocketFlags.None, new AsyncCallback(ReceiveData), so);
}
catch(Exception e)
{
so.Sock.Send (ASCIIEncoding.Default.GetBytes(e.Message));
so.WriteLine(e.Message);
}
}
catch(Exception e)
{
Log.Info (e.Message);
Log.Info (e.StackTrace);
}
}
protected void ReceiveData(IAsyncResult ar)
{
SessionData localSo = (SessionData)ar.AsyncState;
StringBuilder strbuild = new StringBuilder();
try
{
int x = localSo.Sock.EndReceive(ar);
localSo.WriteLine("Receive data");
if(x > 0)
{
localSo.WriteLine(String.Format("Data size: {0}", x));
/*
StringBuilder sb = new StringBuilder();
foreach(byte b in localSo.data)
{
sb.Append(b.ToString("X2") + " ");
}
Console.WriteLine("PRE DECRYPTED:" + sb.ToString());
MemoryStream ms = new MemoryStream(localSo.data);
RijndaelManaged RMCrypto = new RijndaelManaged();
RMCrypto.Padding = PaddingMode.Zeros;
byte[] Key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
byte[] IV = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
CryptoStream CryptStream = new CryptoStream(ms,RMCrypto.CreateDecryptor(Key, IV),CryptoStreamMode.Read);
List<byte> decryptedBytes = new List<byte>();
int decryptedByte = 0;
while(decryptedByte != -1)
{
decryptedByte = CryptStream.ReadByte();
//if ((byte)decryptedByte
decryptedBytes.Add((byte)decryptedByte);
}
//Console.WriteLine("DECRYPTED MESSAGE:" + Encoding.ASCII.GetString(decryptedBytes.ToArray()));
//Read the stream.
//StreamReader SReader = new StreamReader(CryptStream);
//Console.WriteLine("Decrypted:" + SReader.ReadToEnd());
//Close the streams.
//SReader.Close();
ms.Close();
localSo.data = decryptedBytes.ToArray();
*/
if(DNXConfig.ShowInput)
{
localSo.WriteLine(String.Format("Raw data: {0}", Encoding.ASCII.GetString(localSo.data).Trim ('\0')));
}
string chunk = Encoding.ASCII.GetString(localSo.data).Trim ('\0');
localSo.WriteLine("Data received: " + chunk);
strbuild.Append(chunk);
localSo.str.Append(chunk);
for(int ii=0; ii<SessionData.BYTE_SIZE; ii++)
{
localSo.data[ii] = 0;
}
ProcessData(x, strbuild.ToString(), localSo);
localSo.Sock.BeginReceive(localSo.data, 0, SessionData.BYTE_SIZE, SocketFlags.None, new AsyncCallback(ReceiveData), localSo);
}
else
{
Log.Info("Connection Closed");
DeleteThisSessionFromList(localSo);
}
}
catch(Exception e)
{
int i = 0;
if (File.Exists ("ERROR_ID")) {
try {
i = Convert.ToInt32 (File.ReadAllText ("ERROR_ID")) + 1;
} catch {
}
}
StringBuilder str = new StringBuilder();
str.AppendLine("ERROR_ID=" + i);
str.AppendLine("\n----------------------------------\n\nDisconnecting client because error occured at " + DateTime.Now);
str.AppendLine("Message: " + e.Message);
str.AppendLine("Source: " + e.Source);
str.AppendLine("Stack Trace:");
str.AppendLine(e.StackTrace);
str.AppendLine("Input data: " + strbuild.ToString());
Log.Error(str.ToString());
File.WriteAllText ("ERROR_ID", i.ToString());
if(!System.IO.Directory.Exists("Logs"))
{
System.IO.Directory.CreateDirectory("Logs");
}
DateTime now = DateTime.Now;
File.AppendAllText("Logs/error_" + now.Year + now.Month.ToString("00") + now.Day.ToString("00"), str.ToString());
// send error response to client
string error = Convert.ToString((int)CommandResponseEnum.Error) + "`" + i + "~Sorry we encounter a problem processing your data. If the problem persists, do not hesitate to contact us.`";
List<byte> temp = new List<byte> ();
temp.AddRange (Encoding.ASCII.GetBytes (error));
temp.Add (0x03);
byte[] data = temp.ToArray();
try
{
localSo.Sock.Send (data);
}
catch(Exception)
{
Log.Info("Could not send Error ID, Connection to client already closed");
}
// remove user from user list if error occur
DeleteThisSessionFromList (localSo);
//localSo.Sock.BeginReceive(localSo.data, 0, SessionData.BYTE_SIZE, SocketFlags.None, new AsyncCallback(ReceiveData), localSo);
}
}
protected void DeleteThisSessionFromList(SessionData so)
{
foreach (SessionData ses in LoginAction.ListUser)
{
if (ses == so)
{
foreach(RoomData room in BattleAction.ListRoom)
{
if(ses == room.RoomMaster)
{
if(room.RoomGuest != null)
{
string report = (int)CommandResponseEnum.QuitRoomResult + "`" + "1" + "~" + "Room master has left the room" + "`";
room.SendToRoomGuest(report);
room.RoomGuest.IsRoomGuest = false;
room.RoomGuest.RoomId = 0;
room.RoomGuest.InBattle = false;
room.RoomGuest = null;
}
BattleAction.ListRoom.Remove(room);
break;
}
else if ( ses == room.RoomGuest )
{
if(room.RoomMaster != null)
{
string report = (int)CommandResponseEnum.QuitRoomResult + "`" + "2" + "~" + "Room guest has left the room" + "`";
room.SendToRoomMaster(report);
}
room.RoomGuest = null;
if(room.RoomMaster == null)
{
BattleAction.ListRoom.Remove(room);
}
break;
}
}
LoginAction.ListUser.Remove(so);
break;
}
}
}
// protected void PushMessage(object so)
// {
// SessionData newSo = (SessionData)so;
//
// int i = 0;
// try
// {
// for(;;)
// {
// i++;
//
// if(newSo.Sock.Connected)
// {
// newSo.WriteLine("Push #" + i.ToString());
// newSo.Sock.Send(System.Text.Encoding.ASCII.GetBytes("[\"MSG~\", \"Push " + i.ToString() + "\"]\n\0"));
// System.Threading.Thread.Sleep(1000);
// }
// else
// {
// break;
// }
// }
// }
// catch(SocketException)
// {
// newSo.WriteLine("Exception... Closing.");
// }
// finally
// {
// newSo.WriteLine("Disconnected. Push aborted");
// System.Threading.Thread.CurrentThread.Abort();
// }
// }
}
}
| |
//
// Copyright (c) 2004-2020 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.
//
namespace NLog.Targets.Wrappers
{
using System;
using System.Collections.Generic;
using NLog.Common;
using NLog.Conditions;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// Filters buffered log entries based on a set of conditions that are evaluated on a group of events.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/PostFilteringWrapper-target">Documentation on NLog Wiki</seealso>
/// <remarks>
/// PostFilteringWrapper must be used with some type of buffering target or wrapper, such as
/// AsyncTargetWrapper, BufferingWrapper or ASPNetBufferingWrapper.
/// </remarks>
/// <example>
/// <p>
/// This example works like this. If there are no Warn,Error or Fatal messages in the buffer
/// only Info messages are written to the file, but if there are any warnings or errors,
/// the output includes detailed trace (levels >= Debug). You can plug in a different type
/// of buffering wrapper (such as ASPNetBufferingWrapper) to achieve different
/// functionality.
/// </p>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/PostFilteringWrapper/NLog.config" />
/// <p>
/// The above examples assume just one target and a single rule. See below for
/// a programmatic configuration that's equivalent to the above config file:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/PostFilteringWrapper/Simple/Example.cs" />
/// </example>
[Target("PostFilteringWrapper", IsWrapper = true)]
public class PostFilteringTargetWrapper : WrapperTargetBase
{
private static object boxedTrue = true;
/// <summary>
/// Initializes a new instance of the <see cref="PostFilteringTargetWrapper" /> class.
/// </summary>
public PostFilteringTargetWrapper()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PostFilteringTargetWrapper" /> class.
/// </summary>
public PostFilteringTargetWrapper(Target wrappedTarget)
: this(null, wrappedTarget)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PostFilteringTargetWrapper" /> class.
/// </summary>
/// <param name="name">Name of the target.</param>
/// <param name="wrappedTarget">The wrapped target.</param>
public PostFilteringTargetWrapper(string name, Target wrappedTarget)
{
Name = name;
WrappedTarget = wrappedTarget;
Rules = new List<FilteringRule>();
}
/// <summary>
/// Gets or sets the default filter to be applied when no specific rule matches.
/// </summary>
/// <docgen category='Filtering Options' order='10' />
public ConditionExpression DefaultFilter { get; set; }
/// <summary>
/// Gets the collection of filtering rules. The rules are processed top-down
/// and the first rule that matches determines the filtering condition to
/// be applied to log events.
/// </summary>
/// <docgen category='Filtering Rules' order='10' />
[ArrayParameter(typeof(FilteringRule), "when")]
public IList<FilteringRule> Rules { get; private set; }
/// <inheritdoc/>
protected override void InitializeTarget()
{
base.InitializeTarget();
if (!OptimizeBufferReuse && WrappedTarget != null && WrappedTarget.OptimizeBufferReuse)
{
OptimizeBufferReuse = GetType() == typeof(PostFilteringTargetWrapper); // Class not sealed, reduce breaking changes
}
}
/// <inheritdoc/>
protected override void Write(AsyncLogEventInfo logEvent)
{
Write((IList<AsyncLogEventInfo>)new[] { logEvent }); // Single LogEvent should also work
}
/// <summary>
/// NOTE! Obsolete, instead override Write(IList{AsyncLogEventInfo} logEvents)
///
/// Writes an array of logging events to the log target. By default it iterates on all
/// events and passes them to "Write" method. Inheriting classes can use this method to
/// optimize batch writes.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
[Obsolete("Instead override Write(IList<AsyncLogEventInfo> logEvents. Marked obsolete on NLog 4.5")]
protected override void Write(AsyncLogEventInfo[] logEvents)
{
Write((IList<AsyncLogEventInfo>)logEvents);
}
/// <summary>
/// Evaluates all filtering rules to find the first one that matches.
/// The matching rule determines the filtering condition to be applied
/// to all items in a buffer. If no condition matches, default filter
/// is applied to the array of log events.
/// </summary>
/// <param name="logEvents">Array of log events to be post-filtered.</param>
protected override void Write(IList<AsyncLogEventInfo> logEvents)
{
InternalLogger.Trace("PostFilteringWrapper(Name={0}): Running on {1} events", Name, logEvents.Count);
var resultFilter = EvaluateAllRules(logEvents) ?? DefaultFilter;
if (resultFilter == null)
{
WrappedTarget.WriteAsyncLogEvents(logEvents);
}
else
{
InternalLogger.Trace("PostFilteringWrapper(Name={0}): Filter to apply: {1}", Name, resultFilter);
var resultBuffer = logEvents.Filter(resultFilter, ApplyFilter);
InternalLogger.Trace("PostFilteringWrapper(Name={0}): After filtering: {1} events.", Name, resultBuffer.Count);
if (resultBuffer.Count > 0)
{
InternalLogger.Trace("PostFilteringWrapper(Name={0}): Sending to {1}", Name, WrappedTarget);
WrappedTarget.WriteAsyncLogEvents(resultBuffer);
}
}
}
private static bool ApplyFilter(AsyncLogEventInfo logEvent, ConditionExpression resultFilter)
{
object v = resultFilter.Evaluate(logEvent.LogEvent);
if (boxedTrue.Equals(v))
{
return true;
}
else
{
logEvent.Continuation(null);
return false;
}
}
/// <summary>
/// Evaluate all the rules to get the filtering condition
/// </summary>
/// <param name="logEvents"></param>
/// <returns></returns>
private ConditionExpression EvaluateAllRules(IList<AsyncLogEventInfo> logEvents)
{
if (Rules.Count == 0)
return null;
for (int i = 0; i < logEvents.Count; ++i)
{
for (int j = 0; j < Rules.Count; ++j)
{
var rule = Rules[j];
object v = rule.Exists.Evaluate(logEvents[i].LogEvent);
if (boxedTrue.Equals(v))
{
InternalLogger.Trace("PostFilteringWrapper(Name={0}): Rule matched: {1}", Name, rule.Exists);
return rule.Filter;
}
}
}
return null;
}
}
}
| |
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 Job : ModelBase<Job>, IEquatable<Job>, ITrackable
{
public Job()
{
this.Applications = new ChangeTrackingCollection<Application>();
this.Employees = new ChangeTrackingCollection<Employee>();
this.OpenJobs = new ChangeTrackingCollection<OpenJob>();
}
[DataMember]
public int JobId
{
get { return _JobId; }
set
{
if (Equals(value, _JobId)) return;
_JobId = value;
NotifyPropertyChanged(m => m.JobId);
}
}
private int _JobId;
[DataMember]
public string Position
{
get { return _Position; }
set
{
if (Equals(value, _Position)) return;
_Position = value;
NotifyPropertyChanged(m => m.Position);
}
}
private string _Position;
[DataMember]
public string Description
{
get { return _Description; }
set
{
if (Equals(value, _Description)) return;
_Description = value;
NotifyPropertyChanged(m => m.Description);
}
}
private string _Description;
[DataMember]
public string FullPartTime
{
get { return _FullPartTime; }
set
{
if (Equals(value, _FullPartTime)) return;
_FullPartTime = value;
NotifyPropertyChanged(m => m.FullPartTime);
}
}
private string _FullPartTime;
[DataMember]
public string SalaryRange
{
get { return _SalaryRange; }
set
{
if (Equals(value, _SalaryRange)) return;
_SalaryRange = value;
NotifyPropertyChanged(m => m.SalaryRange);
}
}
private string _SalaryRange;
[DataMember]
public int? QuestionnaireId
{
get { return _QuestionnaireId; }
set
{
if (Equals(value, _QuestionnaireId)) return;
_QuestionnaireId = value;
NotifyPropertyChanged(m => m.QuestionnaireId);
}
}
private int? _QuestionnaireId;
[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? InterviewQuestionId
{
get { return _InterviewQuestionId; }
set
{
if (Equals(value, _InterviewQuestionId)) return;
_InterviewQuestionId = value;
NotifyPropertyChanged(m => m.InterviewQuestionId);
}
}
private int? _InterviewQuestionId;
[DataMember]
public ChangeTrackingCollection<Application> Applications
{
get { return _Applications; }
set
{
if (Equals(value, _Applications)) return;
_Applications = value;
NotifyPropertyChanged(m => m.Applications);
}
}
private ChangeTrackingCollection<Application> _Applications;
[DataMember]
public ChangeTrackingCollection<Employee> Employees
{
get { return _Employees; }
set
{
if (Equals(value, _Employees)) return;
_Employees = value;
NotifyPropertyChanged(m => m.Employees);
}
}
private ChangeTrackingCollection<Employee> _Employees;
[DataMember]
public Hour Hour
{
get { return _Hour; }
set
{
if (Equals(value, _Hour)) return;
_Hour = value;
HourChangeTracker = _Hour == null ? null
: new ChangeTrackingCollection<Hour> { _Hour };
NotifyPropertyChanged(m => m.Hour);
}
}
private Hour _Hour;
private ChangeTrackingCollection<Hour> HourChangeTracker { get; set; }
[DataMember]
public InterviewQuestion InterviewQuestion
{
get { return _InterviewQuestion; }
set
{
if (Equals(value, _InterviewQuestion)) return;
_InterviewQuestion = value;
InterviewQuestionChangeTracker = _InterviewQuestion == null ? null
: new ChangeTrackingCollection<InterviewQuestion> { _InterviewQuestion };
NotifyPropertyChanged(m => m.InterviewQuestion);
}
}
private InterviewQuestion _InterviewQuestion;
private ChangeTrackingCollection<InterviewQuestion> InterviewQuestionChangeTracker { get; set; }
[DataMember]
public Questionnaire Questionnaire
{
get { return _Questionnaire; }
set
{
if (Equals(value, _Questionnaire)) return;
_Questionnaire = value;
QuestionnaireChangeTracker = _Questionnaire == null ? null
: new ChangeTrackingCollection<Questionnaire> { _Questionnaire };
NotifyPropertyChanged(m => m.Questionnaire);
}
}
private Questionnaire _Questionnaire;
private ChangeTrackingCollection<Questionnaire> QuestionnaireChangeTracker { get; set; }
[DataMember]
public ChangeTrackingCollection<OpenJob> OpenJobs
{
get { return _OpenJobs; }
set
{
if (Equals(value, _OpenJobs)) return;
_OpenJobs = value;
NotifyPropertyChanged(m => m.OpenJobs);
}
}
private ChangeTrackingCollection<OpenJob> _OpenJobs;
#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<Job>.Equals(Job other)
{
if (EntityIdentifier != default(Guid))
return EntityIdentifier == other.EntityIdentifier;
return false;
}
#endregion Change Tracking
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
namespace Microsoft.Zelig.Test
{
public class UriTests : TestBase, ITestInterface
{
Uri uri;
UriProperties props;
ParsedUri parsed;
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests.");
// Add your functionality here.
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests.");
// TODO: Add your clean up steps here.
}
public override TestResult Run( string[] args )
{
return TestResult.Pass;
}
//--//
//--//
//--//
#region helper functions
private bool ValidUri(Uri uri, UriProperties props)
{
bool result = true;
// AbsolutePath
if (props.Path != null && uri.AbsolutePath != props.Path)
{
Log.Exception("Expected AbsolutePath: " + props.Path + ", but got: " + uri.AbsolutePath);
result = false;
}
// AbsoluteUri
if (uri.AbsoluteUri != props.AbsoluteUri)
{
Log.Exception("Expected AbsoluteUri: " + props.AbsoluteUri + ", but got: " + uri.AbsoluteUri);
result = false;
}
// HostNameType
if (uri.HostNameType != props.Type)
{
Log.Exception("Expected HostNameType: " + props.Type + ", but got: " + uri.HostNameType);
result = false;
}
switch (uri.Scheme.ToLower())
{
case "http":
case "https":
if (uri.Port != props.Port)
{
Log.Exception("Expected Port: " + props.Port + ", but got: " + uri.Port);
result = false;
}
// Host
if (uri.Host != props.Host)
{
Log.Exception("Expected Host: " + props.Host + ", but got: " + uri.Host);
result = false;
}
break;
default:
// no validation
break;
}
// Scheme
if (uri.Scheme != props.Scheme)
{
Log.Exception("Expected Scheme: " + props.Scheme + ", but got: " + uri.Scheme);
result = false;
}
return result;
}
#endregion Helper functions
#region Test Cases
[TestMethod]
public TestResult InvalidConstructorTests()
{
TestResult result = TestResult.Pass;
try
{
Log.Comment("null string constructor");
try { uri = new Uri(null); }
catch (ArgumentNullException ex)
{
if (!HttpTests.ValidateException(ex, typeof(ArgumentNullException)))
result = TestResult.Fail;
}
Log.Comment("no uri string");
try { uri = new Uri("foo"); }
catch (ArgumentException ex)
{
if (!HttpTests.ValidateException(ex, typeof(ArgumentException)))
result = TestResult.Fail;
}
Log.Comment("uri, no address");
try { uri = new Uri("http:"); }
catch (ArgumentException ex)
{
if (!HttpTests.ValidateException(ex, typeof(ArgumentException)))
result = TestResult.Fail;
}
Log.Comment("uri, starts with non-alpha");
try { uri = new Uri("1ttp://foo.com"); }
catch (ArgumentException ex)
{
if (!HttpTests.ValidateException(ex, typeof(ArgumentException)))
result = TestResult.Fail;
}
Log.Comment("uri, includes numeric");
try { uri = new Uri("h1tp://foo.com"); }
catch (ArgumentException ex)
{
if (!HttpTests.ValidateException(ex, typeof(ArgumentException)))
result = TestResult.Fail;
}
Log.Comment("uri, includes non-alpha");
try { uri = new Uri("h@tp://foo.com"); }
catch (ArgumentException ex)
{
if (!HttpTests.ValidateException(ex, typeof(ArgumentException)))
result = TestResult.Fail;
}
Log.Comment("No ABSPath port URI");
try { uri = new Uri(HttpTests.MSUrl + ":80"); }
catch (ArgumentException ex)
{
if (!HttpTests.ValidateException(ex, typeof(ArgumentException)))
result = TestResult.Fail;
}
Log.Comment("Empty string constructor");
try { uri = new Uri(""); }
catch (ArgumentException ex)
{
if (!HttpTests.ValidateException(ex, typeof(ArgumentNullException)))
result = TestResult.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected Exception", ex);
result = TestResult.Fail;
}
return result;
}
[TestMethod]
public TestResult ValidUri()
{
TestResult result = TestResult.Pass;
try
{
Log.Comment("Microsoft URL");
props = new UriProperties("http", "www.microsoft.com");
uri = new Uri(props.OriginalUri);
if (!ValidUri(uri, props))
result = TestResult.Fail;
Log.Comment("Alternate http port URL");
props = new UriProperties("http", "www.microsoft.com")
{
Port = 1080,
Path = "/" //Need to remove later. This seems like a bug to require it.
};
uri = new Uri(props.OriginalUri);
if (!ValidUri(uri, props))
result = TestResult.Fail;
Log.Comment("URL with content");
props = new UriProperties("http", "www.microsoft.com")
{
Path = "/en/us/default.aspx"
};
uri = new Uri(props.OriginalUri);
if (!ValidUri(uri, props))
result = TestResult.Fail;
}
catch (Exception ex)
{
Log.Exception("Unexpected Exception", ex);
result = TestResult.Fail;
}
return result;
}
[TestMethod]
public TestResult ValidURN()
{
TestResult result = TestResult.Pass;
try
{
Log.Comment("isbn");
props = new UriProperties("urn", "isbn:0451450523");
uri = new Uri(props.OriginalUri);
if (!ValidUri(uri, props))
result = TestResult.Fail;
Log.Comment("isan");
props = new UriProperties("urn", "isan:0000-0000-9E59-0000-O-0000-0000-2");
uri = new Uri(props.OriginalUri);
if (!ValidUri(uri, props))
result = TestResult.Fail;
Log.Comment("issn");
props = new UriProperties("urn", "issn:0167-6423");
uri = new Uri(props.OriginalUri);
if (!ValidUri(uri, props))
result = TestResult.Fail;
Log.Comment("ietf");
props = new UriProperties("urn", "ietf:rfc:2648");
uri = new Uri(props.OriginalUri);
if (!ValidUri(uri, props))
result = TestResult.Fail;
Log.Comment("mpeg");
props = new UriProperties("urn", "mpeg:mpeg7:schema:2001");
uri = new Uri(props.OriginalUri);
if (!ValidUri(uri, props))
result = TestResult.Fail;
Log.Comment("oid");
props = new UriProperties("urn", "oid:2.216.840");
uri = new Uri(props.OriginalUri);
if (!ValidUri(uri, props))
result = TestResult.Fail;
Log.Comment("urn:uuid");
props = new UriProperties("urn", "uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66");
uri = new Uri(props.OriginalUri);
if (!ValidUri(uri, props))
result = TestResult.Fail;
Log.Comment("uuid");
props = new UriProperties("uuid", "6e8bc430-9c3a-11d9-9669-0800200c9a66");
uri = new Uri(props.OriginalUri);
if (!ValidUri(uri, props))
result = TestResult.Fail;
Log.Comment("uci");
props = new UriProperties("urn", "uci:I001+SBSi-B10000083052");
uri = new Uri(props.OriginalUri);
if (!ValidUri(uri, props))
result = TestResult.Fail;
}
catch (Exception ex)
{
Log.Exception("Unexpected Exception", ex);
result = TestResult.Fail;
}
return result;
}
[TestMethod]
public TestResult AdditionalValidUri()
{
TestResult result = TestResult.Pass;
try
{
Log.Comment("iris.beep");
props = new UriProperties("iris.beep", "bop") { Type = UriHostNameType.Unknown };
uri = new Uri(props.OriginalUri);
if (!ValidUri(uri, props))
result = TestResult.Fail;
Log.Comment("Microsoft Secure URL");
props = new UriProperties("https", "www.microsoft.com");
uri = new Uri(props.OriginalUri);
if (!ValidUri(uri, props))
result = TestResult.Fail;
Log.Comment("Alternate https port URL");
props = new UriProperties("https", "www.microsoft.com")
{
Port = 1443
};
uri = new Uri(props.OriginalUri);
if (!ValidUri(uri, props))
result = TestResult.Fail;
Log.Comment("H323 uri");
props = new UriProperties("h323", "user@host:54");
uri = new Uri(props.OriginalUri);
if (!ValidUri(uri, props))
result = TestResult.Fail;
Log.Comment("FTP URI");
uri = new Uri("ftp://ftp.microsoft.com/file.txt");
parsed = new ParsedUri("ftp", "ftp.microsoft.com", UriHostNameType.Dns, 21, "/file.txt", "ftp://ftp.microsoft.com/file.txt");
if (!parsed.ValidUri(uri))
result = TestResult.Fail;
Log.Comment("Unix style file");
uri = new Uri("file:///etc/hosts");
parsed = new ParsedUri("file", string.Empty, UriHostNameType.Basic, -1, "/etc/hosts", "file:///etc/hosts");
if (!parsed.ValidUri(uri))
result = TestResult.Fail;
Log.Comment("Windows share style file");
uri = new Uri("file:///\\\\server\\folder\\file.txt");
parsed = new ParsedUri("file", "server", UriHostNameType.Dns, -1, "/folder/file.txt", "file://server/folder/file.txt");
if (!parsed.ValidUri(uri))
result = TestResult.Fail;
Log.Comment("Windows drive style file");
uri = new Uri("file:///c:\\rbllog");
parsed = new ParsedUri("file", string.Empty, UriHostNameType.Basic, -1, "c:/rbllog", "file:///c:/rbllog");
if (!parsed.ValidUri(uri))
result = TestResult.Fail;
}
catch (Exception ex)
{
Log.Exception("Unexpected Exception - these cases currently all fail", ex);
result = TestResult.Fail;
}
return result;
}
[TestMethod]
public TestResult RelativeURI()
{
TestResult result = TestResult.Pass;
try
{
Log.Comment("relative url");
uri = new Uri("/doc/text.html", UriKind.Relative);
Log.Comment("absolute url");
props = new UriProperties("https", "www.microsoft.com")
{
Path = "/doc/text.html",
Port = 1443
};
uri = new Uri(props.OriginalUri, UriKind.Absolute);
if (!ValidUri(uri, props))
result = TestResult.Fail;
Log.Comment("RelativeOrAbsolute");
try { uri = new Uri("/doc/text.html", UriKind.RelativeOrAbsolute); }
catch (ArgumentException ex)
{
if (!HttpTests.ValidateException(ex, typeof(ArgumentException)))
result = TestResult.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected Exception", ex);
result = TestResult.Fail;
}
return result;
}
[TestMethod]
public TestResult MoreSchemes()
{
TestResult result = TestResult.Pass;
var sUris = new string[]
{
"ws://ws.pusherapp.com:80/app/?client=js&version=1.9.3&protocol=5",
"\tftp://abc.com ",
"ldap://[2001:db8::7]/c=GB?objectClass?one",
"mailto:John.Doe@example.com",
"mailto://abc/d",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"h323:abc",
"h323://abc/d"
};
var parseds = new ParsedUri[]
{
new ParsedUri("ws", "ws.pusherapp.com", UriHostNameType.Dns, 80, "/app/?client=js&version=1.9.3&protocol=5", "ws://ws.pusherapp.com/app/?client=js&version=1.9.3&protocol=5"),
new ParsedUri("ftp", "abc.com", UriHostNameType.Dns, 21, "/", "ftp://abc.com/"),
new ParsedUri("ldap", "[2001:db8::7]", UriHostNameType.IPv6, 389, "/c=GB?objectClass?one", "ldap://[2001:db8::7]/c=GB?objectClass?one"),
new ParsedUri("mailto", "John.Doe@example.com", UriHostNameType.Dns, 25, string.Empty, "mailto:John.Doe@example.com"),
new ParsedUri("mailto", string.Empty, UriHostNameType.Basic, 25, "//abc/d", "mailto://abc/d"),
new ParsedUri("news", string.Empty, UriHostNameType.Unknown, -1, "comp.infosystems.www.servers.unix", "news:comp.infosystems.www.servers.unix"),
new ParsedUri("tel", string.Empty, UriHostNameType.Unknown, -1, "+1-816-555-1212", "tel:+1-816-555-1212"),
new ParsedUri("telnet", "192.0.2.16", UriHostNameType.IPv4, 80, "/", "telnet://192.0.2.16:80/"),
new ParsedUri("h323", string.Empty, UriHostNameType.Unknown, -1, "abc", "h323:abc"),
new ParsedUri("h323", "abc", UriHostNameType.Dns, -1, "/d", "h323://abc/d")
};
for (int i = 0; i < sUris.Length; i++)
{
uri = new Uri(sUris[i]);
if (!parseds[i].ValidUri(uri))
{
result = TestResult.Fail;
}
}
return result;
}
[TestMethod]
public TestResult FileScheme()
{
TestResult result = TestResult.Pass;
var sUris = new string[]
{
"file://",
"file:///",
"file:////",
"file://c",
"file:///c",
"file:////c",
};
var parseds = new ParsedUri[]
{
new ParsedUri("file", string.Empty, UriHostNameType.Basic, -1, "/", "file:///"),
new ParsedUri("file", string.Empty, UriHostNameType.Basic, -1, "/", "file:///"),
new ParsedUri("file", string.Empty, UriHostNameType.Basic, -1, "//", "file:////"),
new ParsedUri("file", "c", UriHostNameType.Dns, -1, "/", "file://c/"),
new ParsedUri("file", string.Empty, UriHostNameType.Basic, -1, "/c", "file:///c"),
new ParsedUri("file", "c", UriHostNameType.Dns, -1, "/", "file://c/"),
};
for (int i = 0; i < sUris.Length; i++)
{
uri = new Uri(sUris[i]);
if (!parseds[i].ValidUri(uri))
{
result = TestResult.Fail;
}
}
return result;
}
[TestMethod]
public TestResult Exceptions()
{
TestResult result = TestResult.Pass;
var sUris = new string[]
{
"file:///c:",
"http:abc/d/",
"file:/server"
};
for (int i = 0; i < sUris.Length; i++)
{
try
{
uri = new Uri(sUris[i]);
result = TestResult.Fail;
}
catch (ArgumentException)
{
}
}
return result;
}
#endregion Test Cases
}
#region helper class
public class UriProperties
{
private string _scheme;
private string _host;
private bool _portSet = false;
private int _port;
private UriHostNameType _type = UriHostNameType.Unknown;
public UriProperties(string Scheme, string Host)
{
// Minimal required properties
_scheme = Scheme;
_host = Host;
}
public string Scheme
{
get { return _scheme; }
}
public string Host
{
set { _host = value; }
get { return _host; }
}
public int Port
{
get
{
return _port;
}
set
{
_portSet = true;
_port = value;
}
}
public bool PortSet
{
get
{
return _portSet;
}
}
public string Path { get; set; }
public UriHostNameType Type
{
get
{
return _type;
}
set
{
_type = value;
}
}
public string AbsoluteUri
{
get
{
string uri = OriginalUri;
// for http[s] add trailing / if no path
if (Path == null && _scheme.ToLower().IndexOf("http") == 0 && uri[uri.Length - 1] != '/')
{
uri += "/";
}
return uri;
}
}
public string OriginalUri
{
get
{
string uri = _scheme;
int defaultPort = 0;
switch (_scheme.ToLower())
{
case "http":
_type = UriHostNameType.Dns;
defaultPort = 80;
uri += "://" + _host;
break;
case "https":
_type = UriHostNameType.Dns;
defaultPort = 443;
uri += "://" + _host;
break;
default:
// No hosts, so move _host to Path
if (_host != "")
{
Path = _host;
_host = "";
}
uri += ":" + _host;
break;
}
if (_portSet)
uri += ":" + Port;
else
_port = defaultPort;
if (Path != null)
uri += Path;
return uri;
}
}
}
class ParsedUri
{
public string Scheme { get; set; }
public string Host { get; set; }
public UriHostNameType HostNameType { get; set; }
public int Port { get; set; }
public string AbsolutePath { get; set; }
public string AbsoluteUri { get; set; }
public ParsedUri(string _scheme, string _host, UriHostNameType _hostNameType, int _port, string _absolutePath, string _absoluteUri)
{
Scheme = _scheme;
Host = _host;
HostNameType = _hostNameType;
Port = _port;
AbsolutePath = _absolutePath;
AbsoluteUri = _absoluteUri;
}
public bool ValidUri(Uri uri)
{
bool result = true;
// Scheme
if (uri.Scheme != Scheme)
{
Log.Exception("Expected Scheme: " + Scheme + ", but got: " + uri.Scheme);
result = false;
}
// Host
if (uri.Host != Host)
{
Log.Exception("Expected Host: " + Host + ", but got: " + uri.Host);
result = false;
}
// Port
if (uri.Port != Port)
{
Log.Exception("Expected Port: " + Port.ToString() + ", but got: " + uri.Port.ToString());
result = false;
}
// AbsolutePath
if (uri.AbsolutePath != AbsolutePath)
{
Log.Exception("Expected AbsolutePath: " + AbsolutePath + ", but got: " + uri.AbsolutePath);
result = false;
}
// AbsoluteUri
if (uri.AbsoluteUri != AbsoluteUri)
{
Log.Exception("Expected AbsoluteUri: " + AbsoluteUri + ", but got: " + uri.AbsoluteUri);
result = false;
}
// HostNameType
if (uri.HostNameType != HostNameType)
{
Log.Exception("Expected HostNameType: " + HostNameType + ", but got: " + uri.HostNameType);
result = false;
}
return result;
}
}
#endregion helper class
}
| |
// Copyright 2007-2014 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Tests.Serialization
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using MassTransit.Serialization;
using NUnit.Framework;
[TestFixture(typeof(XmlMessageSerializer))]
[TestFixture(typeof(JsonMessageSerializer))]
[TestFixture(typeof(BsonMessageSerializer))]
[TestFixture(typeof(EncryptedMessageSerializer))]
public class MoreSerialization_Specs :
SerializationTest
{
[Serializable]
public class ContainerClass
{
public IList<OuterClass> Elements { get; set; }
public bool Equals(ContainerClass other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
if (ReferenceEquals(other.Elements, Elements))
return true;
if (other.Elements == null && Elements != null)
return false;
if (other.Elements != null && Elements == null)
return false;
if (other.Elements != null && Elements != null)
{
if (other.Elements.Count != Elements.Count)
return false;
for (int i = 0; i < Elements.Count; i++)
{
if (!Equals(other.Elements[i], Elements[i]))
return false;
}
}
return true;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != typeof(ContainerClass))
return false;
return Equals((ContainerClass)obj);
}
public override int GetHashCode()
{
return (Elements != null ? Elements.GetHashCode() : 0);
}
}
[Serializable]
public class DictionaryContainerClass
{
public DictionaryContainerClass()
{
Elements = new Dictionary<string, OuterClass>();
}
public IDictionary<string, OuterClass> Elements { get; set; }
public bool Equals(DictionaryContainerClass other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
if (ReferenceEquals(other.Elements, Elements))
return true;
if (other.Elements == null && Elements != null)
{
Trace.WriteLine("other element was null");
return false;
}
if (other.Elements != null && Elements == null)
{
Trace.WriteLine("other element was not null");
return false;
}
if (other.Elements != null && Elements != null)
{
if (other.Elements.Count != Elements.Count)
return false;
foreach (var pair in Elements)
{
if (!other.Elements.ContainsKey(pair.Key))
return false;
if (!Equals(pair.Value, other.Elements[pair.Key]))
return false;
}
}
return true;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != typeof(DictionaryContainerClass))
return false;
return Equals((DictionaryContainerClass)obj);
}
public override int GetHashCode()
{
return (Elements != null ? Elements.GetHashCode() : 0);
}
}
[Serializable]
public class PrimitiveArrayClass
{
public PrimitiveArrayClass()
{
Values = new int[] {};
}
public int[] Values { get; set; }
public bool Equals(PrimitiveArrayClass other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
if (ReferenceEquals(other.Values, Values))
return true;
if (other.Values == null && Values != null)
return false;
if (other.Values != null && Values == null)
return false;
if (other.Values != null && Values != null)
{
if (other.Values.Length != Values.Length)
return false;
for (int i = 0; i < Values.Length; i++)
{
if (!Equals(other.Values[i], Values[i]))
return false;
}
}
return true;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != typeof(PrimitiveArrayClass))
return false;
return Equals((PrimitiveArrayClass)obj);
}
public override int GetHashCode()
{
return (Values != null ? Values.GetHashCode() : 0);
}
}
[Serializable]
public class GenericArrayClass<T>
{
public T[] Values { get; set; }
public bool Equals(GenericArrayClass<T> other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
if (ReferenceEquals(other.Values, Values))
return true;
if (other.Values == null && Values != null)
return false;
if (other.Values != null && Values == null)
return false;
if (other.Values != null && Values != null)
{
if (other.Values.Length != Values.Length)
return false;
for (int i = 0; i < Values.Length; i++)
{
if (!Equals(other.Values[i], Values[i]))
return false;
}
}
return true;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != typeof(GenericArrayClass<T>))
return false;
return Equals((GenericArrayClass<T>)obj);
}
public override int GetHashCode()
{
return (Values != null ? Values.GetHashCode() : 0);
}
}
[Serializable]
public class OuterClass
{
public InnerClass Inner { get; set; }
public bool Equals(OuterClass other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Equals(other.Inner, Inner);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != typeof(OuterClass))
return false;
return Equals((OuterClass)obj);
}
public override int GetHashCode()
{
return (Inner != null ? Inner.GetHashCode() : 0);
}
}
[Serializable]
public class InnerClass
{
public string Name { get; set; }
public bool Equals(InnerClass other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Equals(other.Name, Name);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != typeof(InnerClass))
return false;
return Equals((InnerClass)obj);
}
public override int GetHashCode()
{
return (Name != null ? Name.GetHashCode() : 0);
}
}
[Serializable]
public class EmptyClass
{
public bool Equals(EmptyClass other)
{
return !ReferenceEquals(null, other);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != typeof(EmptyClass))
return false;
return Equals((EmptyClass)obj);
}
public override int GetHashCode()
{
return 0;
}
}
public MoreSerialization_Specs(Type serializerType)
: base(serializerType)
{
}
[Serializable]
public class EnumClass
{
public SomeEnum Setting { get; set; }
public bool Equals(EnumClass other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Equals(other.Setting, Setting);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != typeof(EnumClass))
return false;
return Equals((EnumClass)obj);
}
public override int GetHashCode()
{
return Setting.GetHashCode();
}
}
[Test]
public void A_collection_of_objects_should_be_properly_serialized()
{
var message = new ContainerClass
{
Elements = new List<OuterClass>
{
new OuterClass
{
Inner = new InnerClass {Name = "Chris"},
},
new OuterClass
{
Inner = new InnerClass {Name = "David"},
},
}
};
TestSerialization(message);
}
[Test]
public void A_dictionary_of_no_objects_should_be_properly_serialized()
{
var message = new DictionaryContainerClass
{
Elements = new Dictionary<string, OuterClass>()
};
TestSerialization(message);
}
[Test]
public void A_dictionary_of_objects_should_be_properly_serialized()
{
var message = new DictionaryContainerClass
{
Elements = new Dictionary<string, OuterClass>
{
{"Chris", new OuterClass {Inner = new InnerClass {Name = "Chris"}}},
{"David", new OuterClass {Inner = new InnerClass {Name = "David"}}},
}
};
TestSerialization(message);
}
[Test]
public void A_dictionary_of_one_objects_should_be_properly_serialized()
{
var message = new DictionaryContainerClass
{
Elements = new Dictionary<string, OuterClass>
{
{"David", new OuterClass {Inner = new InnerClass {Name = "David"}}},
}
};
TestSerialization(message);
}
[Test]
public void A_nested_object_should_be_properly_serialized()
{
var message = new OuterClass
{
Inner = new InnerClass {Name = "Chris"},
};
TestSerialization(message);
}
[Test]
public void A_primitive_array_of_objects_should_be_properly_serialized()
{
var message = new PrimitiveArrayClass
{
Values = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
};
TestSerialization(message);
}
[Test]
public void A_primitive_array_of_objects_with_no_elements_should_be_properly_serialized()
{
var message = new PrimitiveArrayClass
{
Values = new int[] {}
};
TestSerialization(message);
}
[Test]
public void A_primitive_array_of_objects_with_one_element_should_be_properly_serialized()
{
var message = new PrimitiveArrayClass
{
Values = new[] {1}
};
TestSerialization(message);
}
[Test]
public void A_private_setter_should_be_serializable()
{
const string expected = "Dr. Cox";
var message = new PrivateSetter(expected);
TestSerialization(message);
}
[Test]
public void An_array_of_objects_should_be_properly_serialized()
{
var message = new GenericArrayClass<InnerClass>
{
Values = new[]
{
new InnerClass {Name = "Chris"},
new InnerClass {Name = "David"}
}
};
TestSerialization(message);
}
[Test]
public void An_empty_array_of_objects_should_be_properly_serialized()
{
var message = new PrimitiveArrayClass
{
Values = new int[] {}
};
TestSerialization(message);
}
[Test]
public void An_empty_class_should_not_break_the_mold()
{
var message = new EmptyClass();
TestSerialization(message);
}
[Test]
public void An_enumeration_should_be_serializable()
{
var message = new EnumClass {Setting = SomeEnum.Second};
TestSerialization(message);
}
}
[Serializable]
public class PrivateSetter
{
public PrivateSetter(string name)
{
Name = name;
}
protected PrivateSetter()
{
}
public string Name { get; private set; }
public bool Equals(PrivateSetter other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Equals(other.Name, Name);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != typeof(PrivateSetter))
return false;
return Equals((PrivateSetter)obj);
}
public override int GetHashCode()
{
return (Name != null ? Name.GetHashCode() : 0);
}
}
public enum SomeEnum
{
First,
Second,
Third,
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using WebApiExternalAuth.Areas.HelpPage.Models;
namespace WebApiExternalAuth.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="XmlElementParser.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Microsoft.OData.Edm.Csdl.Parsing.Common
{
internal static class XmlElementValueExtensions
{
internal static IEnumerable<XmlElementValue<T>> OfResultType<T>(this IEnumerable<XmlElementValue> elements)
where T : class
{
foreach (var element in elements)
{
XmlElementValue<T> result = element as XmlElementValue<T>;
if (result != null)
{
yield return result;
}
else if (element.UntypedValue is T)
{
yield return new XmlElementValue<T>(element.Name, element.Location, element.ValueAs<T>());
}
}
}
internal static IEnumerable<T> ValuesOfType<T>(this IEnumerable<XmlElementValue> elements)
where T : class
{
return elements.OfResultType<T>().Select(ev => ev.Value);
}
internal static IEnumerable<XmlTextValue> OfText(this IEnumerable<XmlElementValue> elements)
{
foreach (var element in elements)
{
if (element.IsText)
{
yield return (XmlTextValue)element;
}
}
}
}
internal abstract class XmlElementParser
{
private readonly Dictionary<string, XmlElementParser> childParsers;
protected XmlElementParser(string elementName, Dictionary<string, XmlElementParser> children)
{
this.ElementName = elementName;
this.childParsers = children;
}
internal string ElementName
{
get;
private set;
}
public void AddChildParser(XmlElementParser child)
{
this.childParsers[child.ElementName] = child;
}
#region Factory Methods
internal static XmlElementParser<TResult> Create<TResult>(string elementName, Func<XmlElementInfo, XmlElementValueCollection, TResult> parserFunc, IEnumerable<XmlElementParser> childParsers, IEnumerable<XmlElementParser> descendantParsers)
{
Dictionary<string, XmlElementParser> children = null;
if (childParsers != null)
{
children = childParsers.ToDictionary(p => p.ElementName);
}
return new XmlElementParser<TResult>(elementName, children, parserFunc);
}
#endregion
internal abstract XmlElementValue Parse(XmlElementInfo element, IList<XmlElementValue> children);
internal bool TryGetChildElementParser(string elementName, out XmlElementParser elementParser)
{
elementParser = null;
return this.childParsers != null && this.childParsers.TryGetValue(elementName, out elementParser);
}
}
internal class XmlElementParser<TResult> : XmlElementParser
{
private readonly Func<XmlElementInfo, XmlElementValueCollection, TResult> parserFunc;
internal XmlElementParser(
string elementName,
Dictionary<string, XmlElementParser> children,
Func<XmlElementInfo, XmlElementValueCollection, TResult> parser)
: base(elementName, children)
{
this.parserFunc = parser;
}
internal override XmlElementValue Parse(XmlElementInfo element, IList<XmlElementValue> children)
{
TResult result = this.parserFunc(element, XmlElementValueCollection.FromList(children));
return new XmlElementValue<TResult>(element.Name, element.Location, result);
}
}
internal class XmlElementValueCollection : IEnumerable<XmlElementValue>
{
private static readonly XmlElementValueCollection empty = new XmlElementValueCollection(new XmlElementValue[] { }, new XmlElementValue[] { }.ToLookup(value => value.Name));
private readonly IList<XmlElementValue> values;
private ILookup<string, XmlElementValue> nameLookup;
private XmlElementValueCollection(IList<XmlElementValue> list, ILookup<string, XmlElementValue> nameMap)
{
Debug.Assert(list != null, "FromList should replace null list with XmlElementValueCollection.empty");
this.values = list;
this.nameLookup = nameMap;
}
internal XmlTextValue FirstText
{
get { return (this.values.OfText().FirstOrDefault() ?? XmlTextValue.Missing); }
}
internal XmlElementValue this[string elementName]
{
get
{
return this.EnsureLookup()[elementName].FirstOrDefault() ?? MissingXmlElementValue.Instance;
}
}
public IEnumerator<XmlElementValue> GetEnumerator()
{
return this.values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.values.GetEnumerator();
}
internal static XmlElementValueCollection FromList(IList<XmlElementValue> values)
{
if (values == null || values.Count == 0)
{
return XmlElementValueCollection.empty;
}
return new XmlElementValueCollection(values, null);
}
internal IEnumerable<XmlElementValue> FindByName(string elementName)
{
return this.EnsureLookup()[elementName];
}
internal IEnumerable<XmlElementValue<TResult>> FindByName<TResult>(string elementName)
where TResult : class
{
return this.FindByName(elementName).OfResultType<TResult>();
}
private ILookup<string, XmlElementValue> EnsureLookup()
{
return this.nameLookup ?? (this.nameLookup = this.values.ToLookup(value => value.Name));
}
internal sealed class MissingXmlElementValue : XmlElementValue
{
internal static readonly MissingXmlElementValue Instance = new MissingXmlElementValue();
private MissingXmlElementValue()
: base(null, default(CsdlLocation))
{
}
internal override object UntypedValue
{
get { return null; }
}
internal override bool IsUsed
{
get { return false; }
}
}
}
internal abstract class XmlElementValue
{
internal XmlElementValue(string elementName, CsdlLocation elementLocation)
{
this.Name = elementName;
this.Location = elementLocation;
}
internal string Name
{
get;
private set;
}
internal CsdlLocation Location
{
get;
private set;
}
internal abstract object UntypedValue
{
get;
}
internal abstract bool IsUsed
{
get;
}
internal virtual bool IsText
{
get { return false; }
}
internal virtual string TextValue
{
get { return this.ValueAs<string>(); }
}
internal virtual TValue ValueAs<TValue>() where TValue : class
{
return this.UntypedValue as TValue;
}
}
internal class XmlElementValue<TValue> : XmlElementValue
{
private readonly TValue value;
private bool isUsed;
internal XmlElementValue(string name, CsdlLocation location, TValue newValue)
: base(name, location)
{
this.value = newValue;
}
internal override bool IsText
{
get { return false; }
}
internal override bool IsUsed
{
get { return this.isUsed; }
}
internal override object UntypedValue
{
get { return this.value; }
}
internal TValue Value
{
get
{
this.isUsed = true;
return this.value;
}
}
internal override T ValueAs<T>()
{
return this.Value as T;
}
}
internal class XmlTextValue : XmlElementValue<string>
{
internal static readonly XmlTextValue Missing = new XmlTextValue(default(CsdlLocation), null);
internal const string ElementName = "<\"Text\">";
internal XmlTextValue(CsdlLocation textLocation, string textValue)
: base(ElementName, textLocation, textValue)
{
}
internal override bool IsText
{
get { return true; }
}
internal override string TextValue
{
get { return this.Value; }
}
}
}
| |
namespace System.Web.DynamicData {
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Globalization;
using System.Web.Resources;
using System.Diagnostics;
/// <summary>
/// Field type that can display DynamicData UI
/// </summary>
[Designer("System.Web.DynamicData.Design.DynamicFieldDesigner, " + AssemblyRef.SystemWebDynamicDataDesign)]
public class DynamicField : DataControlField, IAttributeAccessor, IFieldFormattingOptions {
private bool _customConvertEmptyStringToNullSet;
private bool _customApplyFormatInEditModeSet;
private MetaColumn _column;
private IDictionary<string, string> _attributes;
/// <summary>
/// same as base. uses column's display name if possible
/// </summary>
public override string HeaderText {
get {
object o = ViewState["HeaderText"];
if (o != null)
return (string)o;
// Default to the Column's DisplayName
if (Column != null)
return Column.DisplayName;
// If we couldn't get it, use the name if the data field
return DataField;
}
set {
base.HeaderText = value;
}
}
/// <summary>
/// same as base. uses column's SortExpression property, if possible.
/// </summary>
public override string SortExpression {
get {
object o = ViewState["SortExpression"];
if (o != null)
return (string)o;
// Default to the Column's SortExpression
if (Column != null)
return Column.SortExpression;
return String.Empty;
}
set {
base.SortExpression = value;
}
}
/// <summary>
/// Determines whether the control validates client input or not, defaults to inherit from parent.
/// </summary>
[
Category("Behavior"),
ResourceDescription("DynamicField_ValidateRequestMode"),
DefaultValue(ValidateRequestMode.Inherit)
]
public new ValidateRequestMode ValidateRequestMode {
get {
return base.ValidateRequestMode;
}
set {
base.ValidateRequestMode = value;
}
}
[
SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "ReadOnly", Justification="Matches DataBoundControlMode value"),
DefaultValue(false),
Category("Behavior"),
ResourceDescription("DynamicField_ReadOnly"),
]
/// <summary>
/// Forces this DynamicField to always load a ReadOnly template
/// </summary>
public virtual bool ReadOnly {
get {
object o = ViewState["ReadOnly"];
return (o == null ? false : (bool)o);
}
set {
ViewState["ReadOnly"] = value;
}
}
/// <summary>
/// The name of the column that this field handles
/// </summary>
[
Category("Data"),
DefaultValue(""),
ResourceDescription("DynamicControlFieldCommon_DataField")
]
public virtual string DataField {
get {
object o = ViewState["DataField"];
return ((o == null) ? String.Empty : (string)o);
}
set {
if (!String.Equals(value, ViewState["DataField"])) {
ViewState["DataField"] = value;
OnFieldChanged();
}
}
}
/// <summary>
/// The MetaColumn that this fiedl is working with
/// </summary>
protected MetaColumn Column {
get {
// Don't do anything in Design mode. In some cases in the Designer (in the Edit field dialog),
// DesignMode actually returns true, so checking for a null Control provides an additional check.
if (DesignMode || Control == null)
return null;
if (_column == null) {
MetaTable table = Control.FindMetaTable();
if (table == null) {
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, DynamicDataResources.DynamicControl_ControlNeedsToExistInADataControlUsingDynamicDataSource));
}
_column = table.GetColumn(DataField);
}
return _column;
}
}
/// <summary>
/// An optional UIHint specified on the field
/// </summary>
[
Category("Behavior"),
DefaultValue(""),
ResourceDescription("DynamicControlFieldCommon_UIHint")
]
public virtual string UIHint {
get {
object o = ViewState["UIHint"];
return ((o == null) ? String.Empty : (string)o);
}
set {
if (!String.Equals(value, ViewState["UIHint"])) {
ViewState["UIHint"] = value;
OnFieldChanged();
}
}
}
/// <summary>
/// The validation group that the field template needs to be in
/// </summary>
[
Category("Behavior"),
DefaultValue(""),
ResourceDescription("DynamicControlFieldCommon_ValidationGroup")
]
public virtual string ValidationGroup {
get {
object o = ViewState["ValidationGroup"];
return ((o == null) ? String.Empty : (string)o);
}
set {
if (!String.Equals(value, ViewState["ValidationGroup"])) {
ViewState["ValidationGroup"] = value;
OnFieldChanged();
}
}
}
/// <summary>
/// See base class documentation
/// </summary>
protected override DataControlField CreateField() {
return new DynamicField();
}
/// <summary>
/// See base class documentation
/// </summary>
public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType,
DataControlRowState rowState, int rowIndex) {
base.InitializeCell(cell, cellType, rowState, rowIndex);
if (cellType == DataControlCellType.DataCell) {
DynamicControl control = CreateDynamicControl();
control.DataField = DataField;
control.Mode = DetermineControlMode(rowState);
// Copy various properties into the control
if (_customApplyFormatInEditModeSet) {
control.ApplyFormatInEditMode = ApplyFormatInEditMode;
}
if (_customConvertEmptyStringToNullSet) {
control.ConvertEmptyStringToNull = ConvertEmptyStringToNull;
}
control.DataFormatString = DataFormatString;
if (ViewState["HtmlEncode"] == null) {
// There is no Column in Design Mode
if (!DesignMode) {
control.HtmlEncode = Column.HtmlEncode;
}
}
else {
control.HtmlEncode = HtmlEncode;
}
control.NullDisplayText = NullDisplayText;
control.UIHint = UIHint;
control.ValidationGroup = ValidationGroup;
// Pass it all the extra declarative attributes that we got
control.SetAttributes(_attributes);
ConfigureDynamicControl(control);
cell.Controls.Add(control);
}
}
/// <summary>
/// Provides a way for classes deriving from DynamicField to override how DynamicControl gets created.
/// </summary>
/// <returns></returns>
protected virtual DynamicControl CreateDynamicControl() {
return new DynamicControl();
}
/// <summary>
/// Provides a hook to further modify a DynamicControl that was created by the InitializeCell method
/// </summary>
/// <param name="control"></param>
protected virtual void ConfigureDynamicControl(DynamicControl control) {
Debug.Assert(control != null);
}
private DataBoundControlMode DetermineControlMode(DataControlRowState rowState) {
if (ReadOnly) {
return DataBoundControlMode.ReadOnly;
}
bool edit = (rowState & DataControlRowState.Edit) != 0;
bool insert = (rowState & DataControlRowState.Insert) != 0;
if (edit) {
return DataBoundControlMode.Edit;
} else if (insert) {
return DataBoundControlMode.Insert;
} else {
return DataBoundControlMode.ReadOnly;
}
}
/// <summary>
/// See base class documentation
/// </summary>
public override void ExtractValuesFromCell(IOrderedDictionary dictionary, DataControlFieldCell cell,
DataControlRowState rowState, bool includeReadOnly) {
Misc.ExtractValuesFromBindableControls(dictionary, cell);
}
/// <summary>
/// See base class documentation
/// </summary>
protected override void CopyProperties(DataControlField newField) {
base.CopyProperties(newField);
DynamicField field = ((DynamicField)newField);
field.DataField = DataField;
field.ApplyFormatInEditMode = ApplyFormatInEditMode;
field.ConvertEmptyStringToNull = ConvertEmptyStringToNull;
field.HtmlEncode = HtmlEncode;
field.ReadOnly = ReadOnly;
field.NullDisplayText = NullDisplayText;
field.UIHint = UIHint;
field.ValidationGroup = ValidationGroup;
field.DataFormatString = DataFormatString;
}
#region IAttributeAccessor Members
/// <summary>
/// See IAttributeAccessor
/// </summary>
public string GetAttribute(string key) {
if (_attributes == null)
return String.Empty;
return _attributes[key];
}
/// <summary>
/// See IAttributeAccessor
/// </summary>
public void SetAttribute(string key, string value) {
if (_attributes == null) {
_attributes = new Dictionary<string, string>();
}
_attributes[key] = value;
}
#endregion
#region IFieldFormattingOptions Members
/// <summary>
/// See IFieldFormattingOptions
/// </summary>
[
Category("Behavior"),
DefaultValue(false),
ResourceDescription("DynamicControlFieldCommon_ConvertEmptyStringToNull")
]
public bool ConvertEmptyStringToNull {
get {
object o = ViewState["ConvertEmptyStringToNull"];
return (o == null ? false : (bool)o);
}
set {
_customConvertEmptyStringToNullSet = true;
ViewState["ConvertEmptyStringToNull"] = value;
}
}
/// <summary>
/// See IFieldFormattingOptions
/// </summary>
[
Category("Behavior"),
DefaultValue(false),
ResourceDescription("DynamicControlFieldCommon_ApplyFormatInEditMode")
]
public bool ApplyFormatInEditMode {
get {
object o = ViewState["ApplyFormatInEditMode"];
return (o == null ? false : (bool)o);
}
set {
_customApplyFormatInEditModeSet = true;
ViewState["ApplyFormatInEditMode"] = value;
}
}
/// <summary>
/// See IFieldFormattingOptions
/// </summary>
[
Category("Data"),
DefaultValue(""),
ResourceDescription("DynamicControlFieldCommon_DataFormatString")
]
public string DataFormatString {
get {
object o = ViewState["DataFormatString"];
return (o == null ? String.Empty : (string)o);
}
set {
ViewState["DataFormatString"] = value;
}
}
/// <summary>
/// See IFieldFormattingOptions
/// </summary>
[
Category("Behavior"),
DefaultValue(true),
ResourceDescription("DynamicControlFieldCommon_HtmlEncode")
]
public bool HtmlEncode {
get {
object o = ViewState["HtmlEncode"];
return (o == null ? true : (bool)o);
}
set {
ViewState["HtmlEncode"] = value;
}
}
/// <summary>
/// See IFieldFormattingOptions
/// </summary>
[
Category("Behavior"),
DefaultValue(""),
ResourceDescription("DynamicControlFieldCommon_NullDisplayText")
]
public string NullDisplayText {
get {
object o = ViewState["NullDisplayText"];
return (o == null ? String.Empty : (string)o);
}
set {
ViewState["NullDisplayText"] = value;
}
}
#endregion
}
}
| |
//
// https://github.com/mythz/ServiceStack.Redis
// ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2013 ServiceStack.
//
// Licensed under the same terms of Redis and ServiceStack: new BSD license.
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using NServiceKit.DesignPatterns.Model;
using NServiceKit.Redis.Support;
using NServiceKit.Text;
namespace NServiceKit.Redis
{
public partial class RedisClient : IRedisClient
{
public IHasNamed<IRedisSortedSet> SortedSets { get; set; }
internal class RedisClientSortedSets
: IHasNamed<IRedisSortedSet>
{
private readonly RedisClient client;
public RedisClientSortedSets(RedisClient client)
{
this.client = client;
}
public IRedisSortedSet this[string setId]
{
get
{
return new RedisClientSortedSet(client, setId);
}
set
{
var col = this[setId];
col.Clear();
col.CopyTo(value.ToArray(), 0);
}
}
}
public static double GetLexicalScore(string value)
{
if (string.IsNullOrEmpty(value))
return 0;
var lexicalValue = 0;
if (value.Length >= 1)
lexicalValue += value[0] * (int)Math.Pow(256, 3);
if (value.Length >= 2)
lexicalValue += value[1] * (int)Math.Pow(256, 2);
if (value.Length >= 3)
lexicalValue += value[2] * (int)Math.Pow(256, 1);
if (value.Length >= 4)
lexicalValue += value[3];
return lexicalValue;
}
public bool AddItemToSortedSet(string setId, string value)
{
return AddItemToSortedSet(setId, value, GetLexicalScore(value));
}
public bool AddItemToSortedSet(string setId, string value, double score)
{
return base.ZAdd(setId, score, value.ToUtf8Bytes()) == Success;
}
public bool AddItemToSortedSet(string setId, string value, long score)
{
return base.ZAdd(setId, score, value.ToUtf8Bytes()) == Success;
}
public bool AddRangeToSortedSet(string setId, List<string> values, double score)
{
var pipeline = CreatePipelineCommand();
var uSetId = setId.ToUtf8Bytes();
var uScore = score.ToFastUtf8Bytes();
foreach (var value in values)
{
pipeline.WriteCommand(Commands.ZAdd, uSetId, uScore, value.ToUtf8Bytes());
}
pipeline.Flush();
var success = pipeline.ReadAllAsIntsHaveSuccess();
return success;
}
public long AddRangeToSortedSetWithScores(string setId, List<KeyValuePair<string, double>> valuesWithScore)
{
var uSetId = setId.ToUtf8Bytes();
var byteValuesWithScore = valuesWithScore.Select(x => new KeyValuePair<byte[], double>(x.Key.ToUtf8Bytes(), x.Value)).ToList();
return ZAdd(setId, byteValuesWithScore);
}
public bool AddRangeToSortedSet(string setId, List<string> values, long score)
{
var pipeline = CreatePipelineCommand();
var uSetId = setId.ToUtf8Bytes();
var uScore = score.ToUtf8Bytes();
foreach (var value in values)
{
pipeline.WriteCommand(Commands.ZAdd, uSetId, uScore, value.ToUtf8Bytes());
}
pipeline.Flush();
var success = pipeline.ReadAllAsIntsHaveSuccess();
return success;
}
public bool RemoveItemFromSortedSet(string setId, string value)
{
return base.ZRem(setId, value.ToUtf8Bytes()) == Success;
}
public string PopItemWithLowestScoreFromSortedSet(string setId)
{
//TODO: this should be atomic
var topScoreItemBytes = base.ZRange(setId, FirstElement, 1);
if (topScoreItemBytes.Length == 0) return null;
base.ZRem(setId, topScoreItemBytes[0]);
return topScoreItemBytes[0].FromUtf8Bytes();
}
public string PopItemWithHighestScoreFromSortedSet(string setId)
{
//TODO: this should be atomic
var topScoreItemBytes = base.ZRevRange(setId, FirstElement, 1);
if (topScoreItemBytes.Length == 0) return null;
base.ZRem(setId, topScoreItemBytes[0]);
return topScoreItemBytes[0].FromUtf8Bytes();
}
public bool SortedSetContainsItem(string setId, string value)
{
return base.ZRank(setId, value.ToUtf8Bytes()) != -1;
}
public double IncrementItemInSortedSet(string setId, string value, double incrementBy)
{
return base.ZIncrBy(setId, incrementBy, value.ToUtf8Bytes());
}
public double IncrementItemInSortedSet(string setId, string value, long incrementBy)
{
return base.ZIncrBy(setId, incrementBy, value.ToUtf8Bytes());
}
public long GetItemIndexInSortedSet(string setId, string value)
{
return base.ZRank(setId, value.ToUtf8Bytes());
}
public long GetItemIndexInSortedSetDesc(string setId, string value)
{
return base.ZRevRank(setId, value.ToUtf8Bytes());
}
public List<string> GetAllItemsFromSortedSet(string setId)
{
var multiDataList = base.ZRange(setId, FirstElement, LastElement);
return multiDataList.ToStringList();
}
public List<string> GetAllItemsFromSortedSetDesc(string setId)
{
var multiDataList = base.ZRevRange(setId, FirstElement, LastElement);
return multiDataList.ToStringList();
}
public List<string> GetRangeFromSortedSet(string setId, int fromRank, int toRank)
{
var multiDataList = base.ZRange(setId, fromRank, toRank);
return multiDataList.ToStringList();
}
public List<string> GetRangeFromSortedSetDesc(string setId, int fromRank, int toRank)
{
var multiDataList = base.ZRevRange(setId, fromRank, toRank);
return multiDataList.ToStringList();
}
public IDictionary<string, double> GetAllWithScoresFromSortedSet(string setId)
{
var multiDataList = base.ZRangeWithScores(setId, FirstElement, LastElement);
return CreateSortedScoreMap(multiDataList);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSet(string setId, int fromRank, int toRank)
{
var multiDataList = base.ZRangeWithScores(setId, fromRank, toRank);
return CreateSortedScoreMap(multiDataList);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetDesc(string setId, int fromRank, int toRank)
{
var multiDataList = base.ZRevRangeWithScores(setId, fromRank, toRank);
return CreateSortedScoreMap(multiDataList);
}
private static IDictionary<string, double> CreateSortedScoreMap(byte[][] multiDataList)
{
var map = new OrderedDictionary<string, double>();
for (var i = 0; i < multiDataList.Length; i += 2)
{
var key = multiDataList[i].FromUtf8Bytes();
double value;
double.TryParse(multiDataList[i + 1].FromUtf8Bytes(), NumberStyles.Any, CultureInfo.InvariantCulture, out value);
map[key] = value;
}
return map;
}
public List<string> GetRangeFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore)
{
return GetRangeFromSortedSetByLowestScore(setId, fromStringScore, toStringScore, null, null);
}
public List<string> GetRangeFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take)
{
var fromScore = GetLexicalScore(fromStringScore);
var toScore = GetLexicalScore(toStringScore);
return GetRangeFromSortedSetByLowestScore(setId, fromScore, toScore, skip, take);
}
public List<string> GetRangeFromSortedSetByLowestScore(string setId, double fromScore, double toScore)
{
return GetRangeFromSortedSetByLowestScore(setId, fromScore, toScore, null, null);
}
public List<string> GetRangeFromSortedSetByLowestScore(string setId, long fromScore, long toScore)
{
return GetRangeFromSortedSetByLowestScore(setId, fromScore, toScore, null, null);
}
public List<string> GetRangeFromSortedSetByLowestScore(string setId, double fromScore, double toScore, int? skip, int? take)
{
var multiDataList = base.ZRangeByScore(setId, fromScore, toScore, skip, take);
return multiDataList.ToStringList();
}
public List<string> GetRangeFromSortedSetByLowestScore(string setId, long fromScore, long toScore, int? skip, int? take)
{
var multiDataList = base.ZRangeByScore(setId, fromScore, toScore, skip, take);
return multiDataList.ToStringList();
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore)
{
return GetRangeWithScoresFromSortedSetByLowestScore(setId, fromStringScore, toStringScore, null, null);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take)
{
var fromScore = GetLexicalScore(fromStringScore);
var toScore = GetLexicalScore(toStringScore);
return GetRangeWithScoresFromSortedSetByLowestScore(setId, fromScore, toScore, skip, take);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, double fromScore, double toScore)
{
return GetRangeWithScoresFromSortedSetByLowestScore(setId, fromScore, toScore, null, null);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, long fromScore, long toScore)
{
return GetRangeWithScoresFromSortedSetByLowestScore(setId, fromScore, toScore, null, null);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, double fromScore, double toScore, int? skip, int? take)
{
var multiDataList = base.ZRangeByScoreWithScores(setId, fromScore, toScore, skip, take);
return CreateSortedScoreMap(multiDataList);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, long fromScore, long toScore, int? skip, int? take)
{
var multiDataList = base.ZRangeByScoreWithScores(setId, fromScore, toScore, skip, take);
return CreateSortedScoreMap(multiDataList);
}
public List<string> GetRangeFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore)
{
return GetRangeFromSortedSetByHighestScore(setId, fromStringScore, toStringScore, null, null);
}
public List<string> GetRangeFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take)
{
var fromScore = GetLexicalScore(fromStringScore);
var toScore = GetLexicalScore(toStringScore);
return GetRangeFromSortedSetByHighestScore(setId, fromScore, toScore, skip, take);
}
public List<string> GetRangeFromSortedSetByHighestScore(string setId, double fromScore, double toScore)
{
return GetRangeFromSortedSetByHighestScore(setId, fromScore, toScore, null, null);
}
public List<string> GetRangeFromSortedSetByHighestScore(string setId, long fromScore, long toScore)
{
return GetRangeFromSortedSetByHighestScore(setId, fromScore, toScore, null, null);
}
public List<string> GetRangeFromSortedSetByHighestScore(string setId, double fromScore, double toScore, int? skip, int? take)
{
var multiDataList = base.ZRevRangeByScore(setId, fromScore, toScore, skip, take);
return multiDataList.ToStringList();
}
public List<string> GetRangeFromSortedSetByHighestScore(string setId, long fromScore, long toScore, int? skip, int? take)
{
var multiDataList = base.ZRevRangeByScore(setId, fromScore, toScore, skip, take);
return multiDataList.ToStringList();
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore)
{
return GetRangeWithScoresFromSortedSetByHighestScore(setId, fromStringScore, toStringScore, null, null);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take)
{
var fromScore = GetLexicalScore(fromStringScore);
var toScore = GetLexicalScore(toStringScore);
return GetRangeWithScoresFromSortedSetByHighestScore(setId, fromScore, toScore, skip, take);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, double fromScore, double toScore)
{
return GetRangeWithScoresFromSortedSetByHighestScore(setId, fromScore, toScore, null, null);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, long fromScore, long toScore)
{
return GetRangeWithScoresFromSortedSetByHighestScore(setId, fromScore, toScore, null, null);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, double fromScore, double toScore, int? skip, int? take)
{
var multiDataList = base.ZRevRangeByScoreWithScores(setId, fromScore, toScore, skip, take);
return CreateSortedScoreMap(multiDataList);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, long fromScore, long toScore, int? skip, int? take)
{
var multiDataList = base.ZRevRangeByScoreWithScores(setId, fromScore, toScore, skip, take);
return CreateSortedScoreMap(multiDataList);
}
public long RemoveRangeFromSortedSet(string setId, int minRank, int maxRank)
{
return base.ZRemRangeByRank(setId, minRank, maxRank);
}
public long RemoveRangeFromSortedSetByScore(string setId, double fromScore, double toScore)
{
return base.ZRemRangeByScore(setId, fromScore, toScore);
}
public long RemoveRangeFromSortedSetByScore(string setId, long fromScore, long toScore)
{
return base.ZRemRangeByScore(setId, fromScore, toScore);
}
public long GetSortedSetCount(string setId)
{
return base.ZCard(setId);
}
public long GetSortedSetCount(string setId, string fromStringScore, string toStringScore)
{
var fromScore = GetLexicalScore(fromStringScore);
var toScore = GetLexicalScore(toStringScore);
return GetSortedSetCount(setId, fromScore, toScore);
}
public long GetSortedSetCount(string setId, double fromScore, double toScore)
{
return base.ZCount(setId, fromScore, toScore);
}
public long GetSortedSetCount(string setId, long fromScore, long toScore)
{
return base.ZCount(setId, fromScore, toScore);
}
public double GetItemScoreInSortedSet(string setId, string value)
{
return base.ZScore(setId, value.ToUtf8Bytes());
}
public long StoreIntersectFromSortedSets(string intoSetId, params string[] setIds)
{
return base.ZInterStore(intoSetId, setIds);
}
public long StoreUnionFromSortedSets(string intoSetId, params string[] setIds)
{
return base.ZUnionStore(intoSetId, setIds);
}
}
}
| |
/*
* 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.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Collections.Generic;
using OpenMetaverse;
using log4net;
using OpenSim.Framework;
namespace OpenSim.Data.MSSQL
{
/// <summary>
/// A MSSQL Interface for the Asset server
/// </summary>
public class MSSQLAssetData : AssetDataBase
{
private const string _migrationStore = "AssetStore";
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private long m_ticksToEpoch;
/// <summary>
/// Database manager
/// </summary>
private MSSQLManager m_database;
private string m_connectionString;
#region IPlugin Members
override public void Dispose() { }
/// <summary>
/// <para>Initialises asset interface</para>
/// </summary>
// [Obsolete("Cannot be default-initialized!")]
override public void Initialise()
{
m_log.Info("[MSSQLAssetData]: " + Name + " cannot be default-initialized!");
throw new PluginNotInitialisedException(Name);
}
/// <summary>
/// Initialises asset interface
/// </summary>
/// <para>
/// a string instead of file, if someone writes the support
/// </para>
/// <param name="connectionString">connect string</param>
override public void Initialise(string connectionString)
{
m_ticksToEpoch = new System.DateTime(1970, 1, 1).Ticks;
m_database = new MSSQLManager(connectionString);
m_connectionString = connectionString;
//New migration to check for DB changes
m_database.CheckMigration(_migrationStore);
}
/// <summary>
/// Database provider version.
/// </summary>
override public string Version
{
get { return m_database.getVersion(); }
}
/// <summary>
/// The name of this DB provider.
/// </summary>
override public string Name
{
get { return "MSSQL Asset storage engine"; }
}
#endregion
#region IAssetDataPlugin Members
/// <summary>
/// Fetch Asset from m_database
/// </summary>
/// <param name="assetID">the asset UUID</param>
/// <returns></returns>
override public AssetBase GetAsset(UUID assetID)
{
string sql = "SELECT * FROM assets WHERE id = @id";
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("id", assetID));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
AssetBase asset = new AssetBase(
DBGuid.FromDB(reader["id"]),
(string)reader["name"],
Convert.ToSByte(reader["assetType"]),
reader["creatorid"].ToString()
);
// Region Main
asset.Description = (string)reader["description"];
asset.Local = Convert.ToBoolean(reader["local"]);
asset.Temporary = Convert.ToBoolean(reader["temporary"]);
asset.Flags = (AssetFlags)(Convert.ToInt32(reader["asset_flags"]));
asset.Data = (byte[])reader["data"];
return asset;
}
return null; // throw new Exception("No rows to return");
}
}
}
/// <summary>
/// Create asset in m_database
/// </summary>
/// <param name="asset">the asset</param>
override public void StoreAsset(AssetBase asset)
{
string sql =
@"IF EXISTS(SELECT * FROM assets WHERE id=@id)
UPDATE assets set name = @name, description = @description, assetType = @assetType,
local = @local, temporary = @temporary, creatorid = @creatorid, data = @data
WHERE id=@id
ELSE
INSERT INTO assets
([id], [name], [description], [assetType], [local],
[temporary], [create_time], [access_time], [creatorid], [asset_flags], [data])
VALUES
(@id, @name, @description, @assetType, @local,
@temporary, @create_time, @access_time, @creatorid, @asset_flags, @data)";
string assetName = asset.Name;
if (asset.Name.Length > 64)
{
assetName = asset.Name.Substring(0, 64);
m_log.WarnFormat(
"[ASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add",
asset.Name, asset.ID, asset.Name.Length, assetName.Length);
}
string assetDescription = asset.Description;
if (asset.Description.Length > 64)
{
assetDescription = asset.Description.Substring(0, 64);
m_log.WarnFormat(
"[ASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add",
asset.Description, asset.ID, asset.Description.Length, assetDescription.Length);
}
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand command = new SqlCommand(sql, conn))
{
int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000);
command.Parameters.Add(m_database.CreateParameter("id", asset.FullID));
command.Parameters.Add(m_database.CreateParameter("name", assetName));
command.Parameters.Add(m_database.CreateParameter("description", assetDescription));
command.Parameters.Add(m_database.CreateParameter("assetType", asset.Type));
command.Parameters.Add(m_database.CreateParameter("local", asset.Local));
command.Parameters.Add(m_database.CreateParameter("temporary", asset.Temporary));
command.Parameters.Add(m_database.CreateParameter("access_time", now));
command.Parameters.Add(m_database.CreateParameter("create_time", now));
command.Parameters.Add(m_database.CreateParameter("asset_flags", (int)asset.Flags));
command.Parameters.Add(m_database.CreateParameter("creatorid", asset.Metadata.CreatorID));
command.Parameters.Add(m_database.CreateParameter("data", asset.Data));
conn.Open();
try
{
command.ExecuteNonQuery();
}
catch(Exception e)
{
m_log.Error("[ASSET DB]: Error storing item :" + e.Message);
}
}
}
// Commented out since currently unused - this probably should be called in GetAsset()
// private void UpdateAccessTime(AssetBase asset)
// {
// using (AutoClosingSqlCommand cmd = m_database.Query("UPDATE assets SET access_time = @access_time WHERE id=@id"))
// {
// int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000);
// cmd.Parameters.AddWithValue("@id", asset.FullID.ToString());
// cmd.Parameters.AddWithValue("@access_time", now);
// try
// {
// cmd.ExecuteNonQuery();
// }
// catch (Exception e)
// {
// m_log.Error(e.ToString());
// }
// }
// }
/// <summary>
/// Check if asset exist in m_database
/// </summary>
/// <param name="uuid"></param>
/// <returns>true if exist.</returns>
override public bool ExistsAsset(UUID uuid)
{
if (GetAsset(uuid) != null)
{
return true;
}
return false;
}
/// <summary>
/// Returns a list of AssetMetadata objects. The list is a subset of
/// the entire data set offset by <paramref name="start" /> containing
/// <paramref name="count" /> elements.
/// </summary>
/// <param name="start">The number of results to discard from the total data set.</param>
/// <param name="count">The number of rows the returned list should contain.</param>
/// <returns>A list of AssetMetadata objects.</returns>
public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
{
List<AssetMetadata> retList = new List<AssetMetadata>(count);
string sql = @"WITH OrderedAssets AS
(
SELECT id, name, description, assetType, temporary, creatorid,
RowNumber = ROW_NUMBER() OVER (ORDER BY id)
FROM assets
)
SELECT *
FROM OrderedAssets
WHERE RowNumber BETWEEN @start AND @stop;";
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("start", start));
cmd.Parameters.Add(m_database.CreateParameter("stop", start + count - 1));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
AssetMetadata metadata = new AssetMetadata();
metadata.FullID = DBGuid.FromDB(reader["id"]);
metadata.Name = (string)reader["name"];
metadata.Description = (string)reader["description"];
metadata.Type = Convert.ToSByte(reader["assetType"]);
metadata.Temporary = Convert.ToBoolean(reader["temporary"]);
metadata.CreatorID = (string)reader["creatorid"];
retList.Add(metadata);
}
}
}
return retList;
}
public override bool Delete(string id)
{
return false;
}
#endregion
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace DbgEng.NoExceptions
{
/// <summary>
/// Extension of IDebugClient interface.
/// </summary>
/// <seealso cref="DbgEng.IDebugClient3" />
[ComImport, Guid("CA83C3DE-5089-4CF8-93C8-D892387F2A5E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IDebugClient4 : IDebugClient3
{
#pragma warning disable CS0108 // XXX hides inherited member. This is COM default.
#region IDebugClient
/// <summary>
/// The AttachKernel methods connect the debugger engine to a kernel target.
/// </summary>
/// <param name="Flags">Specifies the flags that control how the debugger attaches to the kernel target.</param>
/// <param name="ConnectOptions">Specifies the connection settings for communicating with the computer running the kernel target.</param>
[PreserveSig]
int AttachKernel(
[In] DebugAttachKernel Flags,
[In, MarshalAs(UnmanagedType.LPStr)] string ConnectOptions = null);
/// <summary>
/// The GetKernelConnectionOptions method returns the connection options for the current kernel target.
/// </summary>
/// <param name="Buffer">Specifies the buffer to receive the connection options.</param>
/// <param name="BufferSize">Specifies the size in characters of the buffer Buffer.</param>
/// <param name="OptionsSize">Receives the size in characters of the connection options.</param>
[PreserveSig]
int GetKernelConnectionOptions(
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer,
[In] uint BufferSize,
[Out] out uint OptionsSize);
/// <summary>
/// The SetKernelConnectionOptions method updates some of the connection options for a live kernel target.
/// </summary>
/// <param name="Options">
/// Specifies the connection options to update. The possible values are:
/// <para><c>"resync"</c> Re-synchronize the connection between the debugger engine and the kernel.For more information, see Synchronizing with the Target Computer.</para>
/// <para><c>"cycle_speed"</c> For kernel connections through a COM port, cycle through the supported baud rates; for other connections, do nothing.</para>
/// </param>
[PreserveSig]
int SetKernelConnectionOptions(
[In, MarshalAs(UnmanagedType.LPStr)] string Options);
/// <summary>
/// The StartProcessServer method starts a process server.
/// </summary>
/// <param name="Flags">Specifies the class of the targets that will be available through the process server. This must be set to <see cref="DebugClass.UserWindows"/>.</param>
/// <param name="Options">Specifies the connections options for this process server. These are the same options given to the -t option of the DbgSrv command line.</param>
/// <param name="Reserved">Set to <see cref="IntPtr.Zero"/>.</param>
[PreserveSig]
int StartProcessServer(
[In] DebugClass Flags,
[In, MarshalAs(UnmanagedType.LPStr)] string Options,
[In] IntPtr Reserved = default(IntPtr));
/// <summary>
/// The ConnectProcessServer methods connect to a process server.
/// </summary>
/// <param name="RemoteOptions">Specifies how the debugger engine will connect with the process server. These are the same options passed to the -premote option on the WinDbg and CDB command lines.</param>
/// <param name="Server">A handle for the process server. This handle is used when creating or attaching to processes by using the process server.</param>
[PreserveSig]
int ConnectProcessServer(
[In, MarshalAs(UnmanagedType.LPStr)] string RemoteOptions,
[Out] out ulong Server);
/// <summary>
/// The DisconnectProcessServer method disconnects the debugger engine from a process server.
/// </summary>
/// <param name="Server">Specifies the server from which to disconnect. This handle must have been previously returned by <see cref="ConnectProcessServer"/>.</param>
[PreserveSig]
int DisconnectProcessServer(
[In] ulong Server);
/// <summary>
/// The GetRunningProcessSystemIds method returns the process IDs for each running process.
/// </summary>
/// <param name="Server">Specifies the process server to query for process IDs. If Server is zero, the engine will return the process IDs of the processes running on the local computer.</param>
/// <param name="Ids">Receives the process IDs. The size of this array is <paramref name="Count"/>. If <paramref name="Ids"/> is <c>null</c>, this information is not returned.</param>
/// <param name="Count">Specifies the number of process IDs the array <paramref name="Ids"/> can hold.</param>
/// <param name="ActualCount">Receives the actual number of process IDs returned in <paramref name="Ids"/>.</param>
[PreserveSig]
int GetRunningProcessSystemIds(
[In] ulong Server,
[Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] Ids,
[In] uint Count,
[Out] out uint ActualCount);
/// <summary>
/// The GetRunningProcessSystemIdByExecutableName method searches for a process with a given executable file name and return its process ID.
/// </summary>
/// <param name="Server">Specifies the process server to search for the executable name. If Server is zero, the engine will search for the executable name among the processes running on the local computer.</param>
/// <param name="ExeName">Specifies the executable file name for which to search.</param>
/// <param name="Flags">Specifies a bit-set that controls how the executable name is matched.</param>
/// <param name="Id">The process ID of the first process to match <paramref name="ExeName"/>.</param>
[PreserveSig]
int GetRunningProcessSystemIdByExecutableName(
[In] ulong Server,
[In, MarshalAs(UnmanagedType.LPStr)] string ExeName,
[In] DebugGetProc Flags,
[Out] out uint Id);
/// <summary>
/// The GetRunningProcessDescription method returns a description of the process that includes the executable image name, the service names, the MTS package names, and the command line.
/// </summary>
/// <param name="Server">Specifies the process server to query for the process description. If Server is zero, the engine will query information about the local process directly.</param>
/// <param name="SystemId">Specifies the process ID of the process whose description is desired.</param>
/// <param name="Flags">Specifies a bit-set containing options that affect the behavior of this method.</param>
/// <param name="ExeName">Receives the name of the executable file used to start the process. If ExeName is <c>null</c>, this information is not returned.</param>
/// <param name="ExeNameSize">Specifies the size in characters of the buffer <paramref name="ExeName"/>.</param>
/// <param name="ActualExeNameSize">Receives the size in characters of the executable file name.</param>
/// <param name="Description">Receives extra information about the process, including service names, MTS package names, and the command line. If Description is <c>null</c>, this information is not returned.</param>
/// <param name="DescriptionSize">Specifies the size in characters of the buffer <paramref name="Description"/>.</param>
/// <param name="ActualDescriptionSize">Receives the size in characters of the extra information.</param>
[PreserveSig]
int GetRunningProcessDescription(
[In] ulong Server,
[In] uint SystemId,
[In] DebugProcDesc Flags,
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder ExeName,
[In] uint ExeNameSize,
[Out] out uint ActualExeNameSize,
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Description,
[In] uint DescriptionSize,
[Out] out uint ActualDescriptionSize);
/// <summary>
/// The AttachProcess method connects the debugger engine to a user-modeprocess.
/// </summary>
/// <param name="Server">Specifies the process server to use to attach to the process. If Server is zero, the engine will connect to a local process without using a process server.</param>
/// <param name="ProcessId">Specifies the process ID of the target process the debugger will attach to.</param>
/// <param name="AttachFlags">Specifies the flags that control how the debugger attaches to the target process.</param>
[PreserveSig]
int AttachProcess(
[In] ulong Server,
[In] uint ProcessId,
[In] DebugAttach AttachFlags);
/// <summary>
/// The CreateProcess method creates a process from the specified command line.
/// </summary>
/// <param name="Server">Specifies the process server to use to attach to the process. If Server is zero, the engine will create a local process without using a process server.</param>
/// <param name="CommandLine">Specifies the command line to execute to create the new process.</param>
/// <param name="CreateFlags">Specifies the flags to use when creating the process. When creating and attaching to a process through the debugger engine, set one of the Platform SDK's process creation flags: <see cref="DebugCreateProcess.DebugProcess"/> or <see cref="DebugCreateProcess.DebugOnlyThisProcess"/>.</param>
[PreserveSig]
int CreateProcess(
[In] ulong Server,
[In, MarshalAs(UnmanagedType.LPStr)] string CommandLine,
[In] DebugCreateProcess CreateFlags);
/// <summary>
/// The CreateProcessAndAttach method creates a process from a specified command line, then attach to another user-mode process. The created process is suspended and only allowed to execute when the attach has completed. This allows rough synchronization when debugging both, client and server processes.
/// </summary>
/// <param name="Server">Specifies the process server to use to attach to the process. If Server is zero, the engine will connect to the local process without using a process server.</param>
/// <param name="CommandLine">Specifies the command line to execute to create the new process. If CommandLine is <c>null</c>, then no process is created and these methods attach to an existing process, as <see cref="AttachProcess"/> does.</param>
/// <param name="CreateFlags">Specifies the flags to use when creating the process. When creating and attaching to a process through the debugger engine, set one of the Platform SDK's process creation flags: <see cref="DebugCreateProcess.DebugProcess"/> or <see cref="DebugCreateProcess.DebugOnlyThisProcess"/>.</param>
/// <param name="ProcessId">Specifies the process ID of the target process the debugger will attach to. If ProcessId is zero, the debugger will attach to the process it created from CommandLine.</param>
/// <param name="AttachFlags">Specifies the flags that control how the debugger attaches to the target process.</param>
[PreserveSig]
int CreateProcessAndAttach(
[In] ulong Server,
[In, MarshalAs(UnmanagedType.LPStr)] string CommandLine,
[In] DebugCreateProcess CreateFlags,
[In] uint ProcessId,
[In] DebugAttach AttachFlags);
/// <summary>
/// The GetProcessOptions method retrieves the process options affecting the current process.
/// </summary>
/// <param name="Options">Receives a set of flags representing the process options for the current process.</param>
[PreserveSig]
int GetProcessOptions(
[Out] out DebugProcess Options);
/// <summary>
/// The AddProcessOptions method adds the process options to those options that affect the current process.
/// </summary>
/// <param name="Options">Specifies the process options to add to those affecting the current process.</param>
[PreserveSig]
int AddProcessOptions(
[In] DebugProcess Options);
/// <summary>
/// The RemoveProcessOptions method removes process options from those options that affect the current process.
/// </summary>
/// <param name="Options">Specifies the process options to remove from those affecting the current process.</param>
[PreserveSig]
int RemoveProcessOptions(
[In] DebugProcess Options);
/// <summary>
/// The SetProcessOptions method sets the process options affecting the current process.
/// </summary>
/// <param name="Options">Specifies a set of flags that will become the new process options for the current process.</param>
[PreserveSig]
int SetProcessOptions(
[In] DebugProcess Options);
/// <summary>
/// The OpenDumpFile method opens a dump file as a debugger target.
/// <note> The engine doesn't completely attach to the dump file until the <see cref="IDebugControl.WaitForEvent"/> method has been called. When a dump file is created from a process or kernel, information about the last event is stored in the dump file. After the dump file is opened, the next time execution is attempted, the engine will generate this event for the event callbacks. Only then does the dump file become available in the debugging session.</note>
/// </summary>
/// <param name="DumpFile">Specifies the name of the dump file to open. DumpFile must include the file name extension. DumpFile can include a relative or absolute path; relative paths are relative to the directory in which the debugger was started. DumpFile can have the form of a file URL, starting with "file://". If DumpFile specifies a cabinet (.cab) file, the cabinet file is searched for the first file with extension .kdmp, then .hdmp, then .mdmp, and finally .dmp.</param>
[PreserveSig]
int OpenDumpFile(
[In, MarshalAs(UnmanagedType.LPStr)] string DumpFile);
/// <summary>
/// The WriteDumpFile method creates a user-mode or kernel-modecrash dump file.
/// </summary>
/// <param name="DumpFile">Specifies the name of the dump file to create. DumpFile must include the file name extension. DumpFile can include a relative or absolute path; relative paths are relative to the directory in which the debugger was started.</param>
/// <param name="Qualifier">Specifies the type of dump file to create.</param>
[PreserveSig]
int WriteDumpFile(
[In, MarshalAs(UnmanagedType.LPStr)] string DumpFile,
[In] DebugDump Qualifier);
/// <summary>
/// The ConnectSession method joins the client to an existing debugger session.
/// </summary>
/// <param name="Flags">Specifies a bit-set of option flags for connecting to the session.</param>
/// <param name="HistoryLimit">Specifies the maximum number of characters from the session's history to send to this client's output upon connection.</param>
[PreserveSig]
int ConnectSession(
[In] DebugConnectSession Flags,
[In] uint HistoryLimit);
/// <summary>
/// The StartServer method starts a debugging server.
/// </summary>
/// <param name="Options">Specifies the connections options for this server. These are the same options given to the .server debugger command or the WinDbg and CDB -server command-line option. For details on the syntax of this string, see Activating a Debugging Server.</param>
/// <remarks>The server that is started will be accessible by other debuggers through the transport specified in the Options parameter.</remarks>
[PreserveSig]
int StartServer(
[In, MarshalAs(UnmanagedType.LPStr)] string Options);
/// <summary>
/// The OutputServers method lists the servers running on a given computer.
/// </summary>
/// <param name="OutputControl">Specifies the output control to use while outputting the servers.</param>
/// <param name="Machine">Specifies the name of the computer whose servers will be listed. Machine has the following form: \\computername </param>
/// <param name="Flags">Specifies a bit-set that determines which servers to output.</param>
[PreserveSig]
int OutputServers(
[In] DebugOutctl OutputControl,
[In, MarshalAs(UnmanagedType.LPStr)] string Machine,
[In] DebugServers Flags);
/// <summary>
/// Attempts to terminate all processes in all targets.
/// </summary>
[PreserveSig]
int TerminateProcesses();
/// <summary>
/// Detaches the debugger engine from all processes in all targets, resuming all their threads.
/// </summary>
[PreserveSig]
int DetachProcesses();
/// <summary>
/// The EndSession method ends the current debugger session.
/// </summary>
/// <param name="Flags">Specifies how to end the session.</param>
[PreserveSig]
int EndSession(
[In] DebugEnd Flags);
/// <summary>
/// The GetExitCode method returns the exit code of the current process if that process has already run through to completion.
/// </summary>
/// <param name="Code">The exit code of the process. If the process is still running, Code will be set to STILL_ACTIVE.</param>
[PreserveSig]
int GetExitCode(
[Out] out uint Code);
/// <summary>
/// The DispatchCallbacks method lets the debugger engine use the current thread for callbacks.
/// </summary>
/// <param name="Timeout">Specifies how many milliseconds to wait before this method will return. If Timeout is uint.MaxValue, this method will not return until <see cref="IDebugClient.ExitDispatch"/> is called or an error occurs.</param>
[PreserveSig]
int DispatchCallbacks(
[In] uint Timeout);
/// <summary>
/// The ExitDispatch method causes the <see cref="DispatchCallbacks"/> method to return.
/// </summary>
/// <param name="Client">Specifies the client whose <see cref="DispatchCallbacks"/> method should return.</param>
[PreserveSig]
int ExitDispatch(
[In, MarshalAs(UnmanagedType.Interface)] IDebugClient Client);
/// <summary>
/// The CreateClient method creates a new client object for the current thread.
/// </summary>
/// <param name="Client">Receives an interface pointer for the new client.</param>
[PreserveSig]
int CreateClient(
[Out, MarshalAs(UnmanagedType.Interface)] out IDebugClient Client);
/// <summary>
/// The GetInputCallbacks method returns the input callbacks object registered with this client.
/// </summary>
/// <param name="Callbacks">Receives an interface pointer for the <see cref="IDebugInputCallbacks"/> object registered with the client.</param>
[PreserveSig]
int GetInputCallbacks(
[Out, MarshalAs(UnmanagedType.Interface)] out IDebugInputCallbacks Callbacks);
/// <summary>
/// The SetInputCallbacks method registers an input callbacks object with the client.
/// </summary>
/// <param name="Callbacks">Specifies the interface pointer to the input callbacks object to register with this client.</param>
[PreserveSig]
int SetInputCallbacks(
[In, MarshalAs(UnmanagedType.Interface)] IDebugInputCallbacks Callbacks = null);
/// <summary>
/// The GetOutputCallbacks method returns the output callbacks object registered with the client.
/// </summary>
/// <param name="Callbacks">Receives an interface pointer to the <see cref="IDebugOutputCallbacks"/> object registered with the client.</param>
[PreserveSig]
int GetOutputCallbacks(
[Out, MarshalAs(UnmanagedType.Interface)] out IDebugOutputCallbacks Callbacks);
/// <summary>
/// The SetOutputCallbacks method registers an output callbacks object with this client.
/// </summary>
/// <param name="Callbacks">Specifies the interface pointer to the output callbacks object to register with this client.</param>
[PreserveSig]
int SetOutputCallbacks(
[In, MarshalAs(UnmanagedType.Interface)] IDebugOutputCallbacks Callbacks = null);
/// <summary>
/// The GetOutputMask method returns the output mask currently set for the client.
/// </summary>
/// <param name="Mask">Receives the output mask for the client.</param>
[PreserveSig]
int GetOutputMask(
[Out] out DebugOutput Mask);
/// <summary>
/// The SetOutputMask method sets the output mask for the client.
/// </summary>
/// <param name="Mask">Specifies the new output mask for the client.</param>
[PreserveSig]
int SetOutputMask(
[In] DebugOutput Mask);
/// <summary>
/// The GetOtherOutputMask method returns the output mask for another client.
/// </summary>
/// <param name="Client">Specifies the client whose output mask is desired.</param>
/// <param name="Mask">Receives the output mask for the client.</param>
[PreserveSig]
int GetOtherOutputMask(
[In, MarshalAs(UnmanagedType.Interface)] IDebugClient Client,
[Out] out DebugOutput Mask);
/// <summary>
/// The SetOtherOutputMask method sets the output mask for another client.
/// </summary>
/// <param name="Client">Specifies the client whose output mask will be set.</param>
/// <param name="Mask">Specifies the new output mask for the client.</param>
[PreserveSig]
int SetOtherOutputMask(
[In, MarshalAs(UnmanagedType.Interface)] IDebugClient Client,
[In] DebugOutput Mask);
/// <summary>
/// Undocumented on MSDN.
/// </summary>
/// <param name="Columns"></param>
[PreserveSig]
int GetOutputWidth(
[Out] out uint Columns);
/// <summary>
/// Undocumented on MSDN.
/// </summary>
/// <param name="Columns"></param>
[PreserveSig]
int SetOutputWidth(
[In] uint Columns);
/// <summary>
/// Undocumented on MSDN.
/// </summary>
/// <param name="Buffer"></param>
/// <param name="BufferSize"></param>
/// <param name="PrefixSize"></param>
[PreserveSig]
int GetOutputLinePrefix(
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer,
[In] uint BufferSize,
[Out] out uint PrefixSize);
/// <summary>
/// Undocumented on MSDN.
/// </summary>
/// <param name="Prefix"></param>
[PreserveSig]
int SetOutputLinePrefix(
[In, MarshalAs(UnmanagedType.LPStr)] string Prefix = null);
/// <summary>
/// The GetIdentity method returns a string describing the computer and user this client represents.
/// </summary>
/// <param name="Buffer">Specifies the buffer to receive the string. If <paramref name="Buffer"/> is <c>null</c>, this information is not returned.</param>
/// <param name="BufferSize">Specifies the size of the buffer <paramref name="Buffer"/>.</param>
/// <param name="IdentitySize">Receives the size of the string.</param>
[PreserveSig]
int GetIdentity(
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer,
[In] uint BufferSize,
[Out] out uint IdentitySize);
/// <summary>
/// The OutputIdentity method formats and outputs a string describing the computer and user this client represents.
/// </summary>
/// <param name="OutputControl">Specifies where to send the output.</param>
/// <param name="Flags">Set to zero.</param>
/// <param name="Format">Specifies a format string similar to the printf format string. However, this format string must only contain one formatting directive, %s, which will be replaced by a description of the computer and user this client represents.</param>
[PreserveSig]
int OutputIdentity(
[In] DebugOutctl OutputControl,
[In] uint Flags,
[In, MarshalAs(UnmanagedType.LPStr)] string Format);
/// <summary>
/// The GetEventCallbacks method returns the event callbacks object registered with this client.
/// </summary>
/// <param name="Callbacks">Receives an interface pointer to the event callbacks object registered with this client.</param>
[PreserveSig]
int GetEventCallbacks(
[Out, MarshalAs(UnmanagedType.Interface)] out IDebugEventCallbacks Callbacks);
/// <summary>
/// The SetEventCallbacks method registers an event callbacks object with this client.
/// </summary>
/// <param name="Callbacks">Specifies the interface pointer to the event callbacks object to register with this client.</param>
[PreserveSig]
int SetEventCallbacks(
[In, MarshalAs(UnmanagedType.Interface)] IDebugEventCallbacks Callbacks = null);
/// <summary>
/// Forces any remaining buffered output to be delivered to the <see cref="IDebugOutputCallbacks"/> object registered with this client.
/// </summary>
[PreserveSig]
int FlushCallbacks();
#endregion
#region IDebugClient2
/// <summary>
/// The WriteDumpFile2 method creates a user-mode or kernel-modecrash dump file.
/// </summary>
/// <param name="DumpFile">Specifies the name of the dump file to create. DumpFile must include the file name extension. DumpFile can include a relative or absolute path; relative paths are relative to the directory in which the debugger was started.</param>
/// <param name="Qualifier">Specifies the type of dump file to create.</param>
/// <param name="FormatFlags">Specifies flags that determine the format of the dump file and--for user-mode minidumps--what information to include in the file.</param>
/// <param name="Comment">Specifies a comment string to be included in the crash dump file. This string is displayed in the debugger console when the dump file is loaded. Some dump file formats do not support the storing of comment strings.</param>
[PreserveSig]
int WriteDumpFile2(
[In, MarshalAs(UnmanagedType.LPStr)] string DumpFile,
[In] DebugDump Qualifier,
[In] DebugFormat FormatFlags,
[In, MarshalAs(UnmanagedType.LPStr)] string Comment = null);
/// <summary>
/// The AddDumpInformationFile method registers additional files containing supporting information that will be used when opening a dump file.
/// <note>ANSI version.</note>
/// </summary>
/// <param name="InfoFile">Specifies the name of the file containing the supporting information.</param>
/// <param name="Type">Specifies the type of the file InfoFile. Currently, only files containing paging file information are supported, and Type must be set to <see cref="DebugDumpFile.PageFileDump"/>.</param>
[PreserveSig]
int AddDumpInformationFile(
[In, MarshalAs(UnmanagedType.LPStr)] string InfoFile,
[In] DebugDumpFile Type);
/// <summary>
/// The EndProcessServer method requests that a process server be shut down.
/// </summary>
/// <param name="Server">Specifies the process server to shut down. This handle must have been previously returned by <see cref="IDebugClient.ConnectProcessServer"/>.</param>
[PreserveSig]
int EndProcessServer(
[In] ulong Server);
/// <summary>
/// The WaitForProcessServerEnd method waits for a local process server to exit.
/// </summary>
/// <param name="Timeout">Specifies how long in milliseconds to wait for a process server to exit. If Timeout is uint.MaxValue, this method will not return until a process server has ended.</param>
[PreserveSig]
int WaitForProcessServerEnd(
[In] uint Timeout);
/// <summary>
/// The IsKernelDebuggerEnabled method checks whether kernel debugging is enabled for the local kernel.
/// </summary>
/// <returns>S_OK if kernel debugging is enabled for the local kernel; S_FALSE otherwise.</returns>
[PreserveSig]
int IsKernelDebuggerEnabled();
/// <summary>
/// The TerminateCurrentProcess method attempts to terminate the current process.
/// </summary>
[PreserveSig]
int TerminateCurrentProcess();
/// <summary>
/// The DetachCurrentProcess method detaches the debugger engine from the current process, resuming all its threads.
/// </summary>
[PreserveSig]
int DetachCurrentProcess();
/// <summary>
/// The AbandonCurrentProcess method removes the current process from the debugger engine's process list without detaching or terminating the process.
/// </summary>
[PreserveSig]
int AbandonCurrentProcess();
#endregion
#region IDebugClient3
/// <summary>
/// The GetRunningProcessSystemIdByExecutableNameWide method searches for a process with a given executable file name and return its process ID.
/// <note>Unicode version</note>
/// </summary>
/// <param name="Server">Specifies the process server to search for the executable name. If Server is zero, the engine will search for the executable name among the processes running on the local computer.</param>
/// <param name="ExeName">Specifies the executable file name for which to search.</param>
/// <param name="Flags">Specifies a bit-set that controls how the executable name is matched.</param>
/// <param name="Id">Receives the process ID of the first process to match <paramref name="ExeName"/>.</param>
[PreserveSig]
int GetRunningProcessSystemIdByExecutableNameWide(
[In] ulong Server,
[In, MarshalAs(UnmanagedType.LPWStr)] string ExeName,
[In] DebugGetProc Flags,
[Out] out uint Id);
/// <summary>
/// The GetRunningProcessDescriptionWide method returns a description of the process that includes the executable image name, the service names, the MTS package names, and the command line.
/// <note>Unicode version</note>
/// </summary>
/// <param name="Server">Specifies the process server to query for the process description. If Server is zero, the engine will query information about the local process directly.</param>
/// <param name="SystemId">Specifies the process ID of the process whose description is desired.</param>
/// <param name="Flags">Specifies a bit-set containing options that affect the behavior of this method.</param>
/// <param name="ExeName">Receives the name of the executable file used to start the process. If ExeName is <c>null</c>, this information is not returned.</param>
/// <param name="ExeNameSize">Specifies the size in characters of the buffer <paramref name="ExeName"/>.</param>
/// <param name="ActualExeNameSize">Receives the size in characters of the executable file name.</param>
/// <param name="Description">Receives extra information about the process, including service names, MTS package names, and the command line. If Description is <c>null</c>, this information is not returned.</param>
/// <param name="DescriptionSize">Specifies the size in characters of the buffer <paramref name="Description"/>.</param>
/// <param name="ActualDescriptionSize">Receives the size in characters of the extra information.</param>
[PreserveSig]
int GetRunningProcessDescriptionWide(
[In] ulong Server,
[In] uint SystemId,
[In] DebugProcDesc Flags,
[Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder ExeName,
[In] uint ExeNameSize,
[Out] out uint ActualExeNameSize,
[Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Description,
[In] uint DescriptionSize,
[Out] out uint ActualDescriptionSize);
/// <summary>
/// The CreateProcessWide method creates a process from the specified command line.
/// <note>Unicode version</note>
/// </summary>
/// <param name="Server">Specifies the process server to use when attaching to the process. If Server is zero, the engine will create a local process without using a process server.</param>
/// <param name="CommandLine">Specifies the command line to execute to create the new process. The CreateProcessWide method might modify the contents of the string that you supply in this parameter. Therefore, this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string). Passing a constant string in this parameter can lead to an access violation.</param>
/// <param name="CreateFlags">Specifies the flags to use when creating the process.</param>
[PreserveSig]
int CreateProcessWide(
[In] ulong Server,
[In, MarshalAs(UnmanagedType.LPWStr)] string CommandLine,
[In] DebugCreateProcess CreateFlags);
/// <summary>
/// The CreateProcessAndAttachWide method creates a process from a specified command line, then attach to another user-mode process. The created process is suspended and only allowed to execute when the attach has completed. This allows rough synchronization when debugging both, client and server processes.
/// </summary>
/// <param name="Server">Specifies the process server to use to attach to the process. If Server is zero, the engine will connect to the local process without using a process server.</param>
/// <param name="CommandLine">Specifies the command line to execute to create the new process. If <paramref name="CommandLine"/> is <c>null</c>, then no process is created and these methods attach to an existing process, as <see cref="IDebugClient.AttachProcess"/> does.</param>
/// <param name="CreateFlags">Specifies the flags to use when creating the process.</param>
/// <param name="ProcessId">Specifies the process ID of the target process the debugger will attach to. If <paramref name="ProcessId"/> is zero, the debugger will attach to the process it created from <paramref name="CommandLine"/>.</param>
/// <param name="AttachFlags">Specifies the flags that control how the debugger attaches to the target process.</param>
[PreserveSig]
int CreateProcessAndAttachWide(
[In] ulong Server,
[In, MarshalAs(UnmanagedType.LPWStr)] string CommandLine,
[In] DebugCreateProcess CreateFlags,
[In] uint ProcessId,
[In] DebugAttach AttachFlags);
#endregion
#pragma warning restore CS0108 // XXX hides inherited member. This is COM default.
/// <summary>
/// The OpenDumpFileWide method opens a dump file as a debugger target.
/// <note>Unicode version</note>
/// </summary>
/// <param name="FileName">Specifies the name of the dump file to open -- unless <paramref name="FileHandle"/> is not zero, in which case <paramref name="FileName"/> is used only when the engine is queried for the name of the dump file. <paramref name="FileName"/> must include the file name extension. <paramref name="FileName"/> can include a relative or absolute path; relative paths are relative to the directory in which the debugger was started. <paramref name="FileName"/> can also be in the form of a file URL, starting with "file://". If <paramref name="FileName"/> specifies a cabinet (.cab) file, the cabinet file is searched for the first file with extension .kdmp, then .hdmp, then .mdmp, and finally .dmp.</param>
/// <param name="FileHandle">Specifies the file handle of the dump file to open. If <paramref name="FileHandle"/> is zero, <paramref name="FileName"/> is used to open the dump file. Otherwise, if <paramref name="FileName"/> is not <c>null</c>, the engine returns it when queried for the name of the dump file. If <paramref name="FileHandle"/> is not zero and <paramref name="FileName"/> is <c>null</c>, the engine will return <HandleOnly> for the file name.</param>
[PreserveSig]
int OpenDumpFileWide(
[In, MarshalAs(UnmanagedType.LPWStr)] string FileName = null,
[In] ulong FileHandle = default(ulong));
/// <summary>
/// The WriteDumpFileWide method creates a user-mode or kernel-modecrash dump file.
/// <note>Unicode version.</note>
/// </summary>
/// <param name="FileName">Specifies the name of the dump file to create. <paramref name="FileName"/> must include the file name extension. <paramref name="FileName"/> can include a relative or absolute path; relative paths are relative to the directory in which the debugger was started. If <paramref name="FileHandle"/> is not 0, <paramref name="FileName"/> is ignored (except when writing status messages to the debugger console).</param>
/// <param name="FileHandle">Specifies the file handle of the file to write the crash dump to. If <paramref name="FileHandle"/> is 0, the file specified in <paramref name="FileName"/> is used instead.</param>
/// <param name="Qualifier">Specifies the type of dump to create.</param>
/// <param name="FormatFlags">Specifies flags that determine the format of the dump file and--for user-mode minidumps--what information to include in the file.</param>
/// <param name="Comment">Specifies a comment string to be included in the crash dump file. This string is displayed in the debugger console when the dump file is loaded.</param>
[PreserveSig]
int WriteDumpFileWide(
[In, MarshalAs(UnmanagedType.LPWStr)] string FileName,
[In] ulong FileHandle = default(ulong),
[In] DebugDump Qualifier = DebugDump.Default,
[In] DebugFormat FormatFlags = DebugFormat.Default,
[In, MarshalAs(UnmanagedType.LPWStr)] string Comment = null);
/// <summary>
/// The AddDumpInformationFileWide method registers additional files containing supporting information that will be used when opening a dump file. The ASCII version of this method is <see cref="IDebugClient2.AddDumpInformationFile"/>.
/// </summary>
/// <param name="FileName">Specifies the name of the file containing the supporting information. If <paramref name="FileHandle"/> is not zero, <paramref name="FileName"/> is used only for informational purposes.</param>
/// <param name="FileHandle">Specifies the handle of the file containing the supporting information. If <paramref name="FileHandle"/> is zero, the file named in <paramref name="FileName"/> is used.</param>
/// <param name="Type">Specifies the type of the file in <paramref name="FileName"/> or <paramref name="FileHandle"/>. Currently, only files containing paging file information are supported, and Type must be set to <see cref="DebugDumpFile.PageFileDump"/>.</param>
[PreserveSig]
int AddDumpInformationFileWide(
[In, Optional, MarshalAs(UnmanagedType.LPWStr)] string FileName,
[In] ulong FileHandle = default(ulong),
[In] DebugDumpFile Type = DebugDumpFile.PageFileDump);
/// <summary>
/// The GetNumberDumpFiles method returns the number of files containing supporting information that were used when opening the current dump target.
/// </summary>
/// <param name="Number">Receives the number of files.</param>
[PreserveSig]
int GetNumberDumpFiles(
[Out] out uint Number);
/// <summary>
/// The GetDumpFileWide method describes the files containing supporting information that were used when opening the current dump target.
/// <note type="note">ANSI version</note>
/// </summary>
/// <param name="Index">Specifies which file to describe. Index can take values between zero and the number of files minus one; the number of files can be found by using <see cref="IDebugClient4.GetNumberDumpFiles"/>.</param>
/// <param name="Buffer">Receives the file name. If <paramref name="Buffer"/> is <c>null</c>, this information is not returned.</param>
/// <param name="BufferSize">Specifies the size in characters of the buffer <paramref name="Buffer"/>.</param>
/// <param name="NameSize">Receives the size of the file name.</param>
/// <param name="Handle">Receives the file handle of the file.</param>
/// <param name="Type">Receives the type of the file.</param>
[PreserveSig]
int GetDumpFile(
[In] uint Index,
[Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer,
[In] uint BufferSize,
[Out] out uint NameSize,
[Out] out ulong Handle,
[Out] out DebugDumpFile Type);
/// <summary>
/// The GetDumpFileWide method describes the files containing supporting information that were used when opening the current dump target.
/// <note type="note">Unicode version</note>
/// </summary>
/// <param name="Index">Specifies which file to describe. Index can take values between zero and the number of files minus one; the number of files can be found by using <see cref="IDebugClient4.GetNumberDumpFiles"/>.</param>
/// <param name="Buffer">Receives the file name. If <paramref name="Buffer"/> is <c>null</c>, this information is not returned.</param>
/// <param name="BufferSize">Specifies the size in characters of the buffer <paramref name="Buffer"/>.</param>
/// <param name="NameSize">Receives the size of the file name.</param>
/// <param name="Handle">Receives the file handle of the file.</param>
/// <param name="Type">Receives the type of the file.</param>
[PreserveSig]
int GetDumpFileWide(
[In] uint Index,
[Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer,
[In] uint BufferSize,
[Out] out uint NameSize,
[Out] out ulong Handle,
[Out] out DebugDumpFile Type);
}
}
| |
// *****************************************************************************
//
// (c) Crownwood Consulting Limited 2002
// All rights reserved. The software and associated documentation
// supplied hereunder are the proprietary information of Crownwood Consulting
// Limited, Haxey, North Lincolnshire, England and are supplied subject to
// licence terms.
//
// IDE Version 1.7 www.dotnetmagic.com
// *****************************************************************************
using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing.Imaging;
using Microsoft.Win32;
using IDE.Common;
using IDE.Controls;
namespace IDE.Docking
{
[ToolboxItem(false)]
internal class WindowDetailCaption : WindowDetail, IMessageFilter
{
// Class fields
protected static ImageList _images;
// Instance events
public event EventHandler Close;
public event EventHandler Restore;
public event EventHandler InvertAutoHide;
public event ContextHandler Context;
// Instance fields
protected InertButton _maxButton;
protected InertButton _closeButton;
protected InertButton _hideButton;
protected RedockerContent _redocker;
protected IZoneMaximizeWindow _maxInterface;
protected bool _showCloseButton;
protected bool _showHideButton;
protected bool _ignoreHideButton;
protected bool _pinnedImage;
// Class fields
protected static ImageAttributes _activeAttr = new ImageAttributes();
protected static ImageAttributes _inactiveAttr = new ImageAttributes();
public WindowDetailCaption(DockingManager manager,
Size fixedSize,
EventHandler closeHandler,
EventHandler restoreHandler,
EventHandler invertAutoHideHandler,
ContextHandler contextHandler)
: base(manager)
{
// Setup correct color remapping depending on initial colors
DefineButtonRemapping();
// Default state
_maxButton = null;
_hideButton = null;
_maxInterface = null;
_redocker = null;
_showCloseButton = true;
_showHideButton = true;
_ignoreHideButton = false;
_pinnedImage = false;
// Prevent flicker with double buffering and all painting inside WM_PAINT
SetStyle(ControlStyles.DoubleBuffer, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
// Our size is always fixed at the required length in both directions
// as one of the sizes will be provided for us because of our docking
this.Size = fixedSize;
if (closeHandler != null)
this.Close += closeHandler;
if (restoreHandler != null)
this.Restore += restoreHandler;
if (invertAutoHideHandler != null)
this.InvertAutoHide += invertAutoHideHandler;
if (contextHandler != null)
this.Context += contextHandler;
// Let derived classes override the button creation
CreateButtons();
// Need to hook into message pump so that the ESCAPE key can be
// intercepted when in redocking mode
Application.AddMessageFilter(this);
}
public override Zone ParentZone
{
set
{
base.ParentZone = value;
RecalculateMaximizeButton();
RecalculateButtons();
}
}
public virtual void OnClose()
{
// Any attached event handlers?
if (Close != null)
Close(this, EventArgs.Empty);
}
public virtual void OnInvertAutoHide()
{
// Any attached event handlers?
if (InvertAutoHide != null)
InvertAutoHide(this, EventArgs.Empty);
}
public virtual void OnRestore()
{
// Any attached event handlers?
if (Restore != null)
Restore(this, EventArgs.Empty);
}
public virtual void OnContext(Point screenPos)
{
// Any attached event handlers?
if (Context != null)
Context(screenPos);
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (_closeButton != null)
{
_closeButton.Click -= new EventHandler(OnButtonClose);
_closeButton.GotFocus -= new EventHandler(OnButtonGotFocus);
}
if (_hideButton != null)
{
_hideButton.Click -= new EventHandler(OnButtonHide);
_hideButton.GotFocus -= new EventHandler(OnButtonGotFocus);
}
if (_maxButton != null)
{
_maxButton.Click -= new EventHandler(OnButtonMax);
_maxButton.GotFocus -= new EventHandler(OnButtonGotFocus);
}
}
base.Dispose( disposing );
}
public override void NotifyAutoHideImage(bool autoHidden)
{
_pinnedImage = autoHidden;
UpdateAutoHideImage();
}
public override void NotifyCloseButton(bool show)
{
_showCloseButton = show;
RecalculateButtons();
}
public override void NotifyHideButton(bool show)
{
// Ignore the AutoHide feature when in floating form
_ignoreHideButton = (_parentWindow.State == State.Floating);
_showHideButton = show;
RecalculateButtons();
}
public override void NotifyShowCaptionBar(bool show)
{
this.Visible = show;
}
protected void RecalculateMaximizeButton()
{
// Are we inside a Zone?
if (this.ParentZone != null)
{
// Does the Zone support the maximizing of a Window?
IZoneMaximizeWindow zmw = this.ParentZone as IZoneMaximizeWindow;
if (zmw != null)
{
AddMaximizeInterface(zmw);
return;
}
}
RemoveMaximizeInterface();
}
protected void AddMaximizeInterface(IZoneMaximizeWindow zmw)
{
// Has the maximize button already been created?
if (_maxInterface == null)
{
// Create the InertButton
_maxButton = new InertButton(_images, 0);
// Hook into button events
_maxButton.Click += new EventHandler(OnButtonMax);
_maxButton.GotFocus += new EventHandler(OnButtonGotFocus);
// Define the default remapping
_maxButton.ImageAttributes = _inactiveAttr;
OnAddMaximizeInterface();
Controls.Add(_maxButton);
// Remember the interface reference
_maxInterface = zmw;
// Hook into the interface change events
_maxInterface.RefreshMaximize += new EventHandler(OnRefreshMaximize);
RecalculateButtons();
}
}
protected void RemoveMaximizeInterface()
{
if (_maxInterface != null)
{
// Unhook from the interface change events
_maxInterface.RefreshMaximize -= new EventHandler(OnRefreshMaximize);
// Remove the interface reference
_maxInterface = null;
// Use helper method to circumvent form Close bug
ControlHelper.Remove(this.Controls, _maxButton);
OnRemoveMaximizeInterface();
// Unhook into button events
_maxButton.Click -= new EventHandler(OnButtonMax);
_maxButton.GotFocus -= new EventHandler(OnButtonGotFocus);
// Kill the button which is no longer needed
_maxButton.Dispose();
_maxButton = null;
RecalculateButtons();
}
}
protected void OnRefreshMaximize(object sender, EventArgs e)
{
UpdateMaximizeImage();
}
protected void OnButtonMax(object sender, EventArgs e)
{
if (this.ParentWindow != null)
{
if (_maxInterface.IsMaximizeAvailable())
{
// Are we already maximized?
if (_maxInterface.IsWindowMaximized(this.ParentWindow))
_maxInterface.RestoreWindow();
else
_maxInterface.MaximizeWindow(this.ParentWindow);
}
}
}
protected void OnButtonClose(Object sender, EventArgs e)
{
if (_showCloseButton)
OnClose();
}
protected void OnButtonHide(Object sender, EventArgs e)
{
// Plain button can still be pressed when disabled, so double check
// that an event should actually be generated
if (_showHideButton && !_ignoreHideButton)
OnInvertAutoHide();
}
protected void OnButtonGotFocus(Object sender, EventArgs e)
{
// Inform parent window we have now got the focus
if (this.ParentWindow != null)
this.ParentWindow.WindowDetailGotFocus(this);
}
protected override void OnDoubleClick(EventArgs e)
{
// The double click event will cause the control to be destroyed as
// the Contents are restored to their alternative positions, so need to
// double check the control is not already dead
if (!IsDisposed)
{
// Are we currently in a redocking state?
if (_redocker != null)
{
// No longer need the object
_redocker = null;
}
}
// Fire attached event handlers
OnRestore();
}
protected override void OnMouseDown(MouseEventArgs e)
{
// The double click event will cause the control to be destroyed as
// the Contents are restored to their alternative positions, so need to
// double check the control is not already dead
if (!IsDisposed)
{
// Left mouse down begins a redocking action
if (e.Button == MouseButtons.Left)
{
if (this.ParentWindow.RedockAllowed)
{
WindowContent wc = this.ParentWindow as WindowContent;
// Is our parent a WindowContent instance?
if (wc != null)
{
// Start redocking activity for the whole WindowContent
_redocker = new RedockerContent(this, wc, new Point(e.X, e.Y));
}
}
}
this.Focus();
}
base.OnMouseDown(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
// The double click event will cause the control to be destroyed as
// the Contents are restored to their alternative positions, so need to
// double check the control is not already dead
if (!IsDisposed)
{
// Redocker object needs mouse movements
if (_redocker != null)
_redocker.OnMouseMove(e);
}
base.OnMouseMove(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
// The double click event will cause the control to be destroyed as
// the Contents are restored to their alternative positions, so need to
// double check the control is not already dead
if (!IsDisposed)
{
// Are we currently in a redocking state?
if (_redocker != null)
{
// Let the redocker finish off
_redocker.OnMouseUp(e);
// No longer need the object
_redocker = null;
}
// Right mouse button can generate a Context event
if (e.Button == MouseButtons.Right)
{
// Get screen coordinates of the mouse
Point pt = this.PointToScreen(new Point(e.X, e.Y));
// Box to transfer as parameter
OnContext(pt);
}
}
base.OnMouseUp(e);
}
protected override void OnResize(EventArgs e)
{
// Any resize of control should redraw all of it
Invalidate();
base.OnResize(e);
}
protected virtual void DefineButtonRemapping() {}
protected virtual void OnAddMaximizeInterface() {}
protected virtual void OnRemoveMaximizeInterface() {}
protected virtual void UpdateMaximizeImage() {}
protected virtual void UpdateAutoHideImage() {}
protected virtual void RecalculateButtons() {}
protected virtual void CreateButtons()
{
// Attach events to button
if (_closeButton != null)
{
_closeButton.Click += new EventHandler(OnButtonClose);
_closeButton.GotFocus += new EventHandler(OnButtonGotFocus);
}
if (_hideButton != null)
{
_hideButton.Click += new EventHandler(OnButtonHide);
_hideButton.GotFocus += new EventHandler(OnButtonGotFocus);
}
}
public bool PreFilterMessage(ref Message m)
{
// Has a key been pressed?
if (m.Msg == (int)Win32.Msgs.WM_KEYDOWN)
{
// Is it the ESCAPE key?
if ((int)m.WParam == (int)Win32.VirtualKeys.VK_ESCAPE)
{
// Are we in redocking mode?
if (_redocker != null)
{
// Cancel the redocking activity
_redocker.QuitTrackingMode(null);
// No longer need the object
_redocker = null;
return true;
}
}
}
return false;
}
}
[ToolboxItem(false)]
internal class WindowDetailCaptionPlain : WindowDetailCaption
{
protected enum ImageIndex
{
Close = 0,
EnabledHorizontalMax = 1,
EnabledHorizontalMin = 2,
EnabledVerticalMax = 3,
EnabledVerticalMin = 4,
AutoHide = 5,
AutoShow = 6
}
// Class constants
protected const int _inset = 3;
protected const int _offset = 5;
protected const int _fixedLength = 14;
protected const int _imageWidth = 10;
protected const int _imageHeight = 10;
protected const int _buttonWidth = 12;
protected const int _buttonHeight = 12;
protected const int _insetButton = 2;
// Instance fields
protected bool _dockLeft;
protected int _buttonOffset;
static WindowDetailCaptionPlain()
{
// Create a strip of images by loading an embedded bitmap resource
_images = ResourceHelper.LoadBitmapStrip(Type.GetType("IDE.Docking.WindowDetailCaptionPlain"),
"IDE.Resources.ImagesCaptionPlain.bmp",
new Size(_imageWidth, _imageHeight),
new Point(0,0));
}
public WindowDetailCaptionPlain(DockingManager manager,
EventHandler closeHandler,
EventHandler restoreHandler,
EventHandler invertAutoHideHandler,
ContextHandler contextHandler)
: base(manager,
new Size(_fixedLength, _fixedLength),
closeHandler,
restoreHandler,
invertAutoHideHandler,
contextHandler)
{
// Default to thinking we are docked on a left edge
_dockLeft = true;
// Modify painting to prevent overwriting the button control
_buttonOffset = 1 + (_buttonWidth + _insetButton) * 2;
}
public override void ParentStateChanged(State newState)
{
// Should we dock to the left or top of our container?
switch(newState)
{
case State.DockTop:
case State.DockBottom:
_dockLeft = true;
break;
case State.Floating:
case State.DockLeft:
case State.DockRight:
_dockLeft = false;
break;
}
// Ignore the AutoHide feature when in floating form
_ignoreHideButton = (_parentWindow.State == State.Floating);
RecalculateButtons();
}
public override void RemovedFromParent(Window parent)
{
if (parent != null)
{
if (this.Dock != DockStyle.None)
{
Size minSize = parent.MinimalSize;
if (this.Dock == DockStyle.Left)
{
// Remove our width from the minimum size of the parent
minSize.Width -= _fixedLength;
}
else
{
// Remove our height from the minimum size of the parent
minSize.Height -= _fixedLength;
}
parent.MinimalSize = minSize;
}
}
}
public override void AddedToParent(Window parent)
{
if (parent != null)
{
if (this.Dock != DockStyle.None)
{
Size minSize = parent.MinimalSize;
if (this.Dock == DockStyle.Left)
{
// Add our width from the minimum size of the parent
minSize.Width += _fixedLength;
}
else
{
// Add our height from the minimum size of the parent
minSize.Height += _fixedLength;
}
parent.MinimalSize = minSize;
}
}
}
protected override void DefineButtonRemapping()
{
// Define use of current system colors
ColorMap activeMap = new ColorMap();
ColorMap inactiveMap = new ColorMap();
activeMap.OldColor = Color.Black;
activeMap.NewColor = _manager.InactiveTextColor;
inactiveMap.OldColor = Color.Black;
inactiveMap.NewColor = Color.FromArgb(128, _manager.InactiveTextColor);
// Create remap attributes for use by button
_activeAttr.SetRemapTable(new ColorMap[]{activeMap}, ColorAdjustType.Bitmap);
_inactiveAttr.SetRemapTable(new ColorMap[]{inactiveMap}, ColorAdjustType.Bitmap);
}
protected override void OnAddMaximizeInterface()
{
if (_maxButton != null)
{
_maxButton.Size = new Size(_buttonWidth, _buttonHeight);
// Shows border all the time and not just when mouse is over control
_maxButton.PopupStyle = false;
// Define the fixed remapping
_maxButton.ImageAttributes = _inactiveAttr;
// Reduce the lines drawing
_buttonOffset += (_buttonWidth + _insetButton);
}
}
protected override void OnRemoveMaximizeInterface()
{
// Reduce the lines drawing
_buttonOffset -= (_buttonWidth + _insetButton);
}
protected override void CreateButtons()
{
// Define the ImageList and which ImageIndex to show initially
_closeButton = new InertButton(_images, (int)ImageIndex.Close);
_hideButton = new InertButton(_images, (int)ImageIndex.AutoHide);
_closeButton.Size = new Size(_buttonWidth, _buttonHeight);
_hideButton.Size = new Size(_buttonWidth, _buttonHeight);
// Shows border all the time and not just when mouse is over control
_closeButton.PopupStyle = false;
_hideButton.PopupStyle = false;
// Define the fixed remapping
_closeButton.ImageAttributes = _activeAttr;
_hideButton.ImageAttributes = _activeAttr;
// Add to the display
Controls.Add(_closeButton);
Controls.Add(_hideButton);
// Let base class perform common actions
base.CreateButtons();
}
protected override void UpdateAutoHideImage()
{
if (_pinnedImage)
_hideButton.ImageIndexEnabled = (int)ImageIndex.AutoShow;
else
_hideButton.ImageIndexEnabled = (int)ImageIndex.AutoHide;
}
protected override void UpdateMaximizeImage()
{
if (_showCloseButton)
_closeButton.ImageAttributes = _activeAttr;
else
_closeButton.ImageAttributes = _inactiveAttr;
if (_showHideButton && !_ignoreHideButton)
_hideButton.ImageAttributes = _activeAttr;
else
_hideButton.ImageAttributes = _inactiveAttr;
if (_maxButton != null)
{
if (_maxInterface.IsMaximizeAvailable())
_maxButton.ImageAttributes = _activeAttr;
else
_maxButton.ImageAttributes = _inactiveAttr;
bool maximized = _maxInterface.IsWindowMaximized(this.ParentWindow);
if (_maxInterface.Direction == Direction.Vertical)
{
if (maximized)
_maxButton.ImageIndexEnabled = (int)ImageIndex.EnabledVerticalMin;
else
_maxButton.ImageIndexEnabled = (int)ImageIndex.EnabledVerticalMax;
}
else
{
if (maximized)
_maxButton.ImageIndexEnabled = (int)ImageIndex.EnabledHorizontalMin;
else
_maxButton.ImageIndexEnabled = (int)ImageIndex.EnabledHorizontalMax;
}
}
}
protected override void RecalculateButtons()
{
if (_dockLeft)
{
if (this.Dock != DockStyle.Left)
{
RemovedFromParent(this.ParentWindow);
this.Dock = DockStyle.Left;
AddedToParent(this.ParentWindow);
}
int iStart = _inset;
// Button position is fixed, regardless of our size
_closeButton.Location = new Point(_insetButton, iStart);
_closeButton.Anchor = AnchorStyles.Top;
_closeButton.Show();
iStart += _buttonHeight + _insetButton;
// Button position is fixed, regardless of our size
_hideButton.Location = new Point(_insetButton, iStart);
_hideButton.Anchor = AnchorStyles.Top;
_hideButton.Show();
iStart += _buttonHeight + _insetButton;
if (_maxButton != null)
{
// Button position is fixed, regardless of our size
_maxButton.Location = new Point(_insetButton, iStart);
_maxButton.Anchor = AnchorStyles.Top;
}
}
else
{
if (this.Dock != DockStyle.Top)
{
RemovedFromParent(this.ParentWindow);
this.Dock = DockStyle.Top;
AddedToParent(this.ParentWindow);
}
Size client = this.ClientSize;
int iStart = _inset;
// Button is positioned to right hand side of bar
_closeButton.Location = new Point(client.Width - iStart - _buttonWidth, _insetButton);
_closeButton.Anchor = AnchorStyles.Right;
_closeButton.Show();
iStart += _buttonWidth + _insetButton;
// Next the AutoHide button is positioned
_hideButton.Location = new Point(client.Width - iStart - _buttonWidth, _insetButton);
_hideButton.Anchor = AnchorStyles.Right;
_hideButton.Show();
iStart += _buttonWidth + _insetButton;
if (_maxButton != null)
{
// Button position is fixed, regardless of our size
_maxButton.Location = new Point(client.Width - iStart - _buttonWidth, _insetButton);
_maxButton.Anchor = AnchorStyles.Right;
}
}
UpdateMaximizeImage();
}
protected override void OnPaint(PaintEventArgs e)
{
Size ourSize = this.ClientSize;
Point[] light = new Point[4];
Point[] dark = new Point[4];
// Depends on orientation
if (_dockLeft)
{
int iBottom = ourSize.Height - _inset - 1;
int iRight = _offset + 2;
int iTop = _inset + _buttonOffset;
light[3].X = light[2].X = light[0].X = _offset;
light[2].Y = light[1].Y = light[0].Y = iTop;
light[1].X = _offset + 1;
light[3].Y = iBottom;
dark[2].X = dark[1].X = dark[0].X = iRight;
dark[3].Y = dark[2].Y = dark[1].Y = iBottom;
dark[0].Y = iTop;
dark[3].X = iRight - 1;
}
else
{
int iBottom = _offset + 2;
int iRight = ourSize.Width - (_inset + _buttonOffset);
light[3].X = light[2].X = light[0].X = _inset;
light[1].Y = light[2].Y = light[0].Y = _offset;
light[1].X = iRight;
light[3].Y = _offset + 1;
dark[2].X = dark[1].X = dark[0].X = iRight;
dark[3].Y = dark[2].Y = dark[1].Y = iBottom;
dark[0].Y = _offset;
dark[3].X = _inset;
}
using (Pen lightPen = new Pen(ControlPaint.LightLight(_manager.BackColor)),
darkPen = new Pen(ControlPaint.Dark(_manager.BackColor)))
{
e.Graphics.DrawLine(lightPen, light[0], light[1]);
e.Graphics.DrawLine(lightPen, light[2], light[3]);
e.Graphics.DrawLine(darkPen, dark[0], dark[1]);
e.Graphics.DrawLine(darkPen, dark[2], dark[3]);
// Shift coordinates to draw section grab bar
if (_dockLeft)
{
for(int i=0; i<4; i++)
{
light[i].X += 4;
dark[i].X += 4;
}
}
else
{
for(int i=0; i<4; i++)
{
light[i].Y += 4;
dark[i].Y += 4;
}
}
e.Graphics.DrawLine(lightPen, light[0], light[1]);
e.Graphics.DrawLine(lightPen, light[2], light[3]);
e.Graphics.DrawLine(darkPen, dark[0], dark[1]);
e.Graphics.DrawLine(darkPen, dark[2], dark[3]);
}
base.OnPaint(e);
}
}
internal class WindowDetailCaptionIDE : WindowDetailCaption
{
protected enum ImageIndex
{
Close = 0,
EnabledVerticalMax = 1,
EnabledVerticalMin = 2,
AutoHide = 3,
AutoShow = 4
}
// Class constants
protected const int _yInset = 3;
protected const int _yInsetExtra = 3;
protected const int _imageWidth = 12;
protected const int _imageHeight = 11;
protected const int _buttonWidth = 14;
protected const int _buttonHeight = 13;
protected const int _buttonSpacer = 3;
// Class fields
protected static int _fixedLength;
static WindowDetailCaptionIDE()
{
// Create a strip of images by loading an embedded bitmap resource
_images = ResourceHelper.LoadBitmapStrip(Type.GetType("IDE.Docking.WindowDetailCaptionIDE"),
"gViewMap.IDE.Resources.ImagesCaptionIDE.bmp",
new Size(_imageWidth, _imageHeight),
new Point(0,0));
}
public WindowDetailCaptionIDE(DockingManager manager,
EventHandler closeHandler,
EventHandler restoreHandler,
EventHandler invertAutoHideHandler,
ContextHandler contextHandler)
: base(manager,
new Size(_fixedLength, _fixedLength),
closeHandler,
restoreHandler,
invertAutoHideHandler,
contextHandler)
{
// Use specificed font in the caption
UpdateCaptionHeight(manager.CaptionFont);
}
public override void PropogateNameValue(PropogateName name, object value)
{
base.PropogateNameValue(name, value);
switch(name)
{
case PropogateName.CaptionFont:
UpdateCaptionHeight((Font)value);
break;
case PropogateName.ActiveTextColor:
case PropogateName.InactiveTextColor:
DefineButtonRemapping();
Invalidate();
break;
}
}
public override void WindowGotFocus()
{
SetButtonState();
Invalidate();
}
public override void WindowLostFocus()
{
SetButtonState();
Invalidate();
}
public override void NotifyFullTitleText(string title)
{
this.Text = title;
Invalidate();
}
public override void ParentStateChanged(State newState)
{
// Ignore the AutoHide feature when in floating form
_ignoreHideButton = (_parentWindow.State == State.Floating);
this.Dock = DockStyle.Top;
RecalculateButtons();
Invalidate();
}
public override void RemovedFromParent(Window parent)
{
if (parent != null)
{
Size minSize = parent.MinimalSize;
// Remove our height from the minimum size of the parent
minSize.Height -= _fixedLength;
minSize.Width -= _fixedLength;
parent.MinimalSize = minSize;
}
}
protected override void DefineButtonRemapping()
{
// Define use of current system colors
ColorMap activeMap = new ColorMap();
ColorMap inactiveMap = new ColorMap();
activeMap.OldColor = Color.Black;
activeMap.NewColor = _manager.ActiveTextColor;
inactiveMap.OldColor = Color.Black;
inactiveMap.NewColor = _manager.InactiveTextColor;
// Create remap attributes for use by button
_activeAttr.SetRemapTable(new ColorMap[]{activeMap}, ColorAdjustType.Bitmap);
_inactiveAttr.SetRemapTable(new ColorMap[]{inactiveMap}, ColorAdjustType.Bitmap);
}
public override void AddedToParent(Window parent)
{
if (parent != null)
{
Size minSize = parent.MinimalSize;
// Remove our height from the minimum size of the parent
minSize.Height += _fixedLength;
minSize.Width += _fixedLength;
parent.MinimalSize = minSize;
}
}
protected override void OnAddMaximizeInterface()
{
if (_maxButton != null)
{
// Set the correct size for the button
_maxButton.Size = new Size(_buttonWidth, _buttonHeight);
// Give the button a very thin button
_maxButton.BorderWidth = 1;
// Define correct color setup
_maxButton.BackColor = this.BackColor;
_maxButton.ImageAttributes = _inactiveAttr;
// Force the ImageAttribute for the button to be set
SetButtonState();
}
}
protected override void UpdateAutoHideImage()
{
if (_pinnedImage)
_hideButton.ImageIndexEnabled = (int)ImageIndex.AutoShow;
else
_hideButton.ImageIndexEnabled = (int)ImageIndex.AutoHide;
}
protected override void UpdateMaximizeImage()
{
if ((_maxButton != null) && (_maxInterface != null))
{
bool enabled = _maxInterface.IsMaximizeAvailable();
if (!enabled)
{
if (_maxButton.Visible)
_maxButton.Hide();
}
else
{
bool maximized = _maxInterface.IsWindowMaximized(this.ParentWindow);
if (!_maxButton.Visible)
_maxButton.Show();
if (maximized)
_maxButton.ImageIndexEnabled = (int)ImageIndex.EnabledVerticalMin;
else
_maxButton.ImageIndexEnabled = (int)ImageIndex.EnabledVerticalMax;
}
}
}
protected void SetButtonState()
{
if (this.ParentWindow != null)
{
if (this.ParentWindow.ContainsFocus)
{
if (_closeButton.BackColor != _manager.ActiveColor)
{
_closeButton.BackColor = _manager.ActiveColor;
_closeButton.ImageAttributes = _activeAttr;
_closeButton.Invalidate();
}
if (_hideButton != null)
{
if (_hideButton.BackColor != _manager.ActiveColor)
{
_hideButton.BackColor = _manager.ActiveColor;
_hideButton.ImageAttributes = _activeAttr;
_hideButton.Invalidate();
}
}
if (_maxButton != null)
{
if (_maxButton.BackColor != _manager.ActiveColor)
{
_maxButton.BackColor = _manager.ActiveColor;
_maxButton.ImageAttributes = _activeAttr;
_maxButton.Invalidate();
}
}
}
else
{
if (_closeButton.BackColor != this.BackColor)
{
_closeButton.BackColor = this.BackColor;
_closeButton.ImageAttributes = _inactiveAttr;
_closeButton.Invalidate();
}
if (_hideButton != null)
{
if (_hideButton.BackColor != this.BackColor)
{
_hideButton.BackColor = this.BackColor;
_hideButton.ImageAttributes = _inactiveAttr;
_hideButton.Invalidate();
}
}
if (_maxButton != null)
{
if (_maxButton.BackColor != this.BackColor)
{
_maxButton.BackColor = this.BackColor;
_maxButton.ImageAttributes = _inactiveAttr;
_maxButton.Invalidate();
}
}
}
}
}
protected override void RecalculateButtons()
{
int buttonX = this.Width - _buttonWidth - _buttonSpacer;
int buttonY = (_fixedLength - _yInset * 2 - _buttonHeight) / 2 + _yInset;
if (_showCloseButton)
{
// Button position is fixed, regardless of our size
_closeButton.Location = new Point(buttonX, buttonY);
_closeButton.Size = new Size(_buttonWidth, _buttonHeight);
// Give the button a very thin button
_closeButton.BorderWidth = 1;
// Let the location of the control be updated for us
_closeButton.Anchor = AnchorStyles.Right;
// Just in case currently hidden
_closeButton.Show();
// Define start of next button
buttonX -= _buttonWidth;
}
else
_closeButton.Hide();
if (_showHideButton && !_ignoreHideButton)
{
// Button position is fixed, regardless of our size
_hideButton.Location = new Point(buttonX, buttonY);
_hideButton.Size = new Size(_buttonWidth, _buttonHeight);
// Give the button a very thin button
_hideButton.BorderWidth = 1;
// Let the location of the control be updated for us
_hideButton.Anchor = AnchorStyles.Right;
// Just in case currently hidden
_hideButton.Show();
// Define start of next button
buttonX -= _buttonWidth;
UpdateAutoHideImage();
}
else
_hideButton.Hide();
if (_maxButton != null)
{
// Button position is fixed, regardless of our size
_maxButton.Location = new Point(buttonX, buttonY);
_maxButton.Size = new Size(_buttonWidth, _buttonHeight);
// Give the button a very thin button
_maxButton.BorderWidth = 1;
// Let the location of the control be updated for us
_maxButton.Anchor = AnchorStyles.Right;
// Define start of next button
buttonX -= _buttonWidth;
UpdateMaximizeImage();
}
}
protected override void CreateButtons()
{
// Define the ImageList and which ImageIndex to show initially
_closeButton = new InertButton(_images, (int)ImageIndex.Close);
_hideButton = new InertButton(_images, (int)ImageIndex.AutoHide);
_closeButton.Size = new Size(_buttonWidth, _buttonHeight);
_hideButton.Size = new Size(_buttonWidth, _buttonHeight);
// Let the location of the control be updated for us
_closeButton.Anchor = AnchorStyles.Right;
_hideButton.Anchor = AnchorStyles.Right;
// Define the button position relative to the size set in the constructor
_closeButton.Location = new Point(_fixedLength - _buttonWidth - _buttonSpacer,
(_fixedLength - _yInset * 2 - _buttonHeight) / 2 + _yInset);
_hideButton.Location = new Point(_fixedLength - (_buttonWidth - _buttonSpacer) * 2,
(_fixedLength - _yInset * 2 - _buttonHeight) / 2 + _yInset);
// Give the button a very thin button
_closeButton.BorderWidth = 1;
_hideButton.BorderWidth = 1;
// Define correct color setup
_closeButton.BackColor = this.BackColor;
_closeButton.ImageAttributes = _inactiveAttr;
_hideButton.BackColor = this.BackColor;
_hideButton.ImageAttributes = _inactiveAttr;
// Add to the display
Controls.Add(_closeButton);
Controls.Add(_hideButton);
// Let base class perform common actions
base.CreateButtons();
}
protected void UpdateCaptionHeight(Font captionFont)
{
// Dynamically calculate the required height of the caption area
_fixedLength = (int)captionFont.GetHeight() + (_yInset + _yInsetExtra) * 2;
int minHeight = _buttonHeight + _yInset * 4 + 1;
// Maintain a minimum height to allow correct showing of buttons
if (_fixedLength < minHeight)
_fixedLength = minHeight;
this.Size = new Size(_fixedLength, _fixedLength);
RecalculateButtons();
Invalidate();
}
protected override void OnPaintBackground(PaintEventArgs e)
{
// Overriden to prevent background being painted
}
protected override void OnPaint(PaintEventArgs e)
{
bool focused = false;
if (this.ParentWindow != null)
focused = this.ParentWindow.ContainsFocus;
// Sometimes the min/max button is created and then an attempt is made to
// hide the button. But for some reason it does not always manage to hide
// the button. So forced to check here everytime to ensure its hidden.
UpdateMaximizeImage();
SetButtonState();
Size ourSize = this.ClientSize;
int xEnd = ourSize.Width;
int yEnd = ourSize.Height - _yInset * 2;
Rectangle rectCaption = new Rectangle(0, _yInset, xEnd, yEnd - _yInset + 1);
using(SolidBrush backBrush = new SolidBrush(this.BackColor),
activeBrush = new SolidBrush(_manager.ActiveColor),
activeTextBrush = new SolidBrush(_manager.ActiveTextColor),
inactiveBrush = new SolidBrush(_manager.InactiveTextColor))
{
// Is this control Active?
if (focused)
{
// Fill the entire background area
e.Graphics.FillRectangle(backBrush, e.ClipRectangle);
// Use a solid filled background for text
e.Graphics.FillRectangle(activeBrush, rectCaption);
// Start drawing text a little from the left
rectCaption.X += _buttonSpacer;
rectCaption.Y += 1;
rectCaption.Height -= 2;
// Reduce the width to account for close button
rectCaption.Width -= _closeButton.Width + _buttonSpacer;
// Reduce width to account for the optional maximize button
if ((_maxButton != null) && (_maxButton.Visible))
rectCaption.Width -= _closeButton.Width;
e.Graphics.DrawString(this.Text, _manager.CaptionFont, activeTextBrush, rectCaption);
}
else
{
// Fill the entire background area
e.Graphics.FillRectangle(backBrush, e.ClipRectangle);
// Inactive and so use a rounded rectangle
using (Pen dark = new Pen(ControlPaint.LightLight(_manager.InactiveTextColor)))
{
e.Graphics.DrawLine(dark, 1, _yInset, xEnd - 2, _yInset);
e.Graphics.DrawLine(dark, 1, yEnd, xEnd - 2, yEnd);
e.Graphics.DrawLine(dark, 0, _yInset + 1, 0, yEnd - 1);
e.Graphics.DrawLine(dark, xEnd - 1, _yInset + 1, xEnd - 1, yEnd - 1);
// Start drawing text a little from the left
rectCaption.X += _buttonSpacer;
rectCaption.Y += 1;
rectCaption.Height -= 2;
// Reduce the width to account for close button
rectCaption.Width -= _closeButton.Width + _buttonSpacer;
// Reduce width to account for the optional maximize button
if ((_maxButton != null) && (_maxButton.Visible))
rectCaption.Width -= _maxButton.Width;
e.Graphics.DrawString(this.Text, _manager.CaptionFont, inactiveBrush, rectCaption);
}
}
}
// Let delegates fire through base
base.OnPaint(e);
// Always get the button to repaint as we have painted over their area
_closeButton.Refresh();
}
}
}
| |
using System;
using System.Collections.Generic;
using Assets.PostProcessing.Runtime.Components;
using Assets.PostProcessing.Runtime.Models;
using Assets.PostProcessing.Runtime.Utils;
using UnityEngine;
using UnityEngine.Rendering;
namespace Assets.PostProcessing.Runtime
{
using DebugMode = BuiltinDebugViewsModel.Mode;
#if UNITY_5_4_OR_NEWER
[ImageEffectAllowedInSceneView]
#endif
[RequireComponent(typeof(Camera)), DisallowMultipleComponent, ExecuteInEditMode]
[AddComponentMenu("Effects/Post-Processing Behaviour", -1)]
public class PostProcessingBehaviour : MonoBehaviour
{
// Inspector fields
public PostProcessingProfile profile;
public Func<Vector2, Matrix4x4> jitteredMatrixFunc;
// Internal helpers
Dictionary<Type, KeyValuePair<CameraEvent, CommandBuffer>> m_CommandBuffers;
List<PostProcessingComponentBase> m_Components;
Dictionary<PostProcessingComponentBase, bool> m_ComponentStates;
MaterialFactory m_MaterialFactory;
RenderTextureFactory m_RenderTextureFactory;
PostProcessingContext m_Context;
Camera m_Camera;
PostProcessingProfile m_PreviousProfile;
bool m_RenderingInSceneView = false;
// Effect components
BuiltinDebugViewsComponent m_DebugViews;
AmbientOcclusionComponent m_AmbientOcclusion;
ScreenSpaceReflectionComponent m_ScreenSpaceReflection;
FogComponent m_FogComponent;
MotionBlurComponent m_MotionBlur;
TaaComponent m_Taa;
EyeAdaptationComponent m_EyeAdaptation;
DepthOfFieldComponent m_DepthOfField;
BloomComponent m_Bloom;
ChromaticAberrationComponent m_ChromaticAberration;
ColorGradingComponent m_ColorGrading;
UserLutComponent m_UserLut;
GrainComponent m_Grain;
VignetteComponent m_Vignette;
DitheringComponent m_Dithering;
FxaaComponent m_Fxaa;
void OnEnable()
{
m_CommandBuffers = new Dictionary<Type, KeyValuePair<CameraEvent, CommandBuffer>>();
m_MaterialFactory = new MaterialFactory();
m_RenderTextureFactory = new RenderTextureFactory();
m_Context = new PostProcessingContext();
// Keep a list of all post-fx for automation purposes
m_Components = new List<PostProcessingComponentBase>();
// Component list
m_DebugViews = AddComponent(new BuiltinDebugViewsComponent());
m_AmbientOcclusion = AddComponent(new AmbientOcclusionComponent());
m_ScreenSpaceReflection = AddComponent(new ScreenSpaceReflectionComponent());
m_FogComponent = AddComponent(new FogComponent());
m_MotionBlur = AddComponent(new MotionBlurComponent());
m_Taa = AddComponent(new TaaComponent());
m_EyeAdaptation = AddComponent(new EyeAdaptationComponent());
m_DepthOfField = AddComponent(new DepthOfFieldComponent());
m_Bloom = AddComponent(new BloomComponent());
m_ChromaticAberration = AddComponent(new ChromaticAberrationComponent());
m_ColorGrading = AddComponent(new ColorGradingComponent());
m_UserLut = AddComponent(new UserLutComponent());
m_Grain = AddComponent(new GrainComponent());
m_Vignette = AddComponent(new VignetteComponent());
m_Dithering = AddComponent(new DitheringComponent());
m_Fxaa = AddComponent(new FxaaComponent());
// Prepare state observers
m_ComponentStates = new Dictionary<PostProcessingComponentBase, bool>();
foreach (var component in m_Components)
m_ComponentStates.Add(component, false);
useGUILayout = false;
}
void OnPreCull()
{
// All the per-frame initialization logic has to be done in OnPreCull instead of Update
// because [ImageEffectAllowedInSceneView] doesn't trigger Update events...
m_Camera = GetComponent<Camera>();
if (profile == null || m_Camera == null)
return;
#if UNITY_EDITOR
// Track the scene view camera to disable some effects we don't want to see in the
// scene view
// Currently disabled effects :
// - Temporal Antialiasing
// - Depth of Field
// - Motion blur
m_RenderingInSceneView = UnityEditor.SceneView.currentDrawingSceneView != null
&& UnityEditor.SceneView.currentDrawingSceneView.camera == m_Camera;
#endif
// Prepare context
var context = m_Context.Reset();
context.profile = profile;
context.renderTextureFactory = m_RenderTextureFactory;
context.materialFactory = m_MaterialFactory;
context.camera = m_Camera;
// Prepare components
m_DebugViews.Init(context, profile.debugViews);
m_AmbientOcclusion.Init(context, profile.ambientOcclusion);
m_ScreenSpaceReflection.Init(context, profile.screenSpaceReflection);
m_FogComponent.Init(context, profile.fog);
m_MotionBlur.Init(context, profile.motionBlur);
m_Taa.Init(context, profile.antialiasing);
m_EyeAdaptation.Init(context, profile.eyeAdaptation);
m_DepthOfField.Init(context, profile.depthOfField);
m_Bloom.Init(context, profile.bloom);
m_ChromaticAberration.Init(context, profile.chromaticAberration);
m_ColorGrading.Init(context, profile.colorGrading);
m_UserLut.Init(context, profile.userLut);
m_Grain.Init(context, profile.grain);
m_Vignette.Init(context, profile.vignette);
m_Dithering.Init(context, profile.dithering);
m_Fxaa.Init(context, profile.antialiasing);
// Handles profile change and 'enable' state observers
if (m_PreviousProfile != profile)
{
DisableComponents();
m_PreviousProfile = profile;
}
CheckObservers();
// Find out which camera flags are needed before rendering begins
// Note that motion vectors will only be available one frame after being enabled
var flags = context.camera.depthTextureMode;
foreach (var component in m_Components)
{
if (component.active)
flags |= component.GetCameraFlags();
}
context.camera.depthTextureMode = flags;
// Temporal antialiasing jittering, needs to happen before culling
if (!m_RenderingInSceneView && m_Taa.active && !profile.debugViews.willInterrupt)
m_Taa.SetProjectionMatrix(jitteredMatrixFunc);
}
void OnPreRender()
{
if (profile == null)
return;
// Command buffer-based effects should be set-up here
TryExecuteCommandBuffer(m_DebugViews);
TryExecuteCommandBuffer(m_AmbientOcclusion);
TryExecuteCommandBuffer(m_ScreenSpaceReflection);
TryExecuteCommandBuffer(m_FogComponent);
if (!m_RenderingInSceneView)
TryExecuteCommandBuffer(m_MotionBlur);
}
void OnPostRender()
{
if (profile == null || m_Camera == null)
return;
if (!m_RenderingInSceneView && m_Taa.active && !profile.debugViews.willInterrupt)
m_Context.camera.ResetProjectionMatrix();
}
// Classic render target pipeline for RT-based effects
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (profile == null || m_Camera == null)
{
Graphics.Blit(source, destination);
return;
}
// Uber shader setup
bool uberActive = false;
bool fxaaActive = m_Fxaa.active;
bool taaActive = m_Taa.active && !m_RenderingInSceneView;
bool dofActive = m_DepthOfField.active && !m_RenderingInSceneView;
var uberMaterial = m_MaterialFactory.Get("Hidden/Post FX/Uber Shader");
uberMaterial.shaderKeywords = null;
var src = source;
var dst = destination;
if (taaActive)
{
var tempRT = m_RenderTextureFactory.Get(src);
m_Taa.Render(src, tempRT);
src = tempRT;
}
#if UNITY_EDITOR
// Render to a dedicated target when monitors are enabled so they can show information
// about the final render.
// At runtime the output will always be the backbuffer or whatever render target is
// currently set on the camera.
if (profile.monitors.onFrameEndEditorOnly != null)
dst = m_RenderTextureFactory.Get(src);
#endif
Texture autoExposure = GraphicsUtils.whiteTexture;
if (m_EyeAdaptation.active)
{
uberActive = true;
autoExposure = m_EyeAdaptation.Prepare(src, uberMaterial);
}
uberMaterial.SetTexture("_AutoExposure", autoExposure);
if (dofActive)
{
uberActive = true;
m_DepthOfField.Prepare(src, uberMaterial, taaActive, m_Taa.jitterVector, m_Taa.model.settings.taaSettings.motionBlending);
}
if (m_Bloom.active)
{
uberActive = true;
m_Bloom.Prepare(src, uberMaterial, autoExposure);
}
uberActive |= TryPrepareUberImageEffect(m_ChromaticAberration, uberMaterial);
uberActive |= TryPrepareUberImageEffect(m_ColorGrading, uberMaterial);
uberActive |= TryPrepareUberImageEffect(m_Vignette, uberMaterial);
uberActive |= TryPrepareUberImageEffect(m_UserLut, uberMaterial);
var fxaaMaterial = fxaaActive
? m_MaterialFactory.Get("Hidden/Post FX/FXAA")
: null;
if (fxaaActive)
{
fxaaMaterial.shaderKeywords = null;
TryPrepareUberImageEffect(m_Grain, fxaaMaterial);
TryPrepareUberImageEffect(m_Dithering, fxaaMaterial);
if (uberActive)
{
var output = m_RenderTextureFactory.Get(src);
Graphics.Blit(src, output, uberMaterial, 0);
src = output;
}
m_Fxaa.Render(src, dst);
}
else
{
uberActive |= TryPrepareUberImageEffect(m_Grain, uberMaterial);
uberActive |= TryPrepareUberImageEffect(m_Dithering, uberMaterial);
if (uberActive)
{
if (!GraphicsUtils.isLinearColorSpace)
uberMaterial.EnableKeyword("UNITY_COLORSPACE_GAMMA");
Graphics.Blit(src, dst, uberMaterial, 0);
}
}
if (!uberActive && !fxaaActive)
Graphics.Blit(src, dst);
#if UNITY_EDITOR
if (profile.monitors.onFrameEndEditorOnly != null)
{
Graphics.Blit(dst, destination);
var oldRt = RenderTexture.active;
profile.monitors.onFrameEndEditorOnly(dst);
RenderTexture.active = oldRt;
}
#endif
m_RenderTextureFactory.ReleaseAll();
}
void OnGUI()
{
if (Event.current.type != EventType.Repaint)
return;
if (profile == null || m_Camera == null)
return;
if (m_EyeAdaptation.active && profile.debugViews.IsModeActive(DebugMode.EyeAdaptation))
m_EyeAdaptation.OnGUI();
else if (m_ColorGrading.active && profile.debugViews.IsModeActive(DebugMode.LogLut))
m_ColorGrading.OnGUI();
else if (m_UserLut.active && profile.debugViews.IsModeActive(DebugMode.UserLut))
m_UserLut.OnGUI();
}
void OnDisable()
{
// Clear command buffers
foreach (var cb in m_CommandBuffers.Values)
{
m_Camera.RemoveCommandBuffer(cb.Key, cb.Value);
cb.Value.Dispose();
}
m_CommandBuffers.Clear();
// Clear components
if (profile != null)
DisableComponents();
m_Components.Clear();
// Factories
m_MaterialFactory.Dispose();
m_RenderTextureFactory.Dispose();
GraphicsUtils.Dispose();
}
public void ResetTemporalEffects()
{
m_Taa.ResetHistory();
m_MotionBlur.ResetHistory();
m_EyeAdaptation.ResetHistory();
}
#region State management
List<PostProcessingComponentBase> m_ComponentsToEnable = new List<PostProcessingComponentBase>();
List<PostProcessingComponentBase> m_ComponentsToDisable = new List<PostProcessingComponentBase>();
void CheckObservers()
{
foreach (var cs in m_ComponentStates)
{
var component = cs.Key;
var state = component.GetModel().enabled;
if (state != cs.Value)
{
if (state) m_ComponentsToEnable.Add(component);
else m_ComponentsToDisable.Add(component);
}
}
for (int i = 0; i < m_ComponentsToDisable.Count; i++)
{
var c = m_ComponentsToDisable[i];
m_ComponentStates[c] = false;
c.OnDisable();
}
for (int i = 0; i < m_ComponentsToEnable.Count; i++)
{
var c = m_ComponentsToEnable[i];
m_ComponentStates[c] = true;
c.OnEnable();
}
m_ComponentsToDisable.Clear();
m_ComponentsToEnable.Clear();
}
void DisableComponents()
{
foreach (var component in m_Components)
{
var model = component.GetModel();
if (model != null && model.enabled)
component.OnDisable();
}
}
#endregion
#region Command buffer handling & rendering helpers
// Placeholders before the upcoming Scriptable Render Loop as command buffers will be
// executed on the go so we won't need of all that stuff
CommandBuffer AddCommandBuffer<T>(CameraEvent evt, string name)
where T : PostProcessingModel
{
var cb = new CommandBuffer { name = name };
var kvp = new KeyValuePair<CameraEvent, CommandBuffer>(evt, cb);
m_CommandBuffers.Add(typeof(T), kvp);
m_Camera.AddCommandBuffer(evt, kvp.Value);
return kvp.Value;
}
void RemoveCommandBuffer<T>()
where T : PostProcessingModel
{
KeyValuePair<CameraEvent, CommandBuffer> kvp;
var type = typeof(T);
if (!m_CommandBuffers.TryGetValue(type, out kvp))
return;
m_Camera.RemoveCommandBuffer(kvp.Key, kvp.Value);
m_CommandBuffers.Remove(type);
kvp.Value.Dispose();
}
CommandBuffer GetCommandBuffer<T>(CameraEvent evt, string name)
where T : PostProcessingModel
{
CommandBuffer cb;
KeyValuePair<CameraEvent, CommandBuffer> kvp;
if (!m_CommandBuffers.TryGetValue(typeof(T), out kvp))
{
cb = AddCommandBuffer<T>(evt, name);
}
else if (kvp.Key != evt)
{
RemoveCommandBuffer<T>();
cb = AddCommandBuffer<T>(evt, name);
}
else cb = kvp.Value;
return cb;
}
void TryExecuteCommandBuffer<T>(PostProcessingComponentCommandBuffer<T> component)
where T : PostProcessingModel
{
if (component.active)
{
var cb = GetCommandBuffer<T>(component.GetCameraEvent(), component.GetName());
cb.Clear();
component.PopulateCommandBuffer(cb);
}
else RemoveCommandBuffer<T>();
}
bool TryPrepareUberImageEffect<T>(PostProcessingComponentRenderTexture<T> component, Material material)
where T : PostProcessingModel
{
if (!component.active)
return false;
component.Prepare(material);
return true;
}
T AddComponent<T>(T component)
where T : PostProcessingComponentBase
{
m_Components.Add(component);
return component;
}
#endregion
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Logging.V2.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedMetricsServiceV2ClientSnippets
{
/// <summary>Snippet for ListLogMetrics</summary>
public void ListLogMetricsRequestObject()
{
// Snippet: ListLogMetrics(ListLogMetricsRequest, CallSettings)
// Create client
MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create();
// Initialize request argument(s)
ListLogMetricsRequest request = new ListLogMetricsRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
};
// Make the request
PagedEnumerable<ListLogMetricsResponse, LogMetric> response = metricsServiceV2Client.ListLogMetrics(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (LogMetric item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListLogMetricsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (LogMetric item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<LogMetric> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (LogMetric item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListLogMetricsAsync</summary>
public async Task ListLogMetricsRequestObjectAsync()
{
// Snippet: ListLogMetricsAsync(ListLogMetricsRequest, CallSettings)
// Create client
MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync();
// Initialize request argument(s)
ListLogMetricsRequest request = new ListLogMetricsRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
};
// Make the request
PagedAsyncEnumerable<ListLogMetricsResponse, LogMetric> response = metricsServiceV2Client.ListLogMetricsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((LogMetric item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListLogMetricsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (LogMetric item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<LogMetric> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (LogMetric item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListLogMetrics</summary>
public void ListLogMetrics()
{
// Snippet: ListLogMetrics(string, string, int?, CallSettings)
// Create client
MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
// Make the request
PagedEnumerable<ListLogMetricsResponse, LogMetric> response = metricsServiceV2Client.ListLogMetrics(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (LogMetric item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListLogMetricsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (LogMetric item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<LogMetric> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (LogMetric item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListLogMetricsAsync</summary>
public async Task ListLogMetricsAsync()
{
// Snippet: ListLogMetricsAsync(string, string, int?, CallSettings)
// Create client
MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
// Make the request
PagedAsyncEnumerable<ListLogMetricsResponse, LogMetric> response = metricsServiceV2Client.ListLogMetricsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((LogMetric item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListLogMetricsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (LogMetric item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<LogMetric> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (LogMetric item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListLogMetrics</summary>
public void ListLogMetricsResourceNames()
{
// Snippet: ListLogMetrics(ProjectName, string, int?, CallSettings)
// Create client
MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
// Make the request
PagedEnumerable<ListLogMetricsResponse, LogMetric> response = metricsServiceV2Client.ListLogMetrics(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (LogMetric item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListLogMetricsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (LogMetric item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<LogMetric> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (LogMetric item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListLogMetricsAsync</summary>
public async Task ListLogMetricsResourceNamesAsync()
{
// Snippet: ListLogMetricsAsync(ProjectName, string, int?, CallSettings)
// Create client
MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
// Make the request
PagedAsyncEnumerable<ListLogMetricsResponse, LogMetric> response = metricsServiceV2Client.ListLogMetricsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((LogMetric item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListLogMetricsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (LogMetric item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<LogMetric> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (LogMetric item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetLogMetric</summary>
public void GetLogMetricRequestObject()
{
// Snippet: GetLogMetric(GetLogMetricRequest, CallSettings)
// Create client
MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create();
// Initialize request argument(s)
GetLogMetricRequest request = new GetLogMetricRequest
{
MetricNameAsLogMetricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]"),
};
// Make the request
LogMetric response = metricsServiceV2Client.GetLogMetric(request);
// End snippet
}
/// <summary>Snippet for GetLogMetricAsync</summary>
public async Task GetLogMetricRequestObjectAsync()
{
// Snippet: GetLogMetricAsync(GetLogMetricRequest, CallSettings)
// Additional: GetLogMetricAsync(GetLogMetricRequest, CancellationToken)
// Create client
MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync();
// Initialize request argument(s)
GetLogMetricRequest request = new GetLogMetricRequest
{
MetricNameAsLogMetricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]"),
};
// Make the request
LogMetric response = await metricsServiceV2Client.GetLogMetricAsync(request);
// End snippet
}
/// <summary>Snippet for GetLogMetric</summary>
public void GetLogMetric()
{
// Snippet: GetLogMetric(string, CallSettings)
// Create client
MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create();
// Initialize request argument(s)
string metricName = "projects/[PROJECT]/metrics/[METRIC]";
// Make the request
LogMetric response = metricsServiceV2Client.GetLogMetric(metricName);
// End snippet
}
/// <summary>Snippet for GetLogMetricAsync</summary>
public async Task GetLogMetricAsync()
{
// Snippet: GetLogMetricAsync(string, CallSettings)
// Additional: GetLogMetricAsync(string, CancellationToken)
// Create client
MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync();
// Initialize request argument(s)
string metricName = "projects/[PROJECT]/metrics/[METRIC]";
// Make the request
LogMetric response = await metricsServiceV2Client.GetLogMetricAsync(metricName);
// End snippet
}
/// <summary>Snippet for GetLogMetric</summary>
public void GetLogMetricResourceNames()
{
// Snippet: GetLogMetric(LogMetricName, CallSettings)
// Create client
MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create();
// Initialize request argument(s)
LogMetricName metricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]");
// Make the request
LogMetric response = metricsServiceV2Client.GetLogMetric(metricName);
// End snippet
}
/// <summary>Snippet for GetLogMetricAsync</summary>
public async Task GetLogMetricResourceNamesAsync()
{
// Snippet: GetLogMetricAsync(LogMetricName, CallSettings)
// Additional: GetLogMetricAsync(LogMetricName, CancellationToken)
// Create client
MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync();
// Initialize request argument(s)
LogMetricName metricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]");
// Make the request
LogMetric response = await metricsServiceV2Client.GetLogMetricAsync(metricName);
// End snippet
}
/// <summary>Snippet for CreateLogMetric</summary>
public void CreateLogMetricRequestObject()
{
// Snippet: CreateLogMetric(CreateLogMetricRequest, CallSettings)
// Create client
MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create();
// Initialize request argument(s)
CreateLogMetricRequest request = new CreateLogMetricRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
Metric = new LogMetric(),
};
// Make the request
LogMetric response = metricsServiceV2Client.CreateLogMetric(request);
// End snippet
}
/// <summary>Snippet for CreateLogMetricAsync</summary>
public async Task CreateLogMetricRequestObjectAsync()
{
// Snippet: CreateLogMetricAsync(CreateLogMetricRequest, CallSettings)
// Additional: CreateLogMetricAsync(CreateLogMetricRequest, CancellationToken)
// Create client
MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync();
// Initialize request argument(s)
CreateLogMetricRequest request = new CreateLogMetricRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
Metric = new LogMetric(),
};
// Make the request
LogMetric response = await metricsServiceV2Client.CreateLogMetricAsync(request);
// End snippet
}
/// <summary>Snippet for CreateLogMetric</summary>
public void CreateLogMetric()
{
// Snippet: CreateLogMetric(string, LogMetric, CallSettings)
// Create client
MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
LogMetric metric = new LogMetric();
// Make the request
LogMetric response = metricsServiceV2Client.CreateLogMetric(parent, metric);
// End snippet
}
/// <summary>Snippet for CreateLogMetricAsync</summary>
public async Task CreateLogMetricAsync()
{
// Snippet: CreateLogMetricAsync(string, LogMetric, CallSettings)
// Additional: CreateLogMetricAsync(string, LogMetric, CancellationToken)
// Create client
MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
LogMetric metric = new LogMetric();
// Make the request
LogMetric response = await metricsServiceV2Client.CreateLogMetricAsync(parent, metric);
// End snippet
}
/// <summary>Snippet for CreateLogMetric</summary>
public void CreateLogMetricResourceNames()
{
// Snippet: CreateLogMetric(ProjectName, LogMetric, CallSettings)
// Create client
MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
LogMetric metric = new LogMetric();
// Make the request
LogMetric response = metricsServiceV2Client.CreateLogMetric(parent, metric);
// End snippet
}
/// <summary>Snippet for CreateLogMetricAsync</summary>
public async Task CreateLogMetricResourceNamesAsync()
{
// Snippet: CreateLogMetricAsync(ProjectName, LogMetric, CallSettings)
// Additional: CreateLogMetricAsync(ProjectName, LogMetric, CancellationToken)
// Create client
MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
LogMetric metric = new LogMetric();
// Make the request
LogMetric response = await metricsServiceV2Client.CreateLogMetricAsync(parent, metric);
// End snippet
}
/// <summary>Snippet for UpdateLogMetric</summary>
public void UpdateLogMetricRequestObject()
{
// Snippet: UpdateLogMetric(UpdateLogMetricRequest, CallSettings)
// Create client
MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create();
// Initialize request argument(s)
UpdateLogMetricRequest request = new UpdateLogMetricRequest
{
MetricNameAsLogMetricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]"),
Metric = new LogMetric(),
};
// Make the request
LogMetric response = metricsServiceV2Client.UpdateLogMetric(request);
// End snippet
}
/// <summary>Snippet for UpdateLogMetricAsync</summary>
public async Task UpdateLogMetricRequestObjectAsync()
{
// Snippet: UpdateLogMetricAsync(UpdateLogMetricRequest, CallSettings)
// Additional: UpdateLogMetricAsync(UpdateLogMetricRequest, CancellationToken)
// Create client
MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync();
// Initialize request argument(s)
UpdateLogMetricRequest request = new UpdateLogMetricRequest
{
MetricNameAsLogMetricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]"),
Metric = new LogMetric(),
};
// Make the request
LogMetric response = await metricsServiceV2Client.UpdateLogMetricAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateLogMetric</summary>
public void UpdateLogMetric()
{
// Snippet: UpdateLogMetric(string, LogMetric, CallSettings)
// Create client
MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create();
// Initialize request argument(s)
string metricName = "projects/[PROJECT]/metrics/[METRIC]";
LogMetric metric = new LogMetric();
// Make the request
LogMetric response = metricsServiceV2Client.UpdateLogMetric(metricName, metric);
// End snippet
}
/// <summary>Snippet for UpdateLogMetricAsync</summary>
public async Task UpdateLogMetricAsync()
{
// Snippet: UpdateLogMetricAsync(string, LogMetric, CallSettings)
// Additional: UpdateLogMetricAsync(string, LogMetric, CancellationToken)
// Create client
MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync();
// Initialize request argument(s)
string metricName = "projects/[PROJECT]/metrics/[METRIC]";
LogMetric metric = new LogMetric();
// Make the request
LogMetric response = await metricsServiceV2Client.UpdateLogMetricAsync(metricName, metric);
// End snippet
}
/// <summary>Snippet for UpdateLogMetric</summary>
public void UpdateLogMetricResourceNames()
{
// Snippet: UpdateLogMetric(LogMetricName, LogMetric, CallSettings)
// Create client
MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create();
// Initialize request argument(s)
LogMetricName metricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]");
LogMetric metric = new LogMetric();
// Make the request
LogMetric response = metricsServiceV2Client.UpdateLogMetric(metricName, metric);
// End snippet
}
/// <summary>Snippet for UpdateLogMetricAsync</summary>
public async Task UpdateLogMetricResourceNamesAsync()
{
// Snippet: UpdateLogMetricAsync(LogMetricName, LogMetric, CallSettings)
// Additional: UpdateLogMetricAsync(LogMetricName, LogMetric, CancellationToken)
// Create client
MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync();
// Initialize request argument(s)
LogMetricName metricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]");
LogMetric metric = new LogMetric();
// Make the request
LogMetric response = await metricsServiceV2Client.UpdateLogMetricAsync(metricName, metric);
// End snippet
}
/// <summary>Snippet for DeleteLogMetric</summary>
public void DeleteLogMetricRequestObject()
{
// Snippet: DeleteLogMetric(DeleteLogMetricRequest, CallSettings)
// Create client
MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create();
// Initialize request argument(s)
DeleteLogMetricRequest request = new DeleteLogMetricRequest
{
MetricNameAsLogMetricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]"),
};
// Make the request
metricsServiceV2Client.DeleteLogMetric(request);
// End snippet
}
/// <summary>Snippet for DeleteLogMetricAsync</summary>
public async Task DeleteLogMetricRequestObjectAsync()
{
// Snippet: DeleteLogMetricAsync(DeleteLogMetricRequest, CallSettings)
// Additional: DeleteLogMetricAsync(DeleteLogMetricRequest, CancellationToken)
// Create client
MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync();
// Initialize request argument(s)
DeleteLogMetricRequest request = new DeleteLogMetricRequest
{
MetricNameAsLogMetricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]"),
};
// Make the request
await metricsServiceV2Client.DeleteLogMetricAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteLogMetric</summary>
public void DeleteLogMetric()
{
// Snippet: DeleteLogMetric(string, CallSettings)
// Create client
MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create();
// Initialize request argument(s)
string metricName = "projects/[PROJECT]/metrics/[METRIC]";
// Make the request
metricsServiceV2Client.DeleteLogMetric(metricName);
// End snippet
}
/// <summary>Snippet for DeleteLogMetricAsync</summary>
public async Task DeleteLogMetricAsync()
{
// Snippet: DeleteLogMetricAsync(string, CallSettings)
// Additional: DeleteLogMetricAsync(string, CancellationToken)
// Create client
MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync();
// Initialize request argument(s)
string metricName = "projects/[PROJECT]/metrics/[METRIC]";
// Make the request
await metricsServiceV2Client.DeleteLogMetricAsync(metricName);
// End snippet
}
/// <summary>Snippet for DeleteLogMetric</summary>
public void DeleteLogMetricResourceNames()
{
// Snippet: DeleteLogMetric(LogMetricName, CallSettings)
// Create client
MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create();
// Initialize request argument(s)
LogMetricName metricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]");
// Make the request
metricsServiceV2Client.DeleteLogMetric(metricName);
// End snippet
}
/// <summary>Snippet for DeleteLogMetricAsync</summary>
public async Task DeleteLogMetricResourceNamesAsync()
{
// Snippet: DeleteLogMetricAsync(LogMetricName, CallSettings)
// Additional: DeleteLogMetricAsync(LogMetricName, CancellationToken)
// Create client
MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync();
// Initialize request argument(s)
LogMetricName metricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]");
// Make the request
await metricsServiceV2Client.DeleteLogMetricAsync(metricName);
// End snippet
}
}
}
| |
// 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.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using Compute.Tests.DiskRPTests;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Azure.Management.Storage.Models;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.Rest.Azure;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Xunit;
namespace Compute.Tests
{
public class GalleryTests : VMTestBase
{
protected const string ResourceGroupPrefix = "galleryPsTestRg";
protected const string GalleryNamePrefix = "galleryPsTestGallery";
protected const string GalleryImageNamePrefix = "galleryPsTestGalleryImage";
protected const string GalleryApplicationNamePrefix = "galleryPsTestGalleryApplication";
private string galleryHomeLocation = "eastus2";
[Fact]
public void Gallery_CRUD_Tests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix);
string rgName2 = rgName + "New";
m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = galleryHomeLocation });
Trace.TraceInformation("Created the resource group: " + rgName);
string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix);
Gallery galleryIn = GetTestInputGallery();
m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, galleryIn);
Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName, rgName));
Gallery galleryOut = m_CrpClient.Galleries.Get(rgName, galleryName);
Trace.TraceInformation("Got the gallery.");
Assert.NotNull(galleryOut);
ValidateGallery(galleryIn, galleryOut);
galleryIn.Description = "This is an updated description";
m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, galleryIn);
Trace.TraceInformation("Updated the gallery.");
galleryOut = m_CrpClient.Galleries.Get(rgName, galleryName);
ValidateGallery(galleryIn, galleryOut);
Trace.TraceInformation("Listing galleries.");
string galleryName2 = galleryName + "New";
m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName2, new ResourceGroup { Location = galleryHomeLocation });
Trace.TraceInformation("Created the resource group: " + rgName2);
ComputeManagementTestUtilities.WaitSeconds(10);
m_CrpClient.Galleries.CreateOrUpdate(rgName2, galleryName2, galleryIn);
Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName2, rgName2));
IPage<Gallery> listGalleriesInRgResult = m_CrpClient.Galleries.ListByResourceGroup(rgName);
Assert.Single(listGalleriesInRgResult);
Assert.Null(listGalleriesInRgResult.NextPageLink);
IPage<Gallery> listGalleriesInSubIdResult = m_CrpClient.Galleries.List();
// Below, >= instead of == is used because this subscription is shared in the group so other developers
// might have created galleries in this subscription.
Assert.True(listGalleriesInSubIdResult.Count() >= 2);
Trace.TraceInformation("Deleting 2 galleries.");
m_CrpClient.Galleries.Delete(rgName, galleryName);
m_CrpClient.Galleries.Delete(rgName2, galleryName2);
listGalleriesInRgResult = m_CrpClient.Galleries.ListByResourceGroup(rgName);
Assert.Empty(listGalleriesInRgResult);
// resource groups cleanup is taken cared by MockContext.Dispose() method.
}
}
[Fact]
public void GalleryImage_CRUD_Tests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix);
m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = galleryHomeLocation });
Trace.TraceInformation("Created the resource group: " + rgName);
string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix);
Gallery gallery = GetTestInputGallery();
m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, gallery);
Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName, rgName));
string galleryImageName = ComputeManagementTestUtilities.GenerateName(GalleryImageNamePrefix);
GalleryImage inputGalleryImage = GetTestInputGalleryImage();
m_CrpClient.GalleryImages.CreateOrUpdate(rgName, galleryName, galleryImageName, inputGalleryImage);
Trace.TraceInformation(string.Format("Created the gallery image: {0} in gallery: {1}", galleryImageName,
galleryName));
GalleryImage galleryImageFromGet = m_CrpClient.GalleryImages.Get(rgName, galleryName, galleryImageName);
Assert.NotNull(galleryImageFromGet);
ValidateGalleryImage(inputGalleryImage, galleryImageFromGet);
inputGalleryImage.Description = "Updated description.";
m_CrpClient.GalleryImages.CreateOrUpdate(rgName, galleryName, galleryImageName, inputGalleryImage);
Trace.TraceInformation(string.Format("Updated the gallery image: {0} in gallery: {1}", galleryImageName,
galleryName));
galleryImageFromGet = m_CrpClient.GalleryImages.Get(rgName, galleryName, galleryImageName);
Assert.NotNull(galleryImageFromGet);
ValidateGalleryImage(inputGalleryImage, galleryImageFromGet);
IPage<GalleryImage> listGalleryImagesResult = m_CrpClient.GalleryImages.ListByGallery(rgName, galleryName);
Assert.Single(listGalleryImagesResult);
Assert.Null(listGalleryImagesResult.NextPageLink);
m_CrpClient.GalleryImages.Delete(rgName, galleryName, galleryImageName);
listGalleryImagesResult = m_CrpClient.GalleryImages.ListByGallery(rgName, galleryName);
Assert.Empty(listGalleryImagesResult);
Trace.TraceInformation(string.Format("Deleted the gallery image: {0} in gallery: {1}", galleryImageName,
galleryName));
m_CrpClient.Galleries.Delete(rgName, galleryName);
}
}
[Fact]
public void GalleryImageVersion_CRUD_Tests()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
using (MockContext context = MockContext.Start(this.GetType()))
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", galleryHomeLocation);
EnsureClientsInitialized(context);
string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix);
VirtualMachine vm = null;
string imageName = ComputeManagementTestUtilities.GenerateName("psTestSourceImage");
try
{
string sourceImageId = "";
vm = CreateCRPImage(rgName, imageName, ref sourceImageId);
Assert.False(string.IsNullOrEmpty(sourceImageId));
Trace.TraceInformation(string.Format("Created the source image id: {0}", sourceImageId));
string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix);
Gallery gallery = GetTestInputGallery();
m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, gallery);
Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName,
rgName));
string galleryImageName = ComputeManagementTestUtilities.GenerateName(GalleryImageNamePrefix);
GalleryImage inputGalleryImage = GetTestInputGalleryImage();
m_CrpClient.GalleryImages.CreateOrUpdate(rgName, galleryName, galleryImageName, inputGalleryImage);
Trace.TraceInformation(string.Format("Created the gallery image: {0} in gallery: {1}", galleryImageName,
galleryName));
string galleryImageVersionName = "1.0.0";
GalleryImageVersion inputImageVersion = GetTestInputGalleryImageVersion(sourceImageId);
m_CrpClient.GalleryImageVersions.CreateOrUpdate(rgName, galleryName, galleryImageName,
galleryImageVersionName, inputImageVersion);
Trace.TraceInformation(string.Format("Created the gallery image version: {0} in gallery image: {1}",
galleryImageVersionName, galleryImageName));
GalleryImageVersion imageVersionFromGet = m_CrpClient.GalleryImageVersions.Get(rgName,
galleryName, galleryImageName, galleryImageVersionName);
Assert.NotNull(imageVersionFromGet);
ValidateGalleryImageVersion(inputImageVersion, imageVersionFromGet);
imageVersionFromGet = m_CrpClient.GalleryImageVersions.Get(rgName, galleryName, galleryImageName,
galleryImageVersionName, ReplicationStatusTypes.ReplicationStatus);
Assert.Equal(StorageAccountType.StandardLRS, imageVersionFromGet.PublishingProfile.StorageAccountType);
Assert.Equal(StorageAccountType.StandardLRS,
imageVersionFromGet.PublishingProfile.TargetRegions.First().StorageAccountType);
Assert.NotNull(imageVersionFromGet.ReplicationStatus);
Assert.NotNull(imageVersionFromGet.ReplicationStatus.Summary);
inputImageVersion.PublishingProfile.EndOfLifeDate = DateTime.Now.AddDays(100).Date;
m_CrpClient.GalleryImageVersions.CreateOrUpdate(rgName, galleryName, galleryImageName,
galleryImageVersionName, inputImageVersion);
Trace.TraceInformation(string.Format("Updated the gallery image version: {0} in gallery image: {1}",
galleryImageVersionName, galleryImageName));
imageVersionFromGet = m_CrpClient.GalleryImageVersions.Get(rgName, galleryName,
galleryImageName, galleryImageVersionName);
Assert.NotNull(imageVersionFromGet);
ValidateGalleryImageVersion(inputImageVersion, imageVersionFromGet);
Trace.TraceInformation("Listing the gallery image versions");
IPage<GalleryImageVersion> listGalleryImageVersionsResult = m_CrpClient.GalleryImageVersions.
ListByGalleryImage(rgName, galleryName, galleryImageName);
Assert.Single(listGalleryImageVersionsResult);
Assert.Null(listGalleryImageVersionsResult.NextPageLink);
m_CrpClient.GalleryImageVersions.Delete(rgName, galleryName, galleryImageName, galleryImageVersionName);
listGalleryImageVersionsResult = m_CrpClient.GalleryImageVersions.
ListByGalleryImage(rgName, galleryName, galleryImageName);
Assert.Empty(listGalleryImageVersionsResult);
Assert.Null(listGalleryImageVersionsResult.NextPageLink);
Trace.TraceInformation(string.Format("Deleted the gallery image version: {0} in gallery image: {1}",
galleryImageVersionName, galleryImageName));
ComputeManagementTestUtilities.WaitMinutes(5);
m_CrpClient.Images.Delete(rgName, imageName);
Trace.TraceInformation("Deleted the CRP image.");
m_CrpClient.VirtualMachines.Delete(rgName, vm.Name);
Trace.TraceInformation("Deleted the virtual machine.");
m_CrpClient.GalleryImages.Delete(rgName, galleryName, galleryImageName);
Trace.TraceInformation("Deleted the gallery image.");
m_CrpClient.Galleries.Delete(rgName, galleryName);
Trace.TraceInformation("Deleted the gallery.");
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
if (vm != null)
{
m_CrpClient.VirtualMachines.Delete(rgName, vm.Name);
}
m_CrpClient.Images.Delete(rgName, imageName);
}
}
}
[Fact]
public void GalleryApplication_CRUD_Tests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
string location = ComputeManagementTestUtilities.DefaultLocation;
EnsureClientsInitialized(context);
string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix);
m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = location });
Trace.TraceInformation("Created the resource group: " + rgName);
string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix);
Gallery gallery = GetTestInputGallery();
gallery.Location = location;
m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, gallery);
Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName, rgName));
string galleryApplicationName = ComputeManagementTestUtilities.GenerateName(GalleryApplicationNamePrefix);
GalleryApplication inputGalleryApplication = GetTestInputGalleryApplication();
m_CrpClient.GalleryApplications.CreateOrUpdate(rgName, galleryName, galleryApplicationName, inputGalleryApplication);
Trace.TraceInformation(string.Format("Created the gallery application: {0} in gallery: {1}", galleryApplicationName,
galleryName));
GalleryApplication galleryApplicationFromGet = m_CrpClient.GalleryApplications.Get(rgName, galleryName, galleryApplicationName);
Assert.NotNull(galleryApplicationFromGet);
ValidateGalleryApplication(inputGalleryApplication, galleryApplicationFromGet);
inputGalleryApplication.Description = "Updated description.";
m_CrpClient.GalleryApplications.CreateOrUpdate(rgName, galleryName, galleryApplicationName, inputGalleryApplication);
Trace.TraceInformation(string.Format("Updated the gallery application: {0} in gallery: {1}", galleryApplicationName,
galleryName));
galleryApplicationFromGet = m_CrpClient.GalleryApplications.Get(rgName, galleryName, galleryApplicationName);
Assert.NotNull(galleryApplicationFromGet);
ValidateGalleryApplication(inputGalleryApplication, galleryApplicationFromGet);
m_CrpClient.GalleryApplications.Delete(rgName, galleryName, galleryApplicationName);
Trace.TraceInformation(string.Format("Deleted the gallery application: {0} in gallery: {1}", galleryApplicationName,
galleryName));
m_CrpClient.Galleries.Delete(rgName, galleryName);
}
}
[Fact]
public void GalleryApplicationVersion_CRUD_Tests()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
using (MockContext context = MockContext.Start(this.GetType()))
{
string location = ComputeManagementTestUtilities.DefaultLocation;
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", location);
EnsureClientsInitialized(context);
string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix);
string applicationName = ComputeManagementTestUtilities.GenerateName("psTestSourceApplication");
string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix);
string galleryApplicationName = ComputeManagementTestUtilities.GenerateName(GalleryApplicationNamePrefix);
try
{
string applicationMediaLink = CreateApplicationMediaLink(rgName, "test.txt");
Assert.False(string.IsNullOrEmpty(applicationMediaLink));
Trace.TraceInformation(string.Format("Created the source application media link: {0}", applicationMediaLink));
Gallery gallery = GetTestInputGallery();
gallery.Location = location;
m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, gallery);
Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName,
rgName));
GalleryApplication inputGalleryApplication = GetTestInputGalleryApplication();
m_CrpClient.GalleryApplications.CreateOrUpdate(rgName, galleryName, galleryApplicationName, inputGalleryApplication);
Trace.TraceInformation(string.Format("Created the gallery application: {0} in gallery: {1}", galleryApplicationName,
galleryName));
string galleryApplicationVersionName = "1.0.0";
GalleryApplicationVersion inputApplicationVersion = GetTestInputGalleryApplicationVersion(applicationMediaLink);
m_CrpClient.GalleryApplicationVersions.CreateOrUpdate(rgName, galleryName, galleryApplicationName,
galleryApplicationVersionName, inputApplicationVersion);
Trace.TraceInformation(string.Format("Created the gallery application version: {0} in gallery application: {1}",
galleryApplicationVersionName, galleryApplicationName));
GalleryApplicationVersion applicationVersionFromGet = m_CrpClient.GalleryApplicationVersions.Get(rgName,
galleryName, galleryApplicationName, galleryApplicationVersionName);
Assert.NotNull(applicationVersionFromGet);
ValidateGalleryApplicationVersion(inputApplicationVersion, applicationVersionFromGet);
applicationVersionFromGet = m_CrpClient.GalleryApplicationVersions.Get(rgName, galleryName, galleryApplicationName,
galleryApplicationVersionName, ReplicationStatusTypes.ReplicationStatus);
Assert.Equal(StorageAccountType.StandardLRS, applicationVersionFromGet.PublishingProfile.StorageAccountType);
Assert.Equal(StorageAccountType.StandardLRS,
applicationVersionFromGet.PublishingProfile.TargetRegions.First().StorageAccountType);
Assert.NotNull(applicationVersionFromGet.ReplicationStatus);
Assert.NotNull(applicationVersionFromGet.ReplicationStatus.Summary);
inputApplicationVersion.PublishingProfile.EndOfLifeDate = DateTime.Now.AddDays(100).Date;
m_CrpClient.GalleryApplicationVersions.CreateOrUpdate(rgName, galleryName, galleryApplicationName,
galleryApplicationVersionName, inputApplicationVersion);
Trace.TraceInformation(string.Format("Updated the gallery application version: {0} in gallery application: {1}",
galleryApplicationVersionName, galleryApplicationName));
applicationVersionFromGet = m_CrpClient.GalleryApplicationVersions.Get(rgName, galleryName,
galleryApplicationName, galleryApplicationVersionName);
Assert.NotNull(applicationVersionFromGet);
ValidateGalleryApplicationVersion(inputApplicationVersion, applicationVersionFromGet);
m_CrpClient.GalleryApplicationVersions.Delete(rgName, galleryName, galleryApplicationName, galleryApplicationVersionName);
Trace.TraceInformation(string.Format("Deleted the gallery application version: {0} in gallery application: {1}",
galleryApplicationVersionName, galleryApplicationName));
m_CrpClient.GalleryApplications.Delete(rgName, galleryName, galleryApplicationName);
Trace.TraceInformation("Deleted the gallery application.");
m_CrpClient.Galleries.Delete(rgName, galleryName);
Trace.TraceInformation("Deleted the gallery.");
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
}
[Fact]
public void Gallery_WithSharingProfile_CRUD_Tests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix);
m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = galleryHomeLocation });
Trace.TraceInformation("Created the resource group: " + rgName);
string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix);
Gallery galleryIn = GetTestInputSharedGallery();
m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, galleryIn);
Trace.TraceInformation(string.Format("Created the shared gallery: {0} in resource group: {1} with sharing profile permission: {2}",
galleryName, rgName, galleryIn.SharingProfile.Permissions));
Gallery galleryOut = m_CrpClient.Galleries.Get(rgName, galleryName);
Trace.TraceInformation("Got the gallery.");
Assert.NotNull(galleryOut);
ValidateGallery(galleryIn, galleryOut);
Trace.TraceInformation("Update the sharing profile via post, add the sharing profile groups.");
string newTenantId = "583d66a9-0041-4999-8838-75baece101d5";
SharingProfileGroup tenantGroups = new SharingProfileGroup()
{
Type = "AADTenants",
Ids = new List<string> { newTenantId }
};
string newSubId = "640c5810-13bf-4b82-b94d-f38c2565e3bc";
SharingProfileGroup subGroups = new SharingProfileGroup()
{
Type = "Subscriptions",
Ids = new List<string> { newSubId }
};
List<SharingProfileGroup> groups = new List<SharingProfileGroup> { tenantGroups, subGroups };
SharingUpdate sharingUpdate = new SharingUpdate()
{
OperationType = "Add",
Groups = groups
};
m_CrpClient.GallerySharingProfile.Update(rgName, galleryName,sharingUpdate);
Gallery galleryOutWithSharingProfile = m_CrpClient.Galleries.Get(rgName, galleryName, SelectPermissions.Permissions);
Trace.TraceInformation("Got the gallery");
Assert.NotNull(galleryOut);
ValidateSharingProfile(galleryIn, galleryOutWithSharingProfile, groups);
Trace.TraceInformation("Reset this gallery to private before deleting it.");
SharingUpdate resetPrivateUpdate = new SharingUpdate()
{
OperationType = "ResetToPrivate",
Groups = null
};
m_CrpClient.GallerySharingProfile.Update(rgName, galleryName, resetPrivateUpdate);
Trace.TraceInformation("Deleting this gallery.");
m_CrpClient.Galleries.Delete(rgName, galleryName);
// resource groups cleanup is taken cared by MockContext.Dispose() method.
}
}
private void ValidateGallery(Gallery galleryIn, Gallery galleryOut)
{
Assert.False(string.IsNullOrEmpty(galleryOut.ProvisioningState));
if (galleryIn.Tags != null)
{
foreach (KeyValuePair<string, string> kvp in galleryIn.Tags)
{
Assert.Equal(kvp.Value, galleryOut.Tags[kvp.Key]);
}
}
if (!string.IsNullOrEmpty(galleryIn.Description))
{
Assert.Equal(galleryIn.Description, galleryOut.Description);
}
Assert.False(string.IsNullOrEmpty(galleryOut?.Identifier?.UniqueName));
}
private void ValidateSharingProfile(Gallery galleryIn, Gallery galleryOut, List<SharingProfileGroup> groups)
{
if(galleryIn.SharingProfile != null)
{
Assert.Equal(galleryIn.SharingProfile.Permissions, galleryOut.SharingProfile.Permissions);
Assert.Equal(groups.Count, galleryOut.SharingProfile.Groups.Count);
foreach (SharingProfileGroup sharingProfileGroup in galleryOut.SharingProfile.Groups)
{
if (sharingProfileGroup.Ids != null)
{
List<string> outIds = sharingProfileGroup.Ids as List<string>;
List<string> inIds = null;
foreach(SharingProfileGroup inGroup in groups)
{
if(inGroup.Type == sharingProfileGroup.Type)
{
inIds = inGroup.Ids as List<string>;
break;
}
}
Assert.NotNull(inIds);
Assert.Equal(inIds.Count, outIds.Count);
for(int i = 0; i < inIds.Count; i++)
{
Assert.Equal(outIds[i], inIds[i]);
}
}
}
}
}
private void ValidateGalleryImage(GalleryImage imageIn, GalleryImage imageOut)
{
Assert.False(string.IsNullOrEmpty(imageOut.ProvisioningState));
if (imageIn.Tags != null)
{
foreach (KeyValuePair<string, string> kvp in imageIn.Tags)
{
Assert.Equal(kvp.Value, imageOut.Tags[kvp.Key]);
}
}
Assert.Equal(imageIn.Identifier.Publisher, imageOut.Identifier.Publisher);
Assert.Equal(imageIn.Identifier.Offer, imageOut.Identifier.Offer);
Assert.Equal(imageIn.Identifier.Sku, imageOut.Identifier.Sku);
Assert.Equal(imageIn.Location, imageOut.Location);
Assert.Equal(imageIn.OsState, imageOut.OsState);
Assert.Equal(imageIn.OsType, imageOut.OsType);
if (imageIn.HyperVGeneration == null)
{
Assert.Equal(HyperVGenerationType.V1, imageOut.HyperVGeneration);
}
else
{
Assert.Equal(imageIn.HyperVGeneration, imageOut.HyperVGeneration);
}
if (!string.IsNullOrEmpty(imageIn.Description))
{
Assert.Equal(imageIn.Description, imageOut.Description);
}
}
private void ValidateGalleryImageVersion(GalleryImageVersion imageVersionIn,
GalleryImageVersion imageVersionOut)
{
Assert.False(string.IsNullOrEmpty(imageVersionOut.ProvisioningState));
if (imageVersionIn.Tags != null)
{
foreach (KeyValuePair<string, string> kvp in imageVersionIn.Tags)
{
Assert.Equal(kvp.Value, imageVersionOut.Tags[kvp.Key]);
}
}
Assert.Equal(imageVersionIn.Location, imageVersionOut.Location);
Assert.False(string.IsNullOrEmpty(imageVersionOut.StorageProfile.Source.Id),
"imageVersionOut.PublishingProfile.Source.ManagedImage.Id is null or empty.");
Assert.NotNull(imageVersionOut.PublishingProfile.EndOfLifeDate);
Assert.NotNull(imageVersionOut.PublishingProfile.PublishedDate);
Assert.NotNull(imageVersionOut.StorageProfile);
}
private Gallery GetTestInputGallery()
{
return new Gallery
{
Location = galleryHomeLocation,
Description = "This is a sample gallery description"
};
}
private Gallery GetTestInputSharedGallery()
{
return new Gallery
{
Location = galleryHomeLocation,
Description = "This is a sample gallery description",
SharingProfile = new SharingProfile
{
Permissions = "Groups"
}
};
}
private GalleryImage GetTestInputGalleryImage()
{
return new GalleryImage
{
Identifier = new GalleryImageIdentifier
{
Publisher = "testPub",
Offer = "testOffer",
Sku = "testSku"
},
Location = galleryHomeLocation,
OsState = OperatingSystemStateTypes.Generalized,
OsType = OperatingSystemTypes.Windows,
Description = "This is the gallery image description.",
HyperVGeneration = null
};
}
private GalleryImageVersion GetTestInputGalleryImageVersion(string sourceImageId)
{
return new GalleryImageVersion
{
Location = galleryHomeLocation,
PublishingProfile = new GalleryImageVersionPublishingProfile
{
ReplicaCount = 1,
StorageAccountType = StorageAccountType.StandardLRS,
TargetRegions = new List<TargetRegion> {
new TargetRegion {
Name = galleryHomeLocation,
RegionalReplicaCount = 1,
StorageAccountType = StorageAccountType.StandardLRS
}
},
EndOfLifeDate = DateTime.Today.AddDays(10).Date
},
StorageProfile = new GalleryImageVersionStorageProfile
{
Source = new GalleryArtifactVersionSource
{
Id = sourceImageId
}
}
};
}
private VirtualMachine CreateCRPImage(string rgName, string imageName, ref string sourceImageId)
{
string storageAccountName = ComputeManagementTestUtilities.GenerateName("saforgallery");
string asName = ComputeManagementTestUtilities.GenerateName("asforgallery");
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
StorageAccount storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); // resource group is also created in this method.
VirtualMachine inputVM = null;
VirtualMachine createdVM = CreateVM(rgName, asName, storageAccountOutput, imageRef, out inputVM);
Image imageInput = new Image()
{
Location = m_location,
Tags = new Dictionary<string, string>()
{
{"RG", "rg"},
{"testTag", "1"},
},
StorageProfile = new ImageStorageProfile()
{
OsDisk = new ImageOSDisk()
{
BlobUri = createdVM.StorageProfile.OsDisk.Vhd.Uri,
OsState = OperatingSystemStateTypes.Generalized,
OsType = OperatingSystemTypes.Windows,
},
ZoneResilient = true
},
HyperVGeneration = HyperVGenerationTypes.V1
};
m_CrpClient.Images.CreateOrUpdate(rgName, imageName, imageInput);
Image getImage = m_CrpClient.Images.Get(rgName, imageName);
sourceImageId = getImage.Id;
return createdVM;
}
private string CreateApplicationMediaLink(string rgName, string fileName)
{
string storageAccountName = ComputeManagementTestUtilities.GenerateName("saforgallery");
string asName = ComputeManagementTestUtilities.GenerateName("asforgallery");
StorageAccount storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); // resource group is also created in this method.
string applicationMediaLink = @"https://saforgallery1969.blob.core.windows.net/sascontainer/test.txt\";
if (HttpMockServer.Mode == HttpRecorderMode.Record)
{
var accountKeyResult = m_SrpClient.StorageAccounts.ListKeysWithHttpMessagesAsync(rgName, storageAccountName).Result;
CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(storageAccountName, accountKeyResult.Body.Key1), useHttps: true);
var blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("sascontainer");
bool created = container.CreateIfNotExistsAsync().Result;
CloudPageBlob pageBlob = container.GetPageBlobReference(fileName);
byte[] blobContent = Encoding.UTF8.GetBytes("Application Package Test");
byte[] bytes = new byte[512]; // Page blob must be multiple of 512
System.Buffer.BlockCopy(blobContent, 0, bytes, 0, blobContent.Length);
pageBlob.UploadFromByteArrayAsync(bytes, 0, bytes.Length);
SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy();
sasConstraints.SharedAccessStartTime = DateTime.UtcNow.AddDays(-1);
sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddDays(2);
sasConstraints.Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write;
//Generate the shared access signature on the blob, setting the constraints directly on the signature.
string sasContainerToken = pageBlob.GetSharedAccessSignature(sasConstraints);
//Return the URI string for the container, including the SAS token.
applicationMediaLink = pageBlob.Uri + sasContainerToken;
}
return applicationMediaLink;
}
private GalleryApplication GetTestInputGalleryApplication()
{
return new GalleryApplication
{
Eula = "This is the gallery application EULA.",
Location = ComputeManagementTestUtilities.DefaultLocation,
SupportedOSType = OperatingSystemTypes.Windows,
PrivacyStatementUri = "www.privacystatement.com",
ReleaseNoteUri = "www.releasenote.com",
Description = "This is the gallery application description.",
};
}
private GalleryApplicationVersion GetTestInputGalleryApplicationVersion(string applicationMediaLink)
{
return new GalleryApplicationVersion
{
Location = ComputeManagementTestUtilities.DefaultLocation,
PublishingProfile = new GalleryApplicationVersionPublishingProfile
{
Source = new UserArtifactSource
{
MediaLink = applicationMediaLink
},
ManageActions = new UserArtifactManage
{
Install = "powershell -command \"Expand-Archive -Path test.zip -DestinationPath C:\\package\"",
Remove = "del C:\\package "
},
ReplicaCount = 1,
StorageAccountType = StorageAccountType.StandardLRS,
TargetRegions = new List<TargetRegion> {
new TargetRegion { Name = ComputeManagementTestUtilities.DefaultLocation, RegionalReplicaCount = 1, StorageAccountType = StorageAccountType.StandardLRS }
},
EndOfLifeDate = DateTime.Today.AddDays(10).Date
}
};
}
private void ValidateGalleryApplication(GalleryApplication applicationIn, GalleryApplication applicationOut)
{
if (applicationIn.Tags != null)
{
foreach (KeyValuePair<string, string> kvp in applicationIn.Tags)
{
Assert.Equal(kvp.Value, applicationOut.Tags[kvp.Key]);
}
}
Assert.Equal(applicationIn.Eula, applicationOut.Eula);
Assert.Equal(applicationIn.PrivacyStatementUri, applicationOut.PrivacyStatementUri);
Assert.Equal(applicationIn.ReleaseNoteUri, applicationOut.ReleaseNoteUri);
Assert.Equal(applicationIn.Location.ToLower(), applicationOut.Location.ToLower());
Assert.Equal(applicationIn.SupportedOSType, applicationOut.SupportedOSType);
if (!string.IsNullOrEmpty(applicationIn.Description))
{
Assert.Equal(applicationIn.Description, applicationOut.Description);
}
}
private void ValidateGalleryApplicationVersion(GalleryApplicationVersion applicationVersionIn, GalleryApplicationVersion applicationVersionOut)
{
Assert.False(string.IsNullOrEmpty(applicationVersionOut.ProvisioningState));
if (applicationVersionIn.Tags != null)
{
foreach (KeyValuePair<string, string> kvp in applicationVersionIn.Tags)
{
Assert.Equal(kvp.Value, applicationVersionOut.Tags[kvp.Key]);
}
}
Assert.Equal(applicationVersionIn.Location.ToLower(), applicationVersionOut.Location.ToLower());
Assert.False(string.IsNullOrEmpty(applicationVersionOut.PublishingProfile.Source.MediaLink),
"applicationVersionOut.PublishingProfile.Source.MediaLink is null or empty.");
Assert.NotNull(applicationVersionOut.PublishingProfile.EndOfLifeDate);
Assert.NotNull(applicationVersionOut.PublishingProfile.PublishedDate);
Assert.NotNull(applicationVersionOut.Id);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.ComponentModel;
using Lidgren.Network;
namespace Microsoft.Xna.Framework.Net
{
public class MonoGameNetworkConfiguration
{
public static IPAddress Broadcast = IPAddress.None;
}
internal class MonoGamerPeer
{
private BackgroundWorker MGServerWorker = new BackgroundWorker ();
bool done = false;
NetServer peer;
NetworkSession session;
AvailableNetworkSession availableSession;
string myLocalAddress = string.Empty;
IPEndPoint myLocalEndPoint = null;
Dictionary<long, NetConnection> pendingGamers = new Dictionary<long, NetConnection> ();
//Dictionary<long, NetConnection> connectedGamers = new Dictionary<long, NetConnection>();
bool online = false;
private static int port = 3074;
private static IPEndPoint m_masterServer;
private static int masterserverport = 6000;
private static string masterServer = "monolive.servegame.com";
internal static string applicationIdentifier = "monogame";
static MonoGamerPeer()
{
#if !WINDOWS_PHONE
// This code looks up the Guid for the host app , this is used to identify the
// application on the network . We use the Guid as that is unique to that application.
var assembly = System.Reflection.Assembly.GetAssembly(Game.Instance.GetType());
if (assembly != null)
{
object[] objects = assembly.GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), false);
if (objects.Length > 0)
{
applicationIdentifier = ((System.Runtime.InteropServices.GuidAttribute)objects[0]).Value;
}
}
#else
#endif
}
public MonoGamerPeer (NetworkSession session,AvailableNetworkSession availableSession)
{
this.session = session;
this.online = this.session.SessionType == NetworkSessionType.PlayerMatch;
this.availableSession = availableSession;
//MGServerWorker.WorkerReportsProgress = true;
MGServerWorker.WorkerSupportsCancellation = true;
MGServerWorker.DoWork += new DoWorkEventHandler (MGServer_DoWork);
MGServerWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler (MGServer_RunWorkerCompleted);
MGServerWorker.RunWorkerAsync ();
HookEvents ();
}
private void HookEvents ()
{
session.GameEnded += HandleSessionStateChanged;
session.SessionEnded += HandleSessionStateChanged;
session.GameStarted += HandleSessionStateChanged;
}
void HandleSessionStateChanged (object sender, EventArgs e)
{
#if !WINDOWS_PHONE
Game.Instance.Log("session state change");
#endif
SendSessionStateChange ();
if (session.SessionState == NetworkSessionState.Ended)
MGServerWorker.CancelAsync ();
}
internal void ShutDown ()
{
MGServerWorker.CancelAsync ();
}
private void MGServer_DoWork (object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
NetPeerConfiguration config = new NetPeerConfiguration (applicationIdentifier);
config.EnableMessageType (NetIncomingMessageType.DiscoveryRequest);
config.EnableMessageType (NetIncomingMessageType.DiscoveryResponse);
config.EnableMessageType (NetIncomingMessageType.NatIntroductionSuccess);
if (availableSession == null)
config.Port = port;
// create and start server
peer = new NetServer (config);
peer.Start ();
myLocalAddress = GetMyLocalIpAddress ();
IPAddress adr = IPAddress.Parse (myLocalAddress);
myLocalEndPoint = new IPEndPoint (adr, port);
// force a little wait until we have a LocalGamer otherwise things
// break. This is the first item in the queue so it shouldnt take long before we
// can continue.
while (session.LocalGamers.Count <= 0)
{
Thread.Sleep(10);
}
if (availableSession != null) {
if (!this.online) {
peer.Connect (availableSession.EndPoint);
} else {
RequestNATIntroduction (availableSession.EndPoint, peer);
}
} else {
if (this.online) {
IPAddress ipaddr = NetUtility.Resolve (masterServer);
if (ipaddr != null) {
m_masterServer = new IPEndPoint (ipaddr, masterserverport);
LocalNetworkGamer localMe = session.LocalGamers [0];
NetOutgoingMessage om = peer.CreateMessage ();
om.Write ((byte)0);
om.Write (session.AllGamers.Count);
om.Write (localMe.Gamertag);
om.Write (session.PrivateGamerSlots);
om.Write (session.MaxGamers);
om.Write (localMe.IsHost);
om.Write (myLocalEndPoint);
om.Write (peer.Configuration.AppIdentifier);
// send up session properties
int[] propertyData = new int[session.SessionProperties.Count * 2];
NetworkSessionProperties.WriteProperties (session.SessionProperties, propertyData);
for (int x = 0; x < propertyData.Length; x++) {
om.Write (propertyData [x]);
}
peer.SendUnconnectedMessage (om, m_masterServer); // send message to peer
} else {
throw new Exception ("Could not resolve live host");
}
}
}
// run until we are done
do {
NetIncomingMessage msg;
while ((msg = peer.ReadMessage ()) != null) {
switch (msg.MessageType) {
case NetIncomingMessageType.UnconnectedData :
break;
case NetIncomingMessageType.NatIntroductionSuccess:
#if !WINDOWS_PHONE
Game.Instance.Log("NAT punch through OK " + msg.SenderEndpoint);
#endif
peer.Connect (msg.SenderEndpoint);
break;
case NetIncomingMessageType.DiscoveryRequest:
//
// Server received a discovery request from a client; send a discovery response (with no extra data attached)
//
// Get the primary local gamer
LocalNetworkGamer localMe = session.LocalGamers [0];
NetOutgoingMessage om = peer.CreateMessage ();
om.Write (session.RemoteGamers.Count);
om.Write (localMe.Gamertag);
om.Write (session.PrivateGamerSlots);
om.Write (session.MaxGamers);
om.Write (localMe.IsHost);
int[] propertyData = new int[session.SessionProperties.Count * 2];
NetworkSessionProperties.WriteProperties (session.SessionProperties, propertyData);
for (int x = 0; x < propertyData.Length; x++) {
om.Write (propertyData [x]);
}
peer.SendDiscoveryResponse (om, msg.SenderEndpoint);
break;
case NetIncomingMessageType.VerboseDebugMessage:
case NetIncomingMessageType.DebugMessage:
case NetIncomingMessageType.WarningMessage:
case NetIncomingMessageType.ErrorMessage:
//
// Just print diagnostic messages to console
//
#if !WINDOWS_PHONE
Game.Instance.Log(msg.ReadString());
#endif
break;
case NetIncomingMessageType.StatusChanged:
NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte ();
if (status == NetConnectionStatus.Disconnected) {
#if !WINDOWS_PHONE
Game.Instance.Log(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " disconnected! from " + msg.SenderEndpoint);
#endif
CommandGamerLeft cgj = new CommandGamerLeft (msg.SenderConnection.RemoteUniqueIdentifier);
CommandEvent cmde = new CommandEvent (cgj);
session.commandQueue.Enqueue (cmde);
}
if (status == NetConnectionStatus.Connected) {
//
// A new player just connected!
//
if (!pendingGamers.ContainsKey (msg.SenderConnection.RemoteUniqueIdentifier)) {
#if !WINDOWS_PHONE
Game.Instance.Log(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " connected! from " + msg.SenderEndpoint);
#endif
pendingGamers.Add (msg.SenderConnection.RemoteUniqueIdentifier, msg.SenderConnection);
SendProfileRequest (msg.SenderConnection);
} else {
#if !WINDOWS_PHONE
Game.Instance.Log("Already have a connection for that user, this is probably due to both NAT intro requests working");
#endif
}
}
break;
case NetIncomingMessageType.Data:
NetworkMessageType mt = (NetworkMessageType)msg.ReadByte ();
switch (mt) {
case NetworkMessageType.Data:
byte[] data = new byte[msg.LengthBytes - 1];
msg.ReadBytes (data, 0, data.Length);
CommandEvent cme = new CommandEvent (new CommandReceiveData (msg.SenderConnection.RemoteUniqueIdentifier,
data));
session.commandQueue.Enqueue (cme);
break;
case NetworkMessageType.Introduction:
var introductionAddress = msg.ReadString ();
try {
IPEndPoint endPoint = ParseIPEndPoint (introductionAddress);
if (myLocalEndPoint.ToString () != endPoint.ToString () && !AlreadyConnected (endPoint)) {
#if !WINDOWS_PHONE
Game.Instance.Log("Received Introduction for: " + introductionAddress +
" and I am: " + myLocalEndPoint + " from: " + msg.SenderEndpoint);
#endif
peer.Connect (endPoint);
}
} catch (Exception exc) {
#if !WINDOWS_PHONE
Game.Instance.Log("Error parsing Introduction: " + introductionAddress + " : " + exc.Message);
#endif
}
break;
case NetworkMessageType.GamerProfile:
#if !WINDOWS_PHONE
Game.Instance.Log("Profile recieved from: " + NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier));
#endif
if (pendingGamers.ContainsKey (msg.SenderConnection.RemoteUniqueIdentifier)) {
pendingGamers.Remove (msg.SenderConnection.RemoteUniqueIdentifier);
msg.ReadInt32 ();
string gamerTag = msg.ReadString ();
msg.ReadInt32 ();
msg.ReadInt32 ();
GamerStates state = (GamerStates)msg.ReadInt32 ();
state &= ~GamerStates.Local;
CommandGamerJoined cgj = new CommandGamerJoined (msg.SenderConnection.RemoteUniqueIdentifier);
cgj.GamerTag = gamerTag;
cgj.State = state;
CommandEvent cmde = new CommandEvent (cgj);
session.commandQueue.Enqueue (cmde);
} else {
#if !WINDOWS_PHONE
Game.Instance.Log("We received a profile for an existing gamer. Need to update it.");
#endif
}
break;
case NetworkMessageType.RequestGamerProfile:
#if !WINDOWS_PHONE
Game.Instance.Log("Profile Request recieved from: " + msg.SenderEndpoint);
#endif
SendProfile (msg.SenderConnection);
break;
case NetworkMessageType.GamerStateChange:
GamerStates gamerstate = (GamerStates)msg.ReadInt32 ();
gamerstate &= ~GamerStates.Local;
#if !WINDOWS_PHONE
Game.Instance.Log("State Change from: " + msg.SenderEndpoint + " new State: " + gamerstate);
#endif
foreach (var gamer in session.RemoteGamers) {
if (gamer.RemoteUniqueIdentifier == msg.SenderConnection.RemoteUniqueIdentifier)
gamer.State = gamerstate;
}
break;
case NetworkMessageType.SessionStateChange:
NetworkSessionState sessionState = (NetworkSessionState)msg.ReadInt32 ();
foreach (var gamer in session.RemoteGamers) {
if (gamer.RemoteUniqueIdentifier == msg.SenderConnection.RemoteUniqueIdentifier) {
#if !WINDOWS_PHONE
Game.Instance.Log("Session State change from: " + NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) +
" session is now: " + sessionState);
#endif
if (gamer.IsHost && sessionState == NetworkSessionState.Playing) {
session.StartGame ();
}
}
}
break;
}
break;
}
}
// sleep to allow other processes to run smoothly
// This may need to be changed depending on network throughput
Thread.Sleep (1);
if (worker.CancellationPending) {
#if !WINDOWS_PHONE
Game.Instance.Log("worker CancellationPending");
#endif
e.Cancel = true;
done = true;
}
} while (!done);
}
private bool AlreadyConnected (IPEndPoint endPoint)
{
foreach (NetConnection player in peer.Connections) {
if (player.RemoteEndpoint == endPoint) {
return true;
}
}
return false;
}
private void MGServer_RunWorkerCompleted (object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true)) {
#if !WINDOWS_PHONE
Game.Instance.Log("Canceled");
#endif
} else if (!(e.Error == null)) {
#if !WINDOWS_PHONE
Game.Instance.Log("Error: " + e.Error.Message);
#endif
}
#if !WINDOWS_PHONE
Game.Instance.Log("worker Completed");
#endif
if (online && this.availableSession == null) {
// inform the master server we have closed
NetOutgoingMessage om = peer.CreateMessage ();
om.Write ((byte)3);
om.Write (this.session.Host.Gamertag);
om.Write (peer.Configuration.AppIdentifier);
peer.SendUnconnectedMessage (om, m_masterServer); // send message to peer
}
peer.Shutdown ("app exiting");
}
internal void SendProfile (NetConnection player)
{
NetOutgoingMessage om = peer.CreateMessage ();
om.Write ((byte)NetworkMessageType.GamerProfile);
om.Write (session.AllGamers.Count);
om.Write (session.LocalGamers [0].Gamertag);
om.Write (session.PrivateGamerSlots);
om.Write (session.MaxGamers);
om.Write ((int)session.LocalGamers[0].State);
#if !WINDOWS_PHONE
Game.Instance.Log("Sent profile to: " + NetUtility.ToHexString(player.RemoteUniqueIdentifier));
#endif
peer.SendMessage (om, player, NetDeliveryMethod.ReliableOrdered);
}
internal void SendProfileRequest (NetConnection player)
{
NetOutgoingMessage om = peer.CreateMessage ();
om.Write ((byte)NetworkMessageType.RequestGamerProfile);
#if !WINDOWS_PHONE
Game.Instance.Log("Sent profile request to: " + NetUtility.ToHexString(player.RemoteUniqueIdentifier));
#endif
peer.SendMessage (om, player, NetDeliveryMethod.ReliableOrdered);
}
internal void SendPeerIntroductions (NetworkGamer gamer)
{
NetConnection playerConnection = null;
foreach (NetConnection player in peer.Connections) {
if (player.RemoteUniqueIdentifier == gamer.RemoteUniqueIdentifier) {
playerConnection = player;
}
}
if (playerConnection == null) {
return;
}
foreach (NetConnection player in peer.Connections) {
#if !WINDOWS_PHONE
Game.Instance.Log("Introduction sent to: " + player.RemoteEndpoint);
#endif
NetOutgoingMessage om = peer.CreateMessage ();
om.Write ((byte)NetworkMessageType.Introduction);
om.Write (playerConnection.RemoteEndpoint.ToString ());
peer.SendMessage (om, player, NetDeliveryMethod.ReliableOrdered);
}
}
internal void SendGamerStateChange (NetworkGamer gamer)
{
#if !WINDOWS_PHONE
Game.Instance.Log("SendGamerStateChange " + gamer.RemoteUniqueIdentifier);
#endif
NetOutgoingMessage om = peer.CreateMessage ();
om.Write ((byte)NetworkMessageType.GamerStateChange);
om.Write ((int)gamer.State);
SendMessage (om, SendDataOptions.Reliable, gamer);
}
internal void SendSessionStateChange ()
{
#if !WINDOWS_PHONE
Game.Instance.Log("Send Session State Change");
#endif
NetOutgoingMessage om = peer.CreateMessage ();
om.Write ((byte)NetworkMessageType.SessionStateChange);
om.Write ((int)session.SessionState);
SendMessage (om, SendDataOptions.Reliable, null);
}
public static IPEndPoint ParseIPEndPoint (string endPoint)
{
string[] ep = endPoint.Split (':');
if (ep.Length != 2)
throw new FormatException ("Invalid endpoint format");
IPAddress ip;
if (!IPAddress.TryParse (ep [0], out ip)) {
throw new FormatException ("Invalid ip-adress");
}
int port;
if (!int.TryParse (ep [1], out port)) {
throw new FormatException ("Invalid port");
}
return new IPEndPoint (ip, port);
}
internal static string GetMyLocalIpAddress ()
{
string localIP = "?";
#if !WINDOWS_PHONE
IPHostEntry host;
host = Dns.GetHostEntry (Dns.GetHostName ());
foreach (IPAddress ip in host.AddressList) {
// We only want those of type InterNetwork
if (ip.AddressFamily == AddressFamily.InterNetwork) {
// We will return the first one in the list
localIP = ip.ToString ();
break;
}
}
#else
FindMyIP.MyIPAddress ip = new FindMyIP.MyIPAddress();
var addr = ip.Find();
localIP = addr.ToString();
#endif
return localIP;
}
/// <summary>
/// Used to Simulate the delay between computers
/// </summary>
public TimeSpan SimulatedLatency
{
get
{
#if DEBUG
if (peer != null)
return new TimeSpan(0,0,(int)peer.Configuration.SimulatedAverageLatency);
else
return new TimeSpan(0);
#else
return new TimeSpan(0);
#endif
}
set
{
#if DEBUG
if (peer != null) {
peer.Configuration.SimulatedMinimumLatency = (float)value.TotalSeconds;
}
#endif
}
}
/// <summary>
/// Used to simulate the number of packets you might expect to loose.
/// </summary>
public float SimulatedPacketLoss
{
get
{
#if DEBUG
if (peer != null)
return peer.Configuration.SimulatedLoss;
else
return 0.0f;
#else
return 0.0f;
#endif
}
set
{
#if DEBUG
if (peer != null) {
peer.Configuration.SimulatedLoss = value;
}
#endif
}
}
internal void DiscoverPeers ()
{
peer.DiscoverLocalPeers (port);
}
internal void SendData (
byte[] data,
SendDataOptions options)
{
this.SendMessage (NetworkMessageType.Data, data, options, null);
}
internal void SendData (
byte[] data,
SendDataOptions options,
NetworkGamer gamer)
{
this.SendMessage (NetworkMessageType.Data, data, options, gamer);
}
private void SendMessage (NetworkMessageType messageType, byte[] data, SendDataOptions options, NetworkGamer gamer)
{
NetOutgoingMessage om = peer.CreateMessage ();
om.Write ((byte)messageType);
om.Write (data);
SendMessage (om, options, gamer);
}
private void SendMessage (NetOutgoingMessage om, SendDataOptions options, NetworkGamer gamer)
{
//Console.WriteLine("Data to send: " + data.Length);
// foreach (NetConnection player in server.Connections) {
// // ... send information about every other player (actually including self)
// foreach (NetConnection otherPlayer in server.Connections) {
// if (gamer != null && gamer.RemoteUniqueIdentifier != otherPlayer.RemoteUniqueIdentifier) {
// continue;
// }
NetDeliveryMethod ndm = NetDeliveryMethod.Unreliable;
switch (options) {
case SendDataOptions.Reliable:
ndm = NetDeliveryMethod.ReliableSequenced;
break;
case SendDataOptions.ReliableInOrder:
ndm = NetDeliveryMethod.ReliableOrdered;
break;
case SendDataOptions.InOrder:
ndm = NetDeliveryMethod.UnreliableSequenced;
break;
case SendDataOptions.None:
ndm = NetDeliveryMethod.Unknown;
break;
}
// send message
//server.SendToAll (om, player, ndm);
peer.SendToAll (om, ndm);
// }
// }
}
static NetPeer netPeer;
static List<NetIncomingMessage> discoveryMsgs;
internal static void Find (NetworkSessionType sessionType)
{
NetPeerConfiguration config = new NetPeerConfiguration (applicationIdentifier);
if (sessionType == NetworkSessionType.PlayerMatch) {
config.EnableMessageType (NetIncomingMessageType.UnconnectedData);
config.EnableMessageType (NetIncomingMessageType.NatIntroductionSuccess);
} else {
config.EnableMessageType (NetIncomingMessageType.DiscoveryRequest);
}
if (MonoGameNetworkConfiguration.Broadcast != IPAddress.None)
{
config.BroadcastAddress = MonoGameNetworkConfiguration.Broadcast;
}
netPeer = new NetPeer (config);
netPeer.Start ();
if (sessionType == NetworkSessionType.PlayerMatch) {
GetServerList (netPeer);
} else {
netPeer.DiscoverLocalPeers (port);
}
DateTime now = DateTime.Now;
discoveryMsgs = new List<NetIncomingMessage> ();
do {
NetIncomingMessage msg;
while ((msg = netPeer.ReadMessage ()) != null) {
switch (msg.MessageType) {
case NetIncomingMessageType.DiscoveryResponse:
discoveryMsgs.Add (msg);
break;
case NetIncomingMessageType.UnconnectedData:
if (msg.SenderEndpoint.Equals (m_masterServer)) {
discoveryMsgs.Add (msg);
/*
* // it's from the master server - must be a host
IPEndPoint hostInternal = msg.ReadIPEndpoint();
IPEndPoint hostExternal = msg.ReadIPEndpoint();
m_hostList.Add(new IPEndPoint[] { hostInternal, hostExternal });
*/
}
break;
case NetIncomingMessageType.VerboseDebugMessage:
case NetIncomingMessageType.DebugMessage:
case NetIncomingMessageType.WarningMessage:
case NetIncomingMessageType.ErrorMessage:
//
// Just print diagnostic messages to console
//
#if DEBUG
Console.WriteLine ("Find: " + msg.ReadString ());
#endif
break;
}
}
} while ((DateTime.Now - now).Seconds <= 2);
netPeer.Shutdown ("Find shutting down");
}
/// <summary>
/// Contacts the Master Server on the net and gets a list of available host games
/// </summary>
/// <param name="netPeer"></param>
private static void GetServerList (NetPeer netPeer)
{
m_masterServer = new IPEndPoint (NetUtility.Resolve (masterServer), masterserverport);
NetOutgoingMessage listRequest = netPeer.CreateMessage ();
listRequest.Write ((byte)1);
listRequest.Write (netPeer.Configuration.AppIdentifier);
netPeer.SendUnconnectedMessage (listRequest, m_masterServer);
}
public static void RequestNATIntroduction (IPEndPoint host, NetPeer peer)
{
if (host == null) {
return;
}
if (m_masterServer == null)
throw new Exception ("Must connect to master server first!");
NetOutgoingMessage om = peer.CreateMessage ();
om.Write ((byte)2); // NAT intro request
// write internal ipendpoint
IPAddress addr = IPAddress.Parse (GetMyLocalIpAddress ());
om.Write (new IPEndPoint (addr, peer.Port));
// write external address of host to request introduction to
IPEndPoint hostEp = new IPEndPoint (host.Address, port);
om.Write (hostEp);
om.Write (peer.Configuration.AppIdentifier); // send the app id
peer.SendUnconnectedMessage (om, m_masterServer);
}
internal static void FindResults (List<AvailableNetworkSession> networkSessions)
{
foreach (NetIncomingMessage im in discoveryMsgs) {
AvailableNetworkSession available = new AvailableNetworkSession ();
switch (im.MessageType) {
case NetIncomingMessageType.DiscoveryResponse :
int currentGameCount = im.ReadInt32 ();
string gamerTag = im.ReadString ();
int openPrivateGamerSlots = im.ReadInt32 ();
int openPublicGamerSlots = im.ReadInt32 ();
bool isHost = im.ReadBoolean ();
NetworkSessionProperties properties = new NetworkSessionProperties ();
int[] propertyData = new int[properties.Count * 2];
for (int x = 0; x < propertyData.Length; x++) {
propertyData [x] = im.ReadInt32 ();
}
NetworkSessionProperties.ReadProperties (properties, propertyData);
available.SessionProperties = properties;
available.SessionType = NetworkSessionType.SystemLink;
available.CurrentGamerCount = currentGameCount;
available.HostGamertag = gamerTag;
available.OpenPrivateGamerSlots = openPrivateGamerSlots;
available.OpenPublicGamerSlots = openPublicGamerSlots;
available.EndPoint = im.SenderEndpoint;
available.InternalEndpont = null;
break;
case NetIncomingMessageType.UnconnectedData :
if (im.SenderEndpoint.Equals (m_masterServer)) {
currentGameCount = im.ReadInt32 ();
gamerTag = im.ReadString ();
openPrivateGamerSlots = im.ReadInt32 ();
openPublicGamerSlots = im.ReadInt32 ();
isHost = im.ReadBoolean ();
IPEndPoint hostInternal = im.ReadIPEndpoint ();
IPEndPoint hostExternal = im.ReadIPEndpoint ();
available.SessionType = NetworkSessionType.PlayerMatch;
available.CurrentGamerCount = currentGameCount;
available.HostGamertag = gamerTag;
available.OpenPrivateGamerSlots = openPrivateGamerSlots;
available.OpenPublicGamerSlots = openPublicGamerSlots;
// its data from the master server so it includes the internal and external endponts
available.EndPoint = hostExternal;
available.InternalEndpont = hostInternal;
}
break;
}
networkSessions.Add (available);
}
}
internal void UpdateLiveSession (NetworkSession networkSession)
{
if (peer != null && m_masterServer != null && networkSession.IsHost) {
NetOutgoingMessage om = peer.CreateMessage ();
om.Write ((byte)0);
om.Write (session.AllGamers.Count);
om.Write (session.LocalGamers [0].Gamertag);
om.Write (session.PrivateGamerSlots);
om.Write (session.MaxGamers);
om.Write (session.LocalGamers [0].IsHost);
IPAddress adr = IPAddress.Parse (GetMyLocalIpAddress ());
om.Write (new IPEndPoint (adr, port));
om.Write (peer.Configuration.AppIdentifier);
peer.SendUnconnectedMessage (om, m_masterServer); // send message to peer
}
}
internal bool IsReady { get { return this.peer != null; } }
}
}
#if WINDOWS_PHONE
namespace FindMyIP
{
using System;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
using System.Linq;
using System.Text;
public class MyIPAddress
{
Action<IPAddress> FoundCallback;
UdpAnySourceMulticastClient MulticastSocket;
const int PortNumber = 50000; // pick a number, any number
string MulticastMessage = "FIND-MY-IP-PLEASE" + new Random().Next().ToString();
public void Find(Action<IPAddress> callback)
{
FoundCallback = callback;
MulticastSocket = new UdpAnySourceMulticastClient(IPAddress.Parse("239.255.255.250"), PortNumber);
MulticastSocket.BeginJoinGroup((result) =>
{
try
{
MulticastSocket.EndJoinGroup(result);
GroupJoined(result);
}
catch (Exception ex)
{
Debug.WriteLine("EndjoinGroup exception {0}", ex.Message);
// This can happen eg when wifi is off
FoundCallback(null);
}
},
null);
}
void callback_send(IAsyncResult result)
{
}
byte[] MulticastData;
bool keepsearching;
void GroupJoined(IAsyncResult result)
{
MulticastData = Encoding.UTF8.GetBytes(MulticastMessage);
keepsearching = true;
MulticastSocket.BeginSendToGroup(MulticastData, 0, MulticastData.Length, callback_send, null);
while (keepsearching)
{
try
{
byte[] buffer = new byte[MulticastData.Length];
MulticastSocket.BeginReceiveFromGroup(buffer, 0, buffer.Length, DoneReceiveFromGroup, buffer);
}
catch (Exception ex)
{
Debug.WriteLine("Stopped Group read due to " + ex.Message);
keepsearching = false;
}
}
}
void DoneReceiveFromGroup(IAsyncResult result)
{
IPEndPoint where;
int responselength = MulticastSocket.EndReceiveFromGroup(result, out where);
byte[] buffer = result.AsyncState as byte[];
if (responselength == MulticastData.Length && buffer.SequenceEqual(MulticastData))
{
Debug.WriteLine("FOUND myself at " + where.Address.ToString());
keepsearching = false;
FoundCallback(where.Address);
}
}
static ManualResetEvent _clientDone = new ManualResetEvent(false);
public IPAddress Find()
{
var ip = IPAddress.None;
_clientDone.Reset();
Find((a) =>
{
ip = a;
_clientDone.Set();
});
_clientDone.WaitOne(1000);
return ip;
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AndInt32()
{
var test = new SimpleBinaryOpTest__AndInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AndInt32
{
private const int VectorSize = 32;
private const int ElementCount = VectorSize / sizeof(Int32);
private static Int32[] _data1 = new Int32[ElementCount];
private static Int32[] _data2 = new Int32[ElementCount];
private static Vector256<Int32> _clsVar1;
private static Vector256<Int32> _clsVar2;
private Vector256<Int32> _fld1;
private Vector256<Int32> _fld2;
private SimpleBinaryOpTest__DataTable<Int32> _dataTable;
static SimpleBinaryOpTest__AndInt32()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__AndInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int32>(_data1, _data2, new Int32[ElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.And(
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.And(
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.And(
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.And(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr);
var result = Avx2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AndInt32();
var result = Avx2.And(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.And(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Int32> left, Vector256<Int32> right, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[ElementCount];
Int32[] inArray2 = new Int32[ElementCount];
Int32[] outArray = new Int32[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[ElementCount];
Int32[] inArray2 = new Int32[ElementCount];
Int32[] outArray = new Int32[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
if ((int)(left[0] & right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((int)(left[i] & right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.And)}<Int32>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.ServiceModel.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.ServiceModel
{
public enum AddressFilterMode
{
Exact = 0,
Prefix = 1,
Any = 2,
}
public enum AuditLevel
{
None = 0,
Success = 1,
Failure = 2,
SuccessOrFailure = 3,
}
public enum AuditLogLocation
{
Default = 0,
Application = 1,
Security = 2,
}
public enum BasicHttpMessageCredentialType
{
UserName = 0,
Certificate = 1,
}
public enum BasicHttpSecurityMode
{
None = 0,
Transport = 1,
Message = 2,
TransportWithMessageCredential = 3,
TransportCredentialOnly = 4,
}
public enum CommunicationState
{
Created = 0,
Opening = 1,
Opened = 2,
Closing = 3,
Closed = 4,
Faulted = 5,
}
public enum ConcurrencyMode
{
Single = 0,
Reentrant = 1,
Multiple = 2,
}
public enum DeadLetterQueue
{
None = 0,
System = 1,
Custom = 2,
}
public enum HostNameComparisonMode
{
StrongWildcard = 0,
Exact = 1,
WeakWildcard = 2,
}
public enum HttpClientCredentialType
{
None = 0,
Basic = 1,
Digest = 2,
Ntlm = 3,
Windows = 4,
Certificate = 5,
}
public enum HttpProxyCredentialType
{
None = 0,
Basic = 1,
Digest = 2,
Ntlm = 3,
Windows = 4,
}
public enum ImpersonationOption
{
NotAllowed = 0,
Allowed = 1,
Required = 2,
}
public enum InstanceContextMode
{
PerSession = 0,
PerCall = 1,
Single = 2,
}
public enum MessageCredentialType
{
None = 0,
Windows = 1,
UserName = 2,
Certificate = 3,
IssuedToken = 4,
}
public enum MsmqAuthenticationMode
{
None = 0,
WindowsDomain = 1,
Certificate = 2,
}
public enum MsmqEncryptionAlgorithm
{
RC4Stream = 0,
Aes = 1,
}
public enum MsmqSecureHashAlgorithm
{
MD5 = 0,
Sha1 = 1,
Sha256 = 2,
Sha512 = 3,
}
public enum NetMsmqSecurityMode
{
None = 0,
Transport = 1,
Message = 2,
Both = 3,
}
public enum NetNamedPipeSecurityMode
{
None = 0,
Transport = 1,
}
public enum OperationFormatStyle
{
Document = 0,
Rpc = 1,
}
public enum OperationFormatUse
{
Literal = 0,
Encoded = 1,
}
public enum PeerMessageOrigination
{
Local = 0,
Remote = 1,
}
public enum PeerMessagePropagation
{
None = 0,
Local = 1,
Remote = 2,
LocalAndRemote = 3,
}
public enum PeerTransportCredentialType
{
Password = 0,
Certificate = 1,
}
public enum QueuedDeliveryRequirementsMode
{
Allowed = 0,
Required = 1,
NotAllowed = 2,
}
public enum QueueTransferProtocol
{
Native = 0,
Srmp = 1,
SrmpSecure = 2,
}
public enum ReceiveErrorHandling
{
Fault = 0,
Drop = 1,
Reject = 2,
Move = 3,
}
public enum ReleaseInstanceMode
{
None = 0,
BeforeCall = 1,
AfterCall = 2,
BeforeAndAfterCall = 3,
}
public enum SecurityMode
{
None = 0,
Transport = 1,
Message = 2,
TransportWithMessageCredential = 3,
}
public enum SessionMode
{
Allowed = 0,
Required = 1,
NotAllowed = 2,
}
public enum TcpClientCredentialType
{
None = 0,
Windows = 1,
Certificate = 2,
}
public enum TransactionFlowOption
{
NotAllowed = 0,
Allowed = 1,
Mandatory = 2,
}
public enum TransferMode
{
Buffered = 0,
Streamed = 1,
StreamedRequest = 2,
StreamedResponse = 3,
}
public enum WSDualHttpSecurityMode
{
None = 0,
Message = 1,
}
public enum WSFederationHttpSecurityMode
{
None = 0,
Message = 1,
TransportWithMessageCredential = 2,
}
public enum WSMessageEncoding
{
Text = 0,
Mtom = 1,
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Diagnostics;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Globalization;
using System.Security;
namespace System.ServiceProcess
{
/// This class represents an NT service. It allows you to connect to a running or stopped service
/// and manipulate it or get information about it.
public class ServiceController : IDisposable
{
private readonly string _machineName;
private readonly ManualResetEvent _waitForStatusSignal = new ManualResetEvent(false);
private const string DefaultMachineName = ".";
private string _name;
private string _eitherName;
private string _displayName;
private int _commandsAccepted;
private bool _statusGenerated;
private int _type;
private bool _disposed;
private SafeServiceHandle _serviceManagerHandle;
private ServiceControllerStatus _status;
private ServiceController[] _dependentServices;
private ServiceController[] _servicesDependedOn;
private const int SERVICENAMEMAXLENGTH = 80;
private const int DISPLAYNAMEBUFFERSIZE = 256;
/// Creates a ServiceController object, based on service name.
public ServiceController(string name)
: this(name, DefaultMachineName)
{
}
/// Creates a ServiceController object, based on machine and service name.
public ServiceController(string name, string machineName)
{
if (!CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.BadMachineName, machineName));
if (string.IsNullOrEmpty(name))
throw new ArgumentException(SR.Format(SR.InvalidParameter, "name", name));
_machineName = machineName;
_eitherName = name;
_type = Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_ALL;
}
/// Used by the GetServices and GetDevices methods. Avoids duplicating work by the static
/// methods and our own GenerateInfo().
private ServiceController(string machineName, Interop.mincore.ENUM_SERVICE_STATUS status)
{
if (!CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.BadMachineName, machineName));
_machineName = machineName;
_name = status.serviceName;
_displayName = status.displayName;
_commandsAccepted = status.controlsAccepted;
_status = (ServiceControllerStatus)status.currentState;
_type = status.serviceType;
_statusGenerated = true;
}
/// Used by the GetServicesInGroup method.
private ServiceController(string machineName, Interop.mincore.ENUM_SERVICE_STATUS_PROCESS status)
{
if (!CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.BadMachineName, machineName));
_machineName = machineName;
_name = status.serviceName;
_displayName = status.displayName;
_commandsAccepted = status.controlsAccepted;
_status = (ServiceControllerStatus)status.currentState;
_type = status.serviceType;
_statusGenerated = true;
}
/// Tells if the service referenced by this object can be paused.
public bool CanPauseAndContinue
{
get
{
GenerateStatus();
return (_commandsAccepted & Interop.mincore.AcceptOptions.ACCEPT_PAUSE_CONTINUE) != 0;
}
}
/// Tells if the service is notified when system shutdown occurs.
public bool CanShutdown
{
get
{
GenerateStatus();
return (_commandsAccepted & Interop.mincore.AcceptOptions.ACCEPT_SHUTDOWN) != 0;
}
}
/// Tells if the service referenced by this object can be stopped.
public bool CanStop
{
get
{
GenerateStatus();
return (_commandsAccepted & Interop.mincore.AcceptOptions.ACCEPT_STOP) != 0;
}
}
/// The descriptive name shown for this service in the Service applet.
public string DisplayName
{
get
{
if (_displayName == null)
GenerateNames();
return _displayName;
}
}
/// The set of services that depend on this service. These are the services that will be stopped if
/// this service is stopped.
public ServiceController[] DependentServices
{
get
{
if (_dependentServices == null)
{
IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_ENUMERATE_DEPENDENTS);
try
{
// figure out how big a buffer we need to get the info
int bytesNeeded = 0;
int numEnumerated = 0;
bool result = Interop.mincore.EnumDependentServices(serviceHandle, Interop.mincore.ServiceState.SERVICE_STATE_ALL, IntPtr.Zero, 0,
ref bytesNeeded, ref numEnumerated);
if (result)
{
_dependentServices = Array.Empty<ServiceController>();
return _dependentServices;
}
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.mincore.Errors.ERROR_MORE_DATA)
throw new Win32Exception(lastError);
// allocate the buffer
IntPtr enumBuffer = Marshal.AllocHGlobal((IntPtr)bytesNeeded);
try
{
// get all the info
result = Interop.mincore.EnumDependentServices(serviceHandle, Interop.mincore.ServiceState.SERVICE_STATE_ALL, enumBuffer, bytesNeeded,
ref bytesNeeded, ref numEnumerated);
if (!result)
throw new Win32Exception();
// for each of the entries in the buffer, create a new ServiceController object.
_dependentServices = new ServiceController[numEnumerated];
for (int i = 0; i < numEnumerated; i++)
{
Interop.mincore.ENUM_SERVICE_STATUS status = new Interop.mincore.ENUM_SERVICE_STATUS();
IntPtr structPtr = (IntPtr)((long)enumBuffer + (i * Marshal.SizeOf<Interop.mincore.ENUM_SERVICE_STATUS>()));
Marshal.PtrToStructure(structPtr, status);
_dependentServices[i] = new ServiceController(_machineName, status);
}
}
finally
{
Marshal.FreeHGlobal(enumBuffer);
}
}
finally
{
Interop.mincore.CloseServiceHandle(serviceHandle);
}
}
return _dependentServices;
}
}
/// The name of the machine on which this service resides.
public string MachineName
{
get
{
return _machineName;
}
}
/// Returns the short name of the service referenced by this object.
public string ServiceName
{
get
{
if (_name == null)
GenerateNames();
return _name;
}
}
public unsafe ServiceController[] ServicesDependedOn
{
get
{
if (_servicesDependedOn != null)
return _servicesDependedOn;
IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_QUERY_CONFIG);
try
{
int bytesNeeded = 0;
bool success = Interop.mincore.QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out bytesNeeded);
if (success)
{
_servicesDependedOn = Array.Empty<ServiceController>();
return _servicesDependedOn;
}
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.mincore.Errors.ERROR_INSUFFICIENT_BUFFER)
throw new Win32Exception(lastError);
// get the info
IntPtr bufPtr = Marshal.AllocHGlobal((IntPtr)bytesNeeded);
try
{
success = Interop.mincore.QueryServiceConfig(serviceHandle, bufPtr, bytesNeeded, out bytesNeeded);
if (!success)
throw new Win32Exception(Marshal.GetLastWin32Error());
Interop.mincore.QUERY_SERVICE_CONFIG config = new Interop.mincore.QUERY_SERVICE_CONFIG();
Marshal.PtrToStructure(bufPtr, config);
Dictionary<string, ServiceController> dependencyHash = null;
char* dependencyChar = config.lpDependencies;
if (dependencyChar != null)
{
// lpDependencies points to the start of multiple null-terminated strings. The list is
// double-null terminated.
int length = 0;
dependencyHash = new Dictionary<string, ServiceController>();
while (*(dependencyChar + length) != '\0')
{
length++;
if (*(dependencyChar + length) == '\0')
{
string dependencyNameStr = new string(dependencyChar, 0, length);
dependencyChar = dependencyChar + length + 1;
length = 0;
if (dependencyNameStr.StartsWith("+", StringComparison.Ordinal))
{
// this entry is actually a service load group
Interop.mincore.ENUM_SERVICE_STATUS_PROCESS[] loadGroup = GetServicesInGroup(_machineName, dependencyNameStr.Substring(1));
foreach (Interop.mincore.ENUM_SERVICE_STATUS_PROCESS groupMember in loadGroup)
{
if (!dependencyHash.ContainsKey(groupMember.serviceName))
dependencyHash.Add(groupMember.serviceName, new ServiceController(MachineName, groupMember));
}
}
else
{
if (!dependencyHash.ContainsKey(dependencyNameStr))
dependencyHash.Add(dependencyNameStr, new ServiceController(dependencyNameStr, MachineName));
}
}
}
}
if (dependencyHash != null)
{
_servicesDependedOn = new ServiceController[dependencyHash.Count];
dependencyHash.Values.CopyTo(_servicesDependedOn, 0);
}
else
{
_servicesDependedOn = Array.Empty<ServiceController>();
}
return _servicesDependedOn;
}
finally
{
Marshal.FreeHGlobal(bufPtr);
}
}
finally
{
Interop.mincore.CloseServiceHandle(serviceHandle);
}
}
}
public SafeHandle ServiceHandle
{
get
{
return new SafeServiceHandle(GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_ALL_ACCESS));
}
}
/// Gets the status of the service referenced by this object, e.g., Running, Stopped, etc.
public ServiceControllerStatus Status
{
get
{
GenerateStatus();
return _status;
}
}
/// Gets the type of service that this object references.
public ServiceType ServiceType
{
get
{
GenerateStatus();
return (ServiceType)_type;
}
}
private static bool CheckMachineName(string value)
{
return !string.IsNullOrWhiteSpace(value) && value.IndexOf('\\') == -1;
}
private void Close()
{
}
public void Dispose()
{
Dispose(true);
}
/// Disconnects this object from the service and frees any allocated resources.
protected virtual void Dispose(bool disposing)
{
if (_serviceManagerHandle != null)
{
_serviceManagerHandle.Dispose();
_serviceManagerHandle = null;
}
_statusGenerated = false;
_type = Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_ALL;
_disposed = true;
}
private unsafe void GenerateStatus()
{
if (!_statusGenerated)
{
IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_QUERY_STATUS);
try
{
Interop.mincore.SERVICE_STATUS svcStatus = new Interop.mincore.SERVICE_STATUS();
bool success = Interop.mincore.QueryServiceStatus(serviceHandle, &svcStatus);
if (!success)
throw new Win32Exception(Marshal.GetLastWin32Error());
_commandsAccepted = svcStatus.controlsAccepted;
_status = (ServiceControllerStatus)svcStatus.currentState;
_type = svcStatus.serviceType;
_statusGenerated = true;
}
finally
{
Interop.mincore.CloseServiceHandle(serviceHandle);
}
}
}
private unsafe void GenerateNames()
{
if (_machineName.Length == 0)
throw new ArgumentException(SR.NoMachineName);
IntPtr databaseHandle = IntPtr.Zero;
IntPtr memory = IntPtr.Zero;
int bytesNeeded;
int servicesReturned;
int resumeHandle = 0;
try
{
databaseHandle = GetDataBaseHandleWithEnumerateAccess(_machineName);
Interop.mincore.EnumServicesStatusEx(
databaseHandle,
Interop.mincore.ServiceControllerOptions.SC_ENUM_PROCESS_INFO,
Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_WIN32,
Interop.mincore.StatusOptions.STATUS_ALL,
IntPtr.Zero,
0,
out bytesNeeded,
out servicesReturned,
ref resumeHandle,
null);
memory = Marshal.AllocHGlobal(bytesNeeded);
Interop.mincore.EnumServicesStatusEx(
databaseHandle,
Interop.mincore.ServiceControllerOptions.SC_ENUM_PROCESS_INFO,
Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_WIN32,
Interop.mincore.StatusOptions.STATUS_ALL,
memory,
bytesNeeded,
out bytesNeeded,
out servicesReturned,
ref resumeHandle,
null);
// Since the service name of one service cannot be equal to the
// service or display name of another service, we can safely
// loop through all services checking if either the service or
// display name matches the user given name. If there is a
// match, then we've found the service.
for (int i = 0; i < servicesReturned; i++)
{
IntPtr structPtr = (IntPtr)((long)memory + (i * Marshal.SizeOf<Interop.mincore.ENUM_SERVICE_STATUS_PROCESS>()));
Interop.mincore.ENUM_SERVICE_STATUS_PROCESS status = new Interop.mincore.ENUM_SERVICE_STATUS_PROCESS();
Marshal.PtrToStructure(structPtr, status);
if (string.Equals(_eitherName, status.serviceName, StringComparison.OrdinalIgnoreCase) ||
string.Equals(_eitherName, status.displayName, StringComparison.OrdinalIgnoreCase))
{
if (_name == null)
{
_name = status.serviceName;
}
if (_displayName == null)
{
_displayName = status.displayName;
}
_eitherName = string.Empty;
return;
}
}
throw new InvalidOperationException(SR.Format(SR.NoService, _eitherName, _machineName));
}
finally
{
Marshal.FreeHGlobal(memory);
if (databaseHandle != IntPtr.Zero)
{
Interop.mincore.CloseServiceHandle(databaseHandle);
}
}
}
private static IntPtr GetDataBaseHandleWithAccess(string machineName, int serviceControlManagerAccess)
{
IntPtr databaseHandle = IntPtr.Zero;
if (machineName.Equals(DefaultMachineName) || machineName.Length == 0)
{
databaseHandle = Interop.mincore.OpenSCManager(null, null, serviceControlManagerAccess);
}
else
{
databaseHandle = Interop.mincore.OpenSCManager(machineName, null, serviceControlManagerAccess);
}
if (databaseHandle == IntPtr.Zero)
{
Exception inner = new Win32Exception(Marshal.GetLastWin32Error());
throw new InvalidOperationException(SR.Format(SR.OpenSC, machineName), inner);
}
return databaseHandle;
}
private void GetDataBaseHandleWithConnectAccess()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
// get a handle to SCM with connect access and store it in serviceManagerHandle field.
if (_serviceManagerHandle == null)
{
_serviceManagerHandle = new SafeServiceHandle(GetDataBaseHandleWithAccess(_machineName, Interop.mincore.ServiceControllerOptions.SC_MANAGER_CONNECT));
}
}
private static IntPtr GetDataBaseHandleWithEnumerateAccess(string machineName)
{
return GetDataBaseHandleWithAccess(machineName, Interop.mincore.ServiceControllerOptions.SC_MANAGER_ENUMERATE_SERVICE);
}
/// Gets all the device-driver services on the local machine.
public static ServiceController[] GetDevices()
{
return GetDevices(DefaultMachineName);
}
/// Gets all the device-driver services in the machine specified.
public static ServiceController[] GetDevices(string machineName)
{
return GetServicesOfType(machineName, Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_DRIVER);
}
/// Opens a handle for the current service. The handle must be closed with
/// a call to Interop.CloseServiceHandle().
private IntPtr GetServiceHandle(int desiredAccess)
{
GetDataBaseHandleWithConnectAccess();
IntPtr serviceHandle = Interop.mincore.OpenService(_serviceManagerHandle.DangerousGetHandle(), ServiceName, desiredAccess);
if (serviceHandle == IntPtr.Zero)
{
Exception inner = new Win32Exception(Marshal.GetLastWin32Error());
throw new InvalidOperationException(SR.Format(SR.OpenService, ServiceName, _machineName), inner);
}
return serviceHandle;
}
/// Gets the services (not including device-driver services) on the local machine.
public static ServiceController[] GetServices()
{
return GetServices(DefaultMachineName);
}
/// Gets the services (not including device-driver services) on the machine specified.
public static ServiceController[] GetServices(string machineName)
{
return GetServicesOfType(machineName, Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_WIN32);
}
/// Helper function for ServicesDependedOn.
private static Interop.mincore.ENUM_SERVICE_STATUS_PROCESS[] GetServicesInGroup(string machineName, string group)
{
return GetServices<Interop.mincore.ENUM_SERVICE_STATUS_PROCESS>(machineName, Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_WIN32, group, status => { return status; });
}
/// Helper function for GetDevices and GetServices.
private static ServiceController[] GetServicesOfType(string machineName, int serviceType)
{
if (!CheckMachineName(machineName))
throw new ArgumentException(SR.Format(SR.BadMachineName, machineName));
return GetServices<ServiceController>(machineName, serviceType, null, status => { return new ServiceController(machineName, status); });
}
/// Helper for GetDevices, GetServices, and ServicesDependedOn
private static T[] GetServices<T>(string machineName, int serviceType, string group, Func<Interop.mincore.ENUM_SERVICE_STATUS_PROCESS, T> selector)
{
IntPtr databaseHandle = IntPtr.Zero;
IntPtr memory = IntPtr.Zero;
int bytesNeeded;
int servicesReturned;
int resumeHandle = 0;
T[] services;
try
{
databaseHandle = GetDataBaseHandleWithEnumerateAccess(machineName);
Interop.mincore.EnumServicesStatusEx(
databaseHandle,
Interop.mincore.ServiceControllerOptions.SC_ENUM_PROCESS_INFO,
serviceType,
Interop.mincore.StatusOptions.STATUS_ALL,
IntPtr.Zero,
0,
out bytesNeeded,
out servicesReturned,
ref resumeHandle,
group);
memory = Marshal.AllocHGlobal((IntPtr)bytesNeeded);
//
// Get the set of services
//
Interop.mincore.EnumServicesStatusEx(
databaseHandle,
Interop.mincore.ServiceControllerOptions.SC_ENUM_PROCESS_INFO,
serviceType,
Interop.mincore.StatusOptions.STATUS_ALL,
memory,
bytesNeeded,
out bytesNeeded,
out servicesReturned,
ref resumeHandle,
group);
//
// Go through the block of memory it returned to us and select the results
//
services = new T[servicesReturned];
for (int i = 0; i < servicesReturned; i++)
{
IntPtr structPtr = (IntPtr)((long)memory + (i * Marshal.SizeOf<Interop.mincore.ENUM_SERVICE_STATUS_PROCESS>()));
Interop.mincore.ENUM_SERVICE_STATUS_PROCESS status = new Interop.mincore.ENUM_SERVICE_STATUS_PROCESS();
Marshal.PtrToStructure(structPtr, status);
services[i] = selector(status);
}
}
finally
{
Marshal.FreeHGlobal(memory);
if (databaseHandle != IntPtr.Zero)
{
Interop.mincore.CloseServiceHandle(databaseHandle);
}
}
return services;
}
/// Suspends a service's operation.
public unsafe void Pause()
{
IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_PAUSE_CONTINUE);
try
{
Interop.mincore.SERVICE_STATUS status = new Interop.mincore.SERVICE_STATUS();
bool result = Interop.mincore.ControlService(serviceHandle, Interop.mincore.ControlOptions.CONTROL_PAUSE, &status);
if (!result)
{
Exception inner = new Win32Exception(Marshal.GetLastWin32Error());
throw new InvalidOperationException(SR.Format(SR.PauseService, ServiceName, _machineName), inner);
}
}
finally
{
Interop.mincore.CloseServiceHandle(serviceHandle);
}
}
/// Continues a service after it has been paused.
public unsafe void Continue()
{
IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_PAUSE_CONTINUE);
try
{
Interop.mincore.SERVICE_STATUS status = new Interop.mincore.SERVICE_STATUS();
bool result = Interop.mincore.ControlService(serviceHandle, Interop.mincore.ControlOptions.CONTROL_CONTINUE, &status);
if (!result)
{
Exception inner = new Win32Exception(Marshal.GetLastWin32Error());
throw new InvalidOperationException(SR.Format(SR.ResumeService, ServiceName, _machineName), inner);
}
}
finally
{
Interop.mincore.CloseServiceHandle(serviceHandle);
}
}
/// Refreshes all property values.
public void Refresh()
{
_statusGenerated = false;
_dependentServices = null;
_servicesDependedOn = null;
}
/// Starts the service.
public void Start()
{
Start(Array.Empty<string>());
}
/// Starts a service in the machine specified.
public void Start(string[] args)
{
if (args == null)
throw new ArgumentNullException("args");
IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_START);
try
{
IntPtr[] argPtrs = new IntPtr[args.Length];
int i = 0;
try
{
for (i = 0; i < args.Length; i++)
{
if (args[i] == null)
throw new ArgumentNullException(SR.ArgsCantBeNull, "args");
argPtrs[i] = Marshal.StringToHGlobalUni(args[i]);
}
}
catch
{
for (int j = 0; j < i; j++)
Marshal.FreeHGlobal(argPtrs[i]);
throw;
}
GCHandle argPtrsHandle = new GCHandle();
try
{
argPtrsHandle = GCHandle.Alloc(argPtrs, GCHandleType.Pinned);
bool result = Interop.mincore.StartService(serviceHandle, args.Length, (IntPtr)argPtrsHandle.AddrOfPinnedObject());
if (!result)
{
Exception inner = new Win32Exception(Marshal.GetLastWin32Error());
throw new InvalidOperationException(SR.Format(SR.CannotStart, ServiceName, _machineName), inner);
}
}
finally
{
for (i = 0; i < args.Length; i++)
Marshal.FreeHGlobal(argPtrs[i]);
if (argPtrsHandle.IsAllocated)
argPtrsHandle.Free();
}
}
finally
{
Interop.mincore.CloseServiceHandle(serviceHandle);
}
}
/// Stops the service. If any other services depend on this one for operation,
/// they will be stopped first. The DependentServices property lists this set
/// of services.
public unsafe void Stop()
{
IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_STOP);
try
{
// Before stopping this service, stop all the dependent services that are running.
// (It's OK not to cache the result of getting the DependentServices property because it caches on its own.)
for (int i = 0; i < DependentServices.Length; i++)
{
ServiceController currentDependent = DependentServices[i];
currentDependent.Refresh();
if (currentDependent.Status != ServiceControllerStatus.Stopped)
{
currentDependent.Stop();
currentDependent.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 30));
}
}
Interop.mincore.SERVICE_STATUS status = new Interop.mincore.SERVICE_STATUS();
bool result = Interop.mincore.ControlService(serviceHandle, Interop.mincore.ControlOptions.CONTROL_STOP, &status);
if (!result)
{
Exception inner = new Win32Exception(Marshal.GetLastWin32Error());
throw new InvalidOperationException(SR.Format(SR.StopService, ServiceName, _machineName), inner);
}
}
finally
{
Interop.mincore.CloseServiceHandle(serviceHandle);
}
}
/// Waits infinitely until the service has reached the given status.
public void WaitForStatus(ServiceControllerStatus desiredStatus)
{
WaitForStatus(desiredStatus, TimeSpan.MaxValue);
}
/// Waits until the service has reached the given status or until the specified time
/// has expired
public void WaitForStatus(ServiceControllerStatus desiredStatus, TimeSpan timeout)
{
if (!Enum.IsDefined(typeof(ServiceControllerStatus), desiredStatus))
throw new ArgumentException(SR.Format(SR.InvalidEnumArgument, "desiredStatus", (int)desiredStatus, typeof(ServiceControllerStatus)));
DateTime start = DateTime.UtcNow;
Refresh();
while (Status != desiredStatus)
{
if (DateTime.UtcNow - start > timeout)
throw new System.ServiceProcess.TimeoutException(SR.Timeout);
_waitForStatusSignal.WaitOne(250);
Refresh();
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
using System.Numerics;
#endif
using System.Text;
using System.IO;
using System.Xml;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
internal enum ReadType
{
Read,
ReadAsInt32,
ReadAsBytes,
ReadAsString,
ReadAsDecimal,
ReadAsDateTime,
#if !NET20
ReadAsDateTimeOffset
#endif
}
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to JSON text data.
/// </summary>
public class JsonTextReader : JsonReader, IJsonLineInfo
{
private const char UnicodeReplacementChar = '\uFFFD';
private readonly TextReader _reader;
private char[] _chars;
private int _charsUsed;
private int _charPos;
private int _lineStartPos;
private int _lineNumber;
private bool _isEndOfFile;
private StringBuffer _buffer;
private StringReference _stringReference;
/// <summary>
/// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>.
/// </summary>
/// <param name="reader">The <c>TextReader</c> containing the XML data to read.</param>
public JsonTextReader(TextReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
_reader = reader;
_lineNumber = 1;
_chars = new char[1025];
}
#if DEBUG
internal void SetCharBuffer(char[] chars)
{
_chars = chars;
}
#endif
private StringBuffer GetBuffer()
{
if (_buffer == null)
{
_buffer = new StringBuffer(1025);
}
else
{
_buffer.Position = 0;
}
return _buffer;
}
private void OnNewLine(int pos)
{
_lineNumber++;
_lineStartPos = pos - 1;
}
private void ParseString(char quote)
{
_charPos++;
ShiftBufferIfNeeded();
ReadStringIntoBuffer(quote);
if (_readType == ReadType.ReadAsBytes)
{
byte[] data;
if (_stringReference.Length == 0)
{
data = new byte[0];
}
else
{
data = Convert.FromBase64CharArray(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length);
}
SetToken(JsonToken.Bytes, data);
}
else if (_readType == ReadType.ReadAsString)
{
string text = _stringReference.ToString();
SetToken(JsonToken.String, text);
_quoteChar = quote;
}
else
{
string text = _stringReference.ToString();
if (_dateParseHandling != DateParseHandling.None)
{
DateParseHandling dateParseHandling;
if (_readType == ReadType.ReadAsDateTime)
dateParseHandling = DateParseHandling.DateTime;
#if !NET20
else if (_readType == ReadType.ReadAsDateTimeOffset)
dateParseHandling = DateParseHandling.DateTimeOffset;
#endif
else
dateParseHandling = _dateParseHandling;
object dt;
if (DateTimeUtils.TryParseDateTime(text, dateParseHandling, DateTimeZoneHandling, out dt))
{
SetToken(JsonToken.Date, dt);
return;
}
}
SetToken(JsonToken.String, text);
_quoteChar = quote;
}
}
private static void BlockCopyChars(char[] src, int srcOffset, char[] dst, int dstOffset, int count)
{
const int charByteCount = 2;
Buffer.BlockCopy(src, srcOffset * charByteCount, dst, dstOffset * charByteCount, count * charByteCount);
}
private void ShiftBufferIfNeeded()
{
// once in the last 10% of the buffer shift the remainling content to the start to avoid
// unnessesarly increasing the buffer size when reading numbers/strings
int length = _chars.Length;
if (length - _charPos <= length * 0.1)
{
int count = _charsUsed - _charPos;
if (count > 0)
BlockCopyChars(_chars, _charPos, _chars, 0, count);
_lineStartPos -= _charPos;
_charPos = 0;
_charsUsed = count;
_chars[_charsUsed] = '\0';
}
}
private int ReadData(bool append)
{
return ReadData(append, 0);
}
private int ReadData(bool append, int charsRequired)
{
if (_isEndOfFile)
return 0;
// char buffer is full
if (_charsUsed + charsRequired >= _chars.Length - 1)
{
if (append)
{
// copy to new array either double the size of the current or big enough to fit required content
int newArrayLength = Math.Max(_chars.Length * 2, _charsUsed + charsRequired + 1);
// increase the size of the buffer
char[] dst = new char[newArrayLength];
BlockCopyChars(_chars, 0, dst, 0, _chars.Length);
_chars = dst;
}
else
{
int remainingCharCount = _charsUsed - _charPos;
if (remainingCharCount + charsRequired + 1 >= _chars.Length)
{
// the remaining count plus the required is bigger than the current buffer size
char[] dst = new char[remainingCharCount + charsRequired + 1];
if (remainingCharCount > 0)
BlockCopyChars(_chars, _charPos, dst, 0, remainingCharCount);
_chars = dst;
}
else
{
// copy any remaining data to the beginning of the buffer if needed and reset positions
if (remainingCharCount > 0)
BlockCopyChars(_chars, _charPos, _chars, 0, remainingCharCount);
}
_lineStartPos -= _charPos;
_charPos = 0;
_charsUsed = remainingCharCount;
}
}
int attemptCharReadCount = _chars.Length - _charsUsed - 1;
int charsRead = _reader.Read(_chars, _charsUsed, attemptCharReadCount);
_charsUsed += charsRead;
if (charsRead == 0)
_isEndOfFile = true;
_chars[_charsUsed] = '\0';
return charsRead;
}
private bool EnsureChars(int relativePosition, bool append)
{
if (_charPos + relativePosition >= _charsUsed)
return ReadChars(relativePosition, append);
return true;
}
private bool ReadChars(int relativePosition, bool append)
{
if (_isEndOfFile)
return false;
int charsRequired = _charPos + relativePosition - _charsUsed + 1;
int totalCharsRead = 0;
// it is possible that the TextReader doesn't return all data at once
// repeat read until the required text is returned or the reader is out of content
do
{
int charsRead = ReadData(append, charsRequired - totalCharsRead);
// no more content
if (charsRead == 0)
break;
totalCharsRead += charsRead;
} while (totalCharsRead < charsRequired);
if (totalCharsRead < charsRequired)
return false;
return true;
}
/// <summary>
/// Reads the next JSON token from the stream.
/// </summary>
/// <returns>
/// true if the next token was read successfully; false if there are no more tokens to read.
/// </returns>
[DebuggerStepThrough]
public override bool Read()
{
_readType = ReadType.Read;
if (!ReadInternal())
{
SetToken(JsonToken.None);
return false;
}
return true;
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>.
/// </summary>
/// <returns>
/// A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array.
/// </returns>
public override byte[] ReadAsBytes()
{
return ReadAsBytesInternal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns>
public override decimal? ReadAsDecimal()
{
return ReadAsDecimalInternal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns>
public override int? ReadAsInt32()
{
return ReadAsInt32Internal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="String"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public override string ReadAsString()
{
return ReadAsStringInternal();
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public override DateTime? ReadAsDateTime()
{
return ReadAsDateTimeInternal();
}
#if !NET20
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>.
/// </summary>
/// <returns>A <see cref="DateTimeOffset"/>. This method will return <c>null</c> at the end of an array.</returns>
public override DateTimeOffset? ReadAsDateTimeOffset()
{
return ReadAsDateTimeOffsetInternal();
}
#endif
internal override bool ReadInternal()
{
while (true)
{
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
return ParseValue();
case State.Complete:
break;
case State.Object:
case State.ObjectStart:
return ParseObject();
case State.PostValue:
// returns true if it hits
// end of object or array
if (ParsePostValue())
return true;
break;
case State.Finished:
if (EnsureChars(0, false))
{
EatWhitespace(false);
if (_isEndOfFile)
{
return false;
}
if (_chars[_charPos] == '/')
{
ParseComment();
return true;
}
else
{
throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
}
return false;
case State.Closed:
break;
case State.Error:
break;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
}
private void ReadStringIntoBuffer(char quote)
{
int charPos = _charPos;
int initialPosition = _charPos;
int lastWritePosition = _charPos;
StringBuffer buffer = null;
while (true)
{
switch (_chars[charPos++])
{
case '\0':
if (_charsUsed == charPos - 1)
{
charPos--;
if (ReadData(true) == 0)
{
_charPos = charPos;
throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
}
}
break;
case '\\':
_charPos = charPos;
if (!EnsureChars(0, true))
{
_charPos = charPos;
throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
}
// start of escape sequence
int escapeStartPos = charPos - 1;
char currentChar = _chars[charPos];
char writeChar;
switch (currentChar)
{
case 'b':
charPos++;
writeChar = '\b';
break;
case 't':
charPos++;
writeChar = '\t';
break;
case 'n':
charPos++;
writeChar = '\n';
break;
case 'f':
charPos++;
writeChar = '\f';
break;
case 'r':
charPos++;
writeChar = '\r';
break;
case '\\':
charPos++;
writeChar = '\\';
break;
case '"':
case '\'':
case '/':
writeChar = currentChar;
charPos++;
break;
case 'u':
charPos++;
_charPos = charPos;
writeChar = ParseUnicode();
if (StringUtils.IsLowSurrogate(writeChar))
{
// low surrogate with no preceding high surrogate; this char is replaced
writeChar = UnicodeReplacementChar;
}
else if (StringUtils.IsHighSurrogate(writeChar))
{
bool anotherHighSurrogate;
// loop for handling situations where there are multiple consecutive high surrogates
do
{
anotherHighSurrogate = false;
// potential start of a surrogate pair
if (EnsureChars(2, true) && _chars[_charPos] == '\\' && _chars[_charPos + 1] == 'u')
{
char highSurrogate = writeChar;
_charPos += 2;
writeChar = ParseUnicode();
if (StringUtils.IsLowSurrogate(writeChar))
{
// a valid surrogate pair!
}
else if (StringUtils.IsHighSurrogate(writeChar))
{
// another high surrogate; replace current and start check over
highSurrogate = UnicodeReplacementChar;
anotherHighSurrogate = true;
}
else
{
// high surrogate not followed by low surrogate; original char is replaced
highSurrogate = UnicodeReplacementChar;
}
if (buffer == null)
buffer = GetBuffer();
WriteCharToBuffer(buffer, highSurrogate, lastWritePosition, escapeStartPos);
lastWritePosition = _charPos;
}
else
{
// there are not enough remaining chars for the low surrogate or is not follow by unicode sequence
// replace high surrogate and continue on as usual
writeChar = UnicodeReplacementChar;
}
} while (anotherHighSurrogate);
}
charPos = _charPos;
break;
default:
charPos++;
_charPos = charPos;
throw JsonReaderException.Create(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar));
}
if (buffer == null)
buffer = GetBuffer();
WriteCharToBuffer(buffer, writeChar, lastWritePosition, escapeStartPos);
lastWritePosition = charPos;
break;
case StringUtils.CarriageReturn:
_charPos = charPos - 1;
ProcessCarriageReturn(true);
charPos = _charPos;
break;
case StringUtils.LineFeed:
_charPos = charPos - 1;
ProcessLineFeed();
charPos = _charPos;
break;
case '"':
case '\'':
if (_chars[charPos - 1] == quote)
{
charPos--;
if (initialPosition == lastWritePosition)
{
_stringReference = new StringReference(_chars, initialPosition, charPos - initialPosition);
}
else
{
if (buffer == null)
buffer = GetBuffer();
if (charPos > lastWritePosition)
buffer.Append(_chars, lastWritePosition, charPos - lastWritePosition);
_stringReference = new StringReference(buffer.GetInternalBuffer(), 0, buffer.Position);
}
charPos++;
_charPos = charPos;
return;
}
break;
}
}
}
private void WriteCharToBuffer(StringBuffer buffer, char writeChar, int lastWritePosition, int writeToPosition)
{
if (writeToPosition > lastWritePosition)
{
buffer.Append(_chars, lastWritePosition, writeToPosition - lastWritePosition);
}
buffer.Append(writeChar);
}
private char ParseUnicode()
{
char writeChar;
if (EnsureChars(4, true))
{
string hexValues = new string(_chars, _charPos, 4);
char hexChar = Convert.ToChar(int.Parse(hexValues, NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo));
writeChar = hexChar;
_charPos += 4;
}
else
{
throw JsonReaderException.Create(this, "Unexpected end while parsing unicode character.");
}
return writeChar;
}
private void ReadNumberIntoBuffer()
{
int charPos = _charPos;
while (true)
{
switch (_chars[charPos++])
{
case '\0':
if (_charsUsed == charPos - 1)
{
charPos--;
_charPos = charPos;
if (ReadData(true) == 0)
return;
}
else
{
_charPos = charPos - 1;
return;
}
break;
case '-':
case '+':
case 'a':
case 'A':
case 'b':
case 'B':
case 'c':
case 'C':
case 'd':
case 'D':
case 'e':
case 'E':
case 'f':
case 'F':
case 'x':
case 'X':
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
break;
default:
_charPos = charPos - 1;
return;
}
}
}
private void ClearRecentString()
{
if (_buffer != null)
_buffer.Position = 0;
_stringReference = new StringReference();
}
private bool ParsePostValue()
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (ReadData(false) == 0)
{
_currentState = State.Finished;
return false;
}
}
else
{
_charPos++;
}
break;
case '}':
_charPos++;
SetToken(JsonToken.EndObject);
return true;
case ']':
_charPos++;
SetToken(JsonToken.EndArray);
return true;
case ')':
_charPos++;
SetToken(JsonToken.EndConstructor);
return true;
case '/':
ParseComment();
return true;
case ',':
_charPos++;
// finished parsing
SetStateBasedOnCurrent();
return false;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
case StringUtils.CarriageReturn:
ProcessCarriageReturn(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
}
else
{
throw JsonReaderException.Create(this, "After parsing a value an unexpected character was encountered: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
break;
}
}
}
private bool ParseObject()
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (ReadData(false) == 0)
return false;
}
else
{
_charPos++;
}
break;
case '}':
SetToken(JsonToken.EndObject);
_charPos++;
return true;
case '/':
ParseComment();
return true;
case StringUtils.CarriageReturn:
ProcessCarriageReturn(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
}
else
{
return ParseProperty();
}
break;
}
}
}
private bool ParseProperty()
{
char firstChar = _chars[_charPos];
char quoteChar;
if (firstChar == '"' || firstChar == '\'')
{
_charPos++;
quoteChar = firstChar;
ShiftBufferIfNeeded();
ReadStringIntoBuffer(quoteChar);
}
else if (ValidIdentifierChar(firstChar))
{
quoteChar = '\0';
ShiftBufferIfNeeded();
ParseUnquotedProperty();
}
else
{
throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
string propertyName = _stringReference.ToString();
EatWhitespace(false);
if (_chars[_charPos] != ':')
throw JsonReaderException.Create(this, "Invalid character after parsing property name. Expected ':' but got: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
_charPos++;
SetToken(JsonToken.PropertyName, propertyName);
_quoteChar = quoteChar;
ClearRecentString();
return true;
}
private bool ValidIdentifierChar(char value)
{
return (char.IsLetterOrDigit(value) || value == '_' || value == '$');
}
private void ParseUnquotedProperty()
{
int initialPosition = _charPos;
// parse unquoted property name until whitespace or colon
while (true)
{
switch (_chars[_charPos])
{
case '\0':
if (_charsUsed == _charPos)
{
if (ReadData(true) == 0)
throw JsonReaderException.Create(this, "Unexpected end while parsing unquoted property name.");
break;
}
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
return;
default:
char currentChar = _chars[_charPos];
if (ValidIdentifierChar(currentChar))
{
_charPos++;
break;
}
else if (char.IsWhiteSpace(currentChar) || currentChar == ':')
{
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
return;
}
throw JsonReaderException.Create(this, "Invalid JavaScript property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
}
}
private bool ParseValue()
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (ReadData(false) == 0)
return false;
}
else
{
_charPos++;
}
break;
case '"':
case '\'':
ParseString(currentChar);
return true;
case 't':
ParseTrue();
return true;
case 'f':
ParseFalse();
return true;
case 'n':
if (EnsureChars(1, true))
{
char next = _chars[_charPos + 1];
if (next == 'u')
ParseNull();
else if (next == 'e')
ParseConstructor();
else
throw JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
else
{
throw JsonReaderException.Create(this, "Unexpected end.");
}
return true;
case 'N':
ParseNumberNaN();
return true;
case 'I':
ParseNumberPositiveInfinity();
return true;
case '-':
if (EnsureChars(1, true) && _chars[_charPos + 1] == 'I')
ParseNumberNegativeInfinity();
else
ParseNumber();
return true;
case '/':
ParseComment();
return true;
case 'u':
ParseUndefined();
return true;
case '{':
_charPos++;
SetToken(JsonToken.StartObject);
return true;
case '[':
_charPos++;
SetToken(JsonToken.StartArray);
return true;
case ']':
_charPos++;
SetToken(JsonToken.EndArray);
return true;
case ',':
// don't increment position, the next call to read will handle comma
// this is done to handle multiple empty comma values
SetToken(JsonToken.Undefined);
return true;
case ')':
_charPos++;
SetToken(JsonToken.EndConstructor);
return true;
case StringUtils.CarriageReturn:
ProcessCarriageReturn(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
break;
}
else if (char.IsNumber(currentChar) || currentChar == '-' || currentChar == '.')
{
ParseNumber();
return true;
}
else
{
throw JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
}
}
}
private void ProcessLineFeed()
{
_charPos++;
OnNewLine(_charPos);
}
private void ProcessCarriageReturn(bool append)
{
_charPos++;
if (EnsureChars(1, append) && _chars[_charPos] == StringUtils.LineFeed)
_charPos++;
OnNewLine(_charPos);
}
private bool EatWhitespace(bool oneOrMore)
{
bool finished = false;
bool ateWhitespace = false;
while (!finished)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (ReadData(false) == 0)
finished = true;
}
else
{
_charPos++;
}
break;
case StringUtils.CarriageReturn:
ProcessCarriageReturn(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
default:
if (currentChar == ' ' || char.IsWhiteSpace(currentChar))
{
ateWhitespace = true;
_charPos++;
}
else
{
finished = true;
}
break;
}
}
return (!oneOrMore || ateWhitespace);
}
private void ParseConstructor()
{
if (MatchValueWithTrailingSeperator("new"))
{
EatWhitespace(false);
int initialPosition = _charPos;
int endPosition;
while (true)
{
char currentChar = _chars[_charPos];
if (currentChar == '\0')
{
if (_charsUsed == _charPos)
{
if (ReadData(true) == 0)
throw JsonReaderException.Create(this, "Unexpected end while parsing constructor.");
}
else
{
endPosition = _charPos;
_charPos++;
break;
}
}
else if (char.IsLetterOrDigit(currentChar))
{
_charPos++;
}
else if (currentChar == StringUtils.CarriageReturn)
{
endPosition = _charPos;
ProcessCarriageReturn(true);
break;
}
else if (currentChar == StringUtils.LineFeed)
{
endPosition = _charPos;
ProcessLineFeed();
break;
}
else if (char.IsWhiteSpace(currentChar))
{
endPosition = _charPos;
_charPos++;
break;
}
else if (currentChar == '(')
{
endPosition = _charPos;
break;
}
else
{
throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
}
_stringReference = new StringReference(_chars, initialPosition, endPosition - initialPosition);
string constructorName = _stringReference.ToString();
EatWhitespace(false);
if (_chars[_charPos] != '(')
throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
_charPos++;
ClearRecentString();
SetToken(JsonToken.StartConstructor, constructorName);
}
else
{
throw JsonReaderException.Create(this, "Unexpected content while parsing JSON.");
}
}
private void ParseNumber()
{
ShiftBufferIfNeeded();
char firstChar = _chars[_charPos];
int initialPosition = _charPos;
ReadNumberIntoBuffer();
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
object numberValue;
JsonToken numberType;
bool singleDigit = (char.IsDigit(firstChar) && _stringReference.Length == 1);
bool nonBase10 = (firstChar == '0' && _stringReference.Length > 1
&& _stringReference.Chars[_stringReference.StartIndex + 1] != '.'
&& _stringReference.Chars[_stringReference.StartIndex + 1] != 'e'
&& _stringReference.Chars[_stringReference.StartIndex + 1] != 'E');
if (_readType == ReadType.ReadAsInt32)
{
if (singleDigit)
{
// digit char values start at 48
numberValue = firstChar - 48;
}
else if (nonBase10)
{
string number = _stringReference.ToString();
// decimal.Parse doesn't support parsing hexadecimal values
int integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
? Convert.ToInt32(number, 16)
: Convert.ToInt32(number, 8);
numberValue = integer;
}
else
{
int value;
ParseResult parseResult = ConvertUtils.Int32TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value);
if (parseResult == ParseResult.Success)
numberValue = value;
else if (parseResult == ParseResult.Overflow)
throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int32.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
else
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid integer.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
}
numberType = JsonToken.Integer;
}
else if (_readType == ReadType.ReadAsDecimal)
{
if (singleDigit)
{
// digit char values start at 48
numberValue = (decimal)firstChar - 48;
}
else if (nonBase10)
{
string number = _stringReference.ToString();
// decimal.Parse doesn't support parsing hexadecimal values
long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
? Convert.ToInt64(number, 16)
: Convert.ToInt64(number, 8);
numberValue = Convert.ToDecimal(integer);
}
else
{
string number = _stringReference.ToString();
decimal value;
if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out value))
numberValue = value;
else
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
}
numberType = JsonToken.Float;
}
else
{
if (singleDigit)
{
// digit char values start at 48
numberValue = (long)firstChar - 48;
numberType = JsonToken.Integer;
}
else if (nonBase10)
{
string number = _stringReference.ToString();
numberValue = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
? Convert.ToInt64(number, 16)
: Convert.ToInt64(number, 8);
numberType = JsonToken.Integer;
}
else
{
long value;
ParseResult parseResult = ConvertUtils.Int64TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value);
if (parseResult == ParseResult.Success)
{
numberValue = value;
numberType = JsonToken.Integer;
}
else if (parseResult == ParseResult.Overflow)
{
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
string number = _stringReference.ToString();
numberValue = BigInteger.Parse(number, CultureInfo.InvariantCulture);
numberType = JsonToken.Integer;
#else
throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
#endif
}
else
{
string number = _stringReference.ToString();
if (_floatParseHandling == FloatParseHandling.Decimal)
{
decimal d;
if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out d))
numberValue = d;
else
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, number));
}
else
{
double d;
if (double.TryParse(number, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d))
numberValue = d;
else
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number));
}
numberType = JsonToken.Float;
}
}
}
ClearRecentString();
SetToken(numberType, numberValue);
}
private void ParseComment()
{
// should have already parsed / character before reaching this method
_charPos++;
if (!EnsureChars(1, false))
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
bool singlelineComment;
if (_chars[_charPos] == '*')
singlelineComment = false;
else if (_chars[_charPos] == '/')
singlelineComment = true;
else
throw JsonReaderException.Create(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
_charPos++;
int initialPosition = _charPos;
bool commentFinished = false;
while (!commentFinished)
{
switch (_chars[_charPos])
{
case '\0':
if (_charsUsed == _charPos)
{
if (ReadData(true) == 0)
{
if (!singlelineComment)
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
commentFinished = true;
}
}
else
{
_charPos++;
}
break;
case '*':
_charPos++;
if (!singlelineComment)
{
if (EnsureChars(0, true))
{
if (_chars[_charPos] == '/')
{
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition - 1);
_charPos++;
commentFinished = true;
}
}
}
break;
case StringUtils.CarriageReturn:
if (singlelineComment)
{
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
commentFinished = true;
}
ProcessCarriageReturn(true);
break;
case StringUtils.LineFeed:
if (singlelineComment)
{
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
commentFinished = true;
}
ProcessLineFeed();
break;
default:
_charPos++;
break;
}
}
SetToken(JsonToken.Comment, _stringReference.ToString());
ClearRecentString();
}
private bool MatchValue(string value)
{
if (!EnsureChars(value.Length - 1, true))
return false;
for (int i = 0; i < value.Length; i++)
{
if (_chars[_charPos + i] != value[i])
{
return false;
}
}
_charPos += value.Length;
return true;
}
private bool MatchValueWithTrailingSeperator(string value)
{
// will match value and then move to the next character, checking that it is a seperator character
bool match = MatchValue(value);
if (!match)
return false;
if (!EnsureChars(0, false))
return true;
return IsSeperator(_chars[_charPos]) || _chars[_charPos] == '\0';
}
private bool IsSeperator(char c)
{
switch (c)
{
case '}':
case ']':
case ',':
return true;
case '/':
// check next character to see if start of a comment
if (!EnsureChars(1, false))
return false;
var nextChart = _chars[_charPos + 1];
return (nextChart == '*' || nextChart == '/');
case ')':
if (CurrentState == State.Constructor || CurrentState == State.ConstructorStart)
return true;
break;
case ' ':
case StringUtils.Tab:
case StringUtils.LineFeed:
case StringUtils.CarriageReturn:
return true;
default:
if (char.IsWhiteSpace(c))
return true;
break;
}
return false;
}
private void ParseTrue()
{
// check characters equal 'true'
// and that it is followed by either a seperator character
// or the text ends
if (MatchValueWithTrailingSeperator(JsonConvert.True))
{
SetToken(JsonToken.Boolean, true);
}
else
{
throw JsonReaderException.Create(this, "Error parsing boolean value.");
}
}
private void ParseNull()
{
if (MatchValueWithTrailingSeperator(JsonConvert.Null))
{
SetToken(JsonToken.Null);
}
else
{
throw JsonReaderException.Create(this, "Error parsing null value.");
}
}
private void ParseUndefined()
{
if (MatchValueWithTrailingSeperator(JsonConvert.Undefined))
{
SetToken(JsonToken.Undefined);
}
else
{
throw JsonReaderException.Create(this, "Error parsing undefined value.");
}
}
private void ParseFalse()
{
if (MatchValueWithTrailingSeperator(JsonConvert.False))
{
SetToken(JsonToken.Boolean, false);
}
else
{
throw JsonReaderException.Create(this, "Error parsing boolean value.");
}
}
private void ParseNumberNegativeInfinity()
{
if (MatchValueWithTrailingSeperator(JsonConvert.NegativeInfinity))
{
if (_floatParseHandling == FloatParseHandling.Decimal)
throw new JsonReaderException("Cannot read -Infinity as a decimal.");
SetToken(JsonToken.Float, double.NegativeInfinity);
}
else
{
throw JsonReaderException.Create(this, "Error parsing negative infinity value.");
}
}
private void ParseNumberPositiveInfinity()
{
if (MatchValueWithTrailingSeperator(JsonConvert.PositiveInfinity))
{
if (_floatParseHandling == FloatParseHandling.Decimal)
throw new JsonReaderException("Cannot read Infinity as a decimal.");
SetToken(JsonToken.Float, double.PositiveInfinity);
}
else
{
throw JsonReaderException.Create(this, "Error parsing positive infinity value.");
}
}
private void ParseNumberNaN()
{
if (MatchValueWithTrailingSeperator(JsonConvert.NaN))
{
if (_floatParseHandling == FloatParseHandling.Decimal)
throw new JsonReaderException("Cannot read NaN as a decimal.");
SetToken(JsonToken.Float, double.NaN);
}
else
{
throw JsonReaderException.Create(this, "Error parsing NaN value.");
}
}
/// <summary>
/// Changes the state to closed.
/// </summary>
public override void Close()
{
base.Close();
if (CloseInput && _reader != null)
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
_reader.Close();
#else
_reader.Dispose();
#endif
if (_buffer != null)
_buffer.Clear();
}
/// <summary>
/// Gets a value indicating whether the class can return line information.
/// </summary>
/// <returns>
/// <c>true</c> if LineNumber and LinePosition can be provided; otherwise, <c>false</c>.
/// </returns>
public bool HasLineInfo()
{
return true;
}
/// <summary>
/// Gets the current line number.
/// </summary>
/// <value>
/// The current line number or 0 if no line information is available (for example, HasLineInfo returns false).
/// </value>
public int LineNumber
{
get
{
if (CurrentState == State.Start && LinePosition == 0)
return 0;
return _lineNumber;
}
}
/// <summary>
/// Gets the current line position.
/// </summary>
/// <value>
/// The current line position or 0 if no line information is available (for example, HasLineInfo returns false).
/// </value>
public int LinePosition
{
get { return _charPos - _lineStartPos; }
}
}
}
| |
// 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.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class PreIncrementAssignTests : IncDecAssignTests
{
[Theory]
[PerCompilationType(nameof(Int16sAndIncrements))]
[PerCompilationType(nameof(NullableInt16sAndIncrements))]
[PerCompilationType(nameof(UInt16sAndIncrements))]
[PerCompilationType(nameof(NullableUInt16sAndIncrements))]
[PerCompilationType(nameof(Int32sAndIncrements))]
[PerCompilationType(nameof(NullableInt32sAndIncrements))]
[PerCompilationType(nameof(UInt32sAndIncrements))]
[PerCompilationType(nameof(NullableUInt32sAndIncrements))]
[PerCompilationType(nameof(Int64sAndIncrements))]
[PerCompilationType(nameof(NullableInt64sAndIncrements))]
[PerCompilationType(nameof(UInt64sAndIncrements))]
[PerCompilationType(nameof(NullableUInt64sAndIncrements))]
[PerCompilationType(nameof(DecimalsAndIncrements))]
[PerCompilationType(nameof(NullableDecimalsAndIncrements))]
[PerCompilationType(nameof(SinglesAndIncrements))]
[PerCompilationType(nameof(NullableSinglesAndIncrements))]
[PerCompilationType(nameof(DoublesAndIncrements))]
[PerCompilationType(nameof(NullableDoublesAndIncrements))]
public void ReturnsCorrectValues(Type type, object value, object result, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PreIncrementAssign(variable)
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(Int16sAndIncrements))]
[PerCompilationType(nameof(NullableInt16sAndIncrements))]
[PerCompilationType(nameof(UInt16sAndIncrements))]
[PerCompilationType(nameof(NullableUInt16sAndIncrements))]
[PerCompilationType(nameof(Int32sAndIncrements))]
[PerCompilationType(nameof(NullableInt32sAndIncrements))]
[PerCompilationType(nameof(UInt32sAndIncrements))]
[PerCompilationType(nameof(NullableUInt32sAndIncrements))]
[PerCompilationType(nameof(Int64sAndIncrements))]
[PerCompilationType(nameof(NullableInt64sAndIncrements))]
[PerCompilationType(nameof(UInt64sAndIncrements))]
[PerCompilationType(nameof(NullableUInt64sAndIncrements))]
[PerCompilationType(nameof(DecimalsAndIncrements))]
[PerCompilationType(nameof(NullableDecimalsAndIncrements))]
[PerCompilationType(nameof(SinglesAndIncrements))]
[PerCompilationType(nameof(NullableSinglesAndIncrements))]
[PerCompilationType(nameof(DoublesAndIncrements))]
[PerCompilationType(nameof(NullableDoublesAndIncrements))]
public void AssignsCorrectValues(Type type, object value, object result, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(type);
LabelTarget target = Expression.Label(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PreIncrementAssign(variable),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(type))
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void SingleNanToNan(bool useInterpreter)
{
TestPropertyClass<float> instance = new TestPropertyClass<float>();
instance.TestInstance = float.NaN;
Assert.True(float.IsNaN(
Expression.Lambda<Func<float>>(
Expression.PreIncrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<float>),
"TestInstance"
)
)
).Compile(useInterpreter)()
));
Assert.True(float.IsNaN(instance.TestInstance));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void DoubleNanToNan(bool useInterpreter)
{
TestPropertyClass<double> instance = new TestPropertyClass<double>();
instance.TestInstance = double.NaN;
Assert.True(double.IsNaN(
Expression.Lambda<Func<double>>(
Expression.PreIncrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<double>),
"TestInstance"
)
)
).Compile(useInterpreter)()
));
Assert.True(double.IsNaN(instance.TestInstance));
}
[Theory]
[PerCompilationType(nameof(IncrementOverflowingValues))]
public void OverflowingValuesThrow(object value, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(value.GetType());
Action overflow = Expression.Lambda<Action>(
Expression.Block(
typeof(void),
new[] { variable },
Expression.Assign(variable, Expression.Constant(value)),
Expression.PreIncrementAssign(variable)
)
).Compile(useInterpreter);
Assert.Throws<OverflowException>(overflow);
}
[Theory]
[MemberData(nameof(UnincrementableAndUndecrementableTypes))]
public void InvalidOperandType(Type type)
{
ParameterExpression variable = Expression.Variable(type);
Assert.Throws<InvalidOperationException>(() => Expression.PreIncrementAssign(variable));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void MethodCorrectResult(bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PreIncrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod"))
);
Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void MethodCorrectAssign(bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(typeof(string));
LabelTarget target = Expression.Label(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PreIncrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(typeof(string)))
);
Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)());
}
[Fact]
public void IncorrectMethodType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod");
Assert.Throws<InvalidOperationException>(() => Expression.PreIncrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodParameterCount()
{
Expression variable = Expression.Variable(typeof(string));
MethodInfo method = typeof(object).GetTypeInfo().GetDeclaredMethod("ReferenceEquals");
Assert.Throws<ArgumentException>(null, () => Expression.PreIncrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodReturnType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("GetString");
Assert.Throws<ArgumentException>(null, () => Expression.PreIncrementAssign(variable, method));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void StaticMemberAccessCorrect(bool useInterpreter)
{
TestPropertyClass<uint>.TestStatic = 2U;
Assert.Equal(
3U,
Expression.Lambda<Func<uint>>(
Expression.PreIncrementAssign(
Expression.Property(null, typeof(TestPropertyClass<uint>), "TestStatic")
)
).Compile(useInterpreter)()
);
Assert.Equal(3U, TestPropertyClass<uint>.TestStatic);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void InstanceMemberAccessCorrect(bool useInterpreter)
{
TestPropertyClass<int> instance = new TestPropertyClass<int>();
instance.TestInstance = 2;
Assert.Equal(
3,
Expression.Lambda<Func<int>>(
Expression.PreIncrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<int>),
"TestInstance"
)
)
).Compile(useInterpreter)()
);
Assert.Equal(3, instance.TestInstance);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void ArrayAccessCorrect(bool useInterpreter)
{
int[] array = new int[1];
array[0] = 2;
Assert.Equal(
3,
Expression.Lambda<Func<int>>(
Expression.PreIncrementAssign(
Expression.ArrayAccess(Expression.Constant(array), Expression.Constant(0))
)
).Compile(useInterpreter)()
);
Assert.Equal(3, array[0]);
}
[Fact]
public void CanReduce()
{
ParameterExpression variable = Expression.Variable(typeof(int));
UnaryExpression op = Expression.PreIncrementAssign(variable);
Assert.True(op.CanReduce);
Assert.NotSame(op, op.ReduceAndCheck());
}
[Fact]
public void NullOperand()
{
Assert.Throws<ArgumentNullException>("expression", () => Expression.PreIncrementAssign(null));
}
[Fact]
public void UnwritableOperand()
{
Assert.Throws<ArgumentException>("expression", () => Expression.PreIncrementAssign(Expression.Constant(1)));
}
[Fact]
public void UnreadableOperand()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("expression", () => Expression.PreIncrementAssign(value));
}
[Fact]
public void UpdateSameOperandSameNode()
{
UnaryExpression op = Expression.PreIncrementAssign(Expression.Variable(typeof(int)));
Assert.Same(op, op.Update(op.Operand));
Assert.Same(op, NoOpVisitor.Instance.Visit(op));
}
[Fact]
public void UpdateDiffOperandDiffNode()
{
UnaryExpression op = Expression.PreIncrementAssign(Expression.Variable(typeof(int)));
Assert.NotSame(op, op.Update(Expression.Variable(typeof(int))));
}
}
}
| |
// 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.Linq;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Security.Cryptography;
namespace Internal.Cryptography
{
internal static partial class OidLookup
{
private static readonly ConcurrentDictionary<string, string> s_lateBoundOidToFriendlyName =
new ConcurrentDictionary<string, string>();
private static readonly ConcurrentDictionary<string, string> s_lateBoundFriendlyNameToOid =
new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
//
// Attempts to map a friendly name to an OID. Returns null if not a known name.
//
public static string ToFriendlyName(string oid, OidGroup oidGroup, bool fallBackToAllGroups)
{
if (oid == null)
throw new ArgumentNullException("oid");
string mappedName;
bool shouldUseCache = ShouldUseCache(oidGroup);
// On Unix shouldUseCache is always true, so no matter what OidGroup is passed in the Windows
// friendly name will be returned.
//
// On Windows shouldUseCache is only true for OidGroup.All, because otherwise the OS may filter
// out the answer based on the group criteria.
if (shouldUseCache)
{
if (s_oidToFriendlyName.TryGetValue(oid, out mappedName) ||
s_compatOids.TryGetValue(oid, out mappedName) ||
s_lateBoundOidToFriendlyName.TryGetValue(oid, out mappedName))
{
return mappedName;
}
}
mappedName = NativeOidToFriendlyName(oid, oidGroup, fallBackToAllGroups);
if (shouldUseCache && mappedName != null)
{
s_lateBoundOidToFriendlyName.TryAdd(oid, mappedName);
// Don't add the reverse here. Just because oid => name doesn't mean name => oid.
// And don't bother doing the reverse lookup proactively, just wait until they ask for it.
}
return mappedName;
}
//
// Attempts to retrieve the friendly name for an OID. Returns null if not a known or valid OID.
//
public static string ToOid(string friendlyName, OidGroup oidGroup, bool fallBackToAllGroups)
{
if (friendlyName == null)
throw new ArgumentNullException("friendlyName");
string mappedOid;
bool shouldUseCache = ShouldUseCache(oidGroup);
if (shouldUseCache)
{
if (s_friendlyNameToOid.TryGetValue(friendlyName, out mappedOid) ||
s_lateBoundFriendlyNameToOid.TryGetValue(friendlyName, out mappedOid))
{
return mappedOid;
}
}
mappedOid = NativeFriendlyNameToOid(friendlyName, oidGroup, fallBackToAllGroups);
if (shouldUseCache && mappedOid != null)
{
s_lateBoundFriendlyNameToOid.TryAdd(friendlyName, mappedOid);
// Don't add the reverse here. Friendly Name => OID is a case insensitive search,
// so the casing provided as input here may not be the 'correct' one. Just let
// ToFriendlyName capture the response and cache it itself.
}
return mappedOid;
}
// This table was originally built by extracting every szOID #define out of wincrypt.h,
// and running them through new Oid(string) on Windows 10. Then, take the list of everything
// which produced a FriendlyName value, and run it through two other languages. If all 3 agree
// on the mapping, consider the value to be non-localized.
//
// This original list was produced on English (Win10), cross-checked with Spanish (Win8.1) and
// Japanese (Win10).
//
// Sometimes wincrypt.h has more than one OID which results in the same name. The OIDs whose value
// doesn't roundtrip (new Oid(new Oid(value).FriendlyName).Value) are contained in s_compatOids.
//
// X-Plat: The names (and casing) in this table come from Windows. Part of the intent of this table
// is to prevent issues wherein an identifier is different between CoreFX\Windows and CoreFX\Unix;
// since any existing code would be using the Windows identifier, it is the de facto standard.
private static readonly Dictionary<string, string> s_friendlyNameToOid =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "3des", "1.2.840.113549.3.7" },
{ "aes128", "2.16.840.1.101.3.4.1.2" },
{ "aes128wrap", "2.16.840.1.101.3.4.1.5" },
{ "aes192", "2.16.840.1.101.3.4.1.22" },
{ "aes192wrap", "2.16.840.1.101.3.4.1.25" },
{ "aes256", "2.16.840.1.101.3.4.1.42" },
{ "aes256wrap", "2.16.840.1.101.3.4.1.45" },
{ "brainpoolP160r1", "1.3.36.3.3.2.8.1.1.1" },
{ "brainpoolP160t1", "1.3.36.3.3.2.8.1.1.2" },
{ "brainpoolP192r1", "1.3.36.3.3.2.8.1.1.3" },
{ "brainpoolP192t1", "1.3.36.3.3.2.8.1.1.4" },
{ "brainpoolP224r1", "1.3.36.3.3.2.8.1.1.5" },
{ "brainpoolP224t1", "1.3.36.3.3.2.8.1.1.6" },
{ "brainpoolP256r1", "1.3.36.3.3.2.8.1.1.7" },
{ "brainpoolP256t1", "1.3.36.3.3.2.8.1.1.8" },
{ "brainpoolP320r1", "1.3.36.3.3.2.8.1.1.9" },
{ "brainpoolP320t1", "1.3.36.3.3.2.8.1.1.10" },
{ "brainpoolP384r1", "1.3.36.3.3.2.8.1.1.11" },
{ "brainpoolP384t1", "1.3.36.3.3.2.8.1.1.12" },
{ "brainpoolP512r1", "1.3.36.3.3.2.8.1.1.13" },
{ "brainpoolP512t1", "1.3.36.3.3.2.8.1.1.14" },
{ "C", "2.5.4.6" },
{ "CMS3DESwrap", "1.2.840.113549.1.9.16.3.6" },
{ "CMSRC2wrap", "1.2.840.113549.1.9.16.3.7" },
{ "CN", "2.5.4.3" },
{ "CPS", "1.3.6.1.5.5.7.2.1" },
{ "DC", "0.9.2342.19200300.100.1.25" },
{ "des", "1.3.14.3.2.7" },
{ "Description", "2.5.4.13" },
{ "DH", "1.2.840.10046.2.1" },
{ "dnQualifier", "2.5.4.46" },
{ "DSA", "1.2.840.10040.4.1" },
{ "dsaSHA1", "1.3.14.3.2.27" },
{ "E", "1.2.840.113549.1.9.1" },
{ "ec192wapi", "1.2.156.11235.1.1.2.1" },
{ "ECC", "1.2.840.10045.2.1" },
{ "ECDH_STD_SHA1_KDF", "1.3.133.16.840.63.0.2" },
{ "ECDH_STD_SHA256_KDF", "1.3.132.1.11.1" },
{ "ECDH_STD_SHA384_KDF", "1.3.132.1.11.2" },
{ "ECDSA_P256", "1.2.840.10045.3.1.7" },
{ "ECDSA_P384", "1.3.132.0.34" },
{ "ECDSA_P521", "1.3.132.0.35" },
{ "ESDH", "1.2.840.113549.1.9.16.3.5" },
{ "G", "2.5.4.42" },
{ "I", "2.5.4.43" },
{ "L", "2.5.4.7" },
{ "md2", "1.2.840.113549.2.2" },
{ "md2RSA", "1.2.840.113549.1.1.2" },
{ "md4", "1.2.840.113549.2.4" },
{ "md4RSA", "1.2.840.113549.1.1.3" },
{ "md5", "1.2.840.113549.2.5" },
{ "md5RSA", "1.2.840.113549.1.1.4" },
{ "mgf1", "1.2.840.113549.1.1.8" },
{ "mosaicKMandUpdSig", "2.16.840.1.101.2.1.1.20" },
{ "mosaicUpdatedSig", "2.16.840.1.101.2.1.1.19" },
{ "nistP192", "1.2.840.10045.3.1.1" },
{ "nistP224", "1.3.132.0.33" },
{ "NO_SIGN", "1.3.6.1.5.5.7.6.2" },
{ "O", "2.5.4.10" },
{ "OU", "2.5.4.11" },
{ "Phone", "2.5.4.20" },
{ "POBox", "2.5.4.18" },
{ "PostalCode", "2.5.4.17" },
{ "rc2", "1.2.840.113549.3.2" },
{ "rc4", "1.2.840.113549.3.4" },
{ "RSA", "1.2.840.113549.1.1.1" },
{ "RSAES_OAEP", "1.2.840.113549.1.1.7" },
{ "RSASSA-PSS", "1.2.840.113549.1.1.10" },
{ "S", "2.5.4.8" },
{ "secP160k1", "1.3.132.0.9" },
{ "secP160r1", "1.3.132.0.8" },
{ "secP160r2", "1.3.132.0.30" },
{ "secP192k1", "1.3.132.0.31" },
{ "secP224k1", "1.3.132.0.32" },
{ "secP256k1", "1.3.132.0.10" },
{ "SERIALNUMBER", "2.5.4.5" },
{ "sha1", "1.3.14.3.2.26" },
{ "sha1DSA", "1.2.840.10040.4.3" },
{ "sha1ECDSA", "1.2.840.10045.4.1" },
{ "sha1RSA", "1.2.840.113549.1.1.5" },
{ "sha256", "2.16.840.1.101.3.4.2.1" },
{ "sha256ECDSA", "1.2.840.10045.4.3.2" },
{ "sha256RSA", "1.2.840.113549.1.1.11" },
{ "sha384", "2.16.840.1.101.3.4.2.2" },
{ "sha384ECDSA", "1.2.840.10045.4.3.3" },
{ "sha384RSA", "1.2.840.113549.1.1.12" },
{ "sha512", "2.16.840.1.101.3.4.2.3" },
{ "sha512ECDSA", "1.2.840.10045.4.3.4" },
{ "sha512RSA", "1.2.840.113549.1.1.13" },
{ "SN", "2.5.4.4" },
{ "specifiedECDSA", "1.2.840.10045.4.3" },
{ "STREET", "2.5.4.9" },
{ "T", "2.5.4.12" },
{ "wtls9", "2.23.43.1.4.9" },
{ "X21Address", "2.5.4.24" },
{ "x962P192v2", "1.2.840.10045.3.1.2" },
{ "x962P192v3", "1.2.840.10045.3.1.3" },
{ "x962P239v1", "1.2.840.10045.3.1.4" },
{ "x962P239v2", "1.2.840.10045.3.1.5" },
{ "x962P239v3", "1.2.840.10045.3.1.6" },
};
private static readonly Dictionary<string, string> s_oidToFriendlyName =
s_friendlyNameToOid.ToDictionary(kvp => kvp.Value, kvp => kvp.Key);
private static readonly Dictionary<string, string> s_compatOids =
new Dictionary<string, string>
{
{ "1.2.840.113549.1.3.1", "DH" },
{ "1.3.14.3.2.12", "DSA" },
{ "1.3.14.3.2.13", "sha1DSA" },
{ "1.3.14.3.2.15", "shaRSA" },
{ "1.3.14.3.2.18", "sha" },
{ "1.3.14.3.2.2", "md4RSA" },
{ "1.3.14.3.2.22", "RSA_KEYX" },
{ "1.3.14.3.2.29", "sha1RSA" },
{ "1.3.14.3.2.3", "md5RSA" },
{ "1.3.14.3.2.4", "md4RSA" },
{ "1.3.14.7.2.3.1", "md2RSA" },
};
}
}
| |
using PlayFab.Json;
using PlayFab.Public;
using PlayFab.SharedModels;
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace PlayFab.Internal
{
/// <summary>
/// This is a wrapper for Http So we can better separate the functionaity of Http Requests delegated to WWW or HttpWebRequest
/// </summary>
public class PlayFabHttp : SingletonMonoBehaviour<PlayFabHttp>
{
private static IPlayFabHttp _internalHttp; //This is the default;
private static List<CallRequestContainer> _apiCallQueue = new List<CallRequestContainer>(); // Starts initialized, and is nulled when it's flushed
public delegate void ApiProcessingEvent<in TEventArgs>(TEventArgs e);
public delegate void ApiProcessErrorEvent(PlayFabRequestCommon request, PlayFabError error);
public static event ApiProcessingEvent<ApiProcessingEventArgs> ApiProcessingEventHandler;
public static event ApiProcessErrorEvent ApiProcessingErrorEventHandler;
#if ENABLE_PLAYFABPLAYSTREAM_API && ENABLE_PLAYFABSERVER_API
private static IPlayFabSignalR _internalSignalR;
#endif
private static IPlayFabLogger _logger;
#if PLAYFAB_REQUEST_TIMING
public struct RequestTiming
{
public DateTime StartTimeUtc;
public string ApiEndpoint;
public int WorkerRequestMs;
public int MainThreadRequestMs;
}
public delegate void ApiRequestTimingEvent(RequestTiming time);
public static event ApiRequestTimingEvent ApiRequestTimingEventHandler;
#endif
/// <summary>
/// Return the number of api calls that are waiting for results from the server
/// </summary>
/// <returns></returns>
public static int GetPendingMessages()
{
return _internalHttp == null ? 0 : _internalHttp.GetPendingMessages();
}
/// <summary>
/// Optional redirect to allow mocking of _internalHttp calls, or use a custom _internalHttp utility
/// </summary>
public static void SetHttp<THttpObject>(THttpObject httpObj) where THttpObject : IPlayFabHttp
{
_internalHttp = httpObj;
}
/// <summary>
/// Optional redirect to allow mocking of AuthKey
/// </summary>
/// <param name="authKey"></param>
public static void SetAuthKey(string authKey)
{
_internalHttp.AuthKey = authKey;
}
/// <summary>
/// This initializes the GameObject and ensures it is in the scene.
/// </summary>
public static void InitializeHttp()
{
if (_internalHttp != null)
return;
Application.runInBackground = true; // Http requests respond even if you lose focus
#if !UNITY_WSA && !UNITY_WP8
if (PlayFabSettings.RequestType == WebRequestType.HttpWebRequest)
_internalHttp = new PlayFabWebRequest();
#endif
if (_internalHttp == null)
_internalHttp = new PlayFabWww();
_internalHttp.InitializeHttp();
CreateInstance(); // Invoke the SingletonMonoBehaviour
}
/// <summary>
/// This initializes the GameObject and ensures it is in the scene.
/// </summary>
public static void InitializeLogger(IPlayFabLogger setLogger = null)
{
if (_logger != null)
throw new Exception("Once initialized, the logger cannot be reset.");
if (setLogger == null)
setLogger = new PlayFabLogger();
_logger = setLogger;
}
#if ENABLE_PLAYFABPLAYSTREAM_API && ENABLE_PLAYFABSERVER_API
public static void InitializeSignalR(string baseUrl, string hubName, Action onConnected, Action<string>onReceived, Action onReconnected, Action onDisconnected, Action<Exception> onError)
{
CreateInstance();
if (_internalSignalR != null) return;
_internalSignalR = new PlayFabSignalR (onConnected);
_internalSignalR.OnReceived += onReceived;
_internalSignalR.OnReconnected += onReconnected;
_internalSignalR.OnDisconnected += onDisconnected;
_internalSignalR.OnError += onError;
_internalSignalR.Start(baseUrl, hubName);
}
public static void SubscribeSignalR(string onInvoked, Action<object[]> callbacks)
{
_internalSignalR.Subscribe(onInvoked, callbacks);
}
public static void InvokeSignalR(string methodName, Action callback, params object[] args)
{
_internalSignalR.Invoke(methodName, callback, args);
}
public static void StopSignalR()
{
_internalSignalR.Stop();
}
#endif
/// <summary>
/// Internal method for Make API Calls
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="apiEndpoint"></param>
/// <param name="request"></param>
/// <param name="authType"></param>
/// <param name="resultCallback"></param>
/// <param name="errorCallback"></param>
/// <param name="customData"></param>
protected internal static void MakeApiCall<TResult>(string apiEndpoint,
PlayFabRequestCommon request, AuthType authType, Action<TResult> resultCallback,
Action<PlayFabError> errorCallback, object customData = null, bool allowQueueing = false)
where TResult : PlayFabResultCommon
{
InitializeHttp();
SendEvent(apiEndpoint, request, null, ApiProcessingEventType.Pre);
var reqContainer = new CallRequestContainer();
#if PLAYFAB_REQUEST_TIMING
reqContainer.Timing.StartTimeUtc = DateTime.UtcNow;
reqContainer.Timing.ApiEndpoint = apiEndpoint;
#endif
reqContainer.ApiEndpoint = apiEndpoint;
reqContainer.FullUrl = PlayFabSettings.GetFullUrl(apiEndpoint);
reqContainer.CustomData = customData;
reqContainer.Payload = Encoding.UTF8.GetBytes(JsonWrapper.SerializeObject(request, PlayFabUtil.ApiSerializerStrategy));
reqContainer.AuthKey = authType;
reqContainer.ApiRequest = request;
reqContainer.ErrorCallback = errorCallback;
// These closures preserve the TResult generic information in a way that's safe for all the devices
reqContainer.DeserializeResultJson = () =>
{
reqContainer.ApiResult = JsonWrapper.DeserializeObject<TResult>(reqContainer.JsonResponse, PlayFabUtil.ApiSerializerStrategy);
};
reqContainer.InvokeSuccessCallback = () =>
{
if (resultCallback != null)
resultCallback((TResult)reqContainer.ApiResult);
};
if (allowQueueing && _apiCallQueue != null && !_internalHttp.SessionStarted)
{
for (var i = _apiCallQueue.Count - 1; i >= 0; i--)
if (_apiCallQueue[i].ApiEndpoint == apiEndpoint)
_apiCallQueue.RemoveAt(i);
_apiCallQueue.Add(reqContainer);
}
else
{
_internalHttp.MakeApiCall(reqContainer);
}
}
/// <summary>
/// MonoBehaviour OnEnable Method
/// </summary>
public void OnEnable()
{
if (_logger != null)
{
_logger.OnEnable();
}
}
/// <summary>
/// MonoBehaviour OnDisable
/// </summary>
public void OnDisable()
{
if (_logger != null)
{
_logger.OnDisable();
}
}
/// <summary>
/// MonoBehaviour OnDestroy
/// </summary>
public void OnDestroy()
{
if (_internalHttp != null)
{
_internalHttp.OnDestroy();
}
#if ENABLE_PLAYFABPLAYSTREAM_API && ENABLE_PLAYFABSERVER_API
if (_internalSignalR != null)
{
_internalSignalR.Stop();
}
#endif
if (_logger != null)
{
_logger.OnDestroy();
}
}
/// <summary>
/// MonoBehaviour Update
/// </summary>
public void Update()
{
if (_internalHttp != null)
{
if (!_internalHttp.SessionStarted && _apiCallQueue != null)
{
foreach (var eachRequest in _apiCallQueue)
_internalHttp.MakeApiCall(eachRequest); // Flush the queue
_apiCallQueue = null; // null this after it's flushed
}
_internalHttp.Update();
}
#if ENABLE_PLAYFABPLAYSTREAM_API && ENABLE_PLAYFABSERVER_API
if (_internalSignalR != null)
{
_internalSignalR.Update();
}
#endif
}
#region Helpers
public static bool IsClientLoggedIn()
{
return _internalHttp != null && !string.IsNullOrEmpty(_internalHttp.AuthKey);
}
protected internal static PlayFabError GeneratePlayFabError(string json, object customData)
{
JsonObject errorDict = null;
Dictionary<string, List<string>> errorDetails = null;
try
{
// Deserialize the error
errorDict = JsonWrapper.DeserializeObject<JsonObject>(json, PlayFabUtil.ApiSerializerStrategy);
}
catch (Exception) { /* Unusual, but shouldn't actually matter */ }
try
{
if (errorDict != null && errorDict.ContainsKey("errorDetails"))
errorDetails = JsonWrapper.DeserializeObject<Dictionary<string, List<string>>>(errorDict["errorDetails"].ToString());
}
catch (Exception) { /* Unusual, but shouldn't actually matter */ }
return new PlayFabError
{
HttpCode = errorDict != null && errorDict.ContainsKey("code") ? Convert.ToInt32(errorDict["code"]) : 400,
HttpStatus = errorDict != null && errorDict.ContainsKey("status") ? (string)errorDict["status"] : "BadRequest",
Error = errorDict != null && errorDict.ContainsKey("errorCode") ? (PlayFabErrorCode)Convert.ToInt32(errorDict["errorCode"]) : PlayFabErrorCode.ServiceUnavailable,
ErrorMessage = errorDict != null && errorDict.ContainsKey("errorMessage") ? (string)errorDict["errorMessage"] : json,
ErrorDetails = errorDetails,
CustomData = customData
};
}
protected internal static void SendErrorEvent(PlayFabRequestCommon request, PlayFabError error)
{
if (ApiProcessingErrorEventHandler == null)
return;
try
{
ApiProcessingErrorEventHandler(request, error);
}
catch (Exception e)
{
Debug.LogException(e);
}
}
protected internal static void SendEvent(string apiEndpoint, PlayFabRequestCommon request, PlayFabResultCommon result, ApiProcessingEventType eventType)
{
if (ApiProcessingEventHandler == null)
return;
try
{
ApiProcessingEventHandler(new ApiProcessingEventArgs
{
ApiEndpoint = apiEndpoint,
EventType = eventType,
Request = request,
Result = result
});
}
catch (Exception e)
{
Debug.LogException(e);
}
}
protected internal static void ClearAllEvents()
{
ApiProcessingEventHandler = null;
ApiProcessingErrorEventHandler = null;
}
#if PLAYFAB_REQUEST_TIMING
protected internal static void SendRequestTiming(RequestTiming rt) {
if (ApiRequestTimingEventHandler != null) {
ApiRequestTimingEventHandler(rt);
}
}
#endif
#endregion
}
#region Event Classes
public enum ApiProcessingEventType
{
Pre,
Post
}
public class ApiProcessingEventArgs
{
public string ApiEndpoint;
public ApiProcessingEventType EventType;
public PlayFabRequestCommon Request;
public PlayFabResultCommon Result;
public TRequest GetRequest<TRequest>() where TRequest : PlayFabRequestCommon
{
return Request as TRequest;
}
}
#endregion
}
| |
using GameTimer;
using InputHelper;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using System;
using System.Threading.Tasks;
namespace MenuBuddy
{
/// <summary>
/// This is a button that can be clicked on
/// </summary>
public abstract class BaseButton : Widget, IButton, IDisposable
{
#region Fields
/// <summary>
/// whether or not to draw this item when inactive
/// </summary>
private bool _drawWhenInactive;
private Vector2 _size;
public event EventHandler<ClickEventArgs> OnClick;
private CountdownTimer _clickTimer;
public float ClickTimeDelta { get; set; } = 0.2f;
private ILayout _layout;
#endregion //Fields
#region Properties
public bool Clickable { get; set; }
public Vector2 Size
{
protected get
{
return _size;
}
set
{
if (_size != value)
{
_size = value;
CalculateRect();
}
}
}
public override float Scale
{
get
{
return base.Scale;
}
set
{
base.Scale = value;
Layout.Scale = value;
}
}
/// <summary>
/// The layout to add to this button
/// </summary>
public ILayout Layout
{
get
{
return _layout;
}
protected set
{
_layout = value;
if (null != _layout)
{
_layout.TransitionObject = TransitionObject;
}
}
}
public override bool IsHighlighted
{
get
{
return base.IsHighlighted;
}
set
{
base.IsHighlighted = value;
Layout.IsHighlighted = value;
}
}
public override bool DrawWhenInactive
{
get
{
return _drawWhenInactive;
}
set
{
_drawWhenInactive = value;
}
}
public override Point Position
{
get { return base.Position; }
set
{
if (base.Position != value)
{
base.Position = value;
CalculateRect();
}
}
}
/// <summary>
/// A description of the function of the menu entry.
/// </summary>
public string Description { get; set; }
public bool IsQuiet { get; set; }
protected SoundEffect HighlightedSoundEffect { get; set; }
protected SoundEffect ClickedSoundEffect { get; set; }
public bool IsClicked
{
get
{
return _clickTimer.HasTimeRemaining;
}
set
{
Layout.IsClicked = value;
}
}
public override ITransitionObject TransitionObject
{
get
{
return base.TransitionObject;
}
set
{
base.TransitionObject = value;
if (null != Layout)
{
Layout.TransitionObject = value;
}
}
}
public string HighlightedSound { get; set; }
public string ClickedSound { get; set; }
/// <summary>
/// Event raised when the menu entry is selected.
/// </summary>
public event EventHandler OnLeft;
/// <summary>
/// Event raised when the menu entry is selected.
/// </summary>
public event EventHandler OnRight;
#endregion //Properties
#region Initialization
/// <summary>
/// Constructs a new button with the specified text.
/// </summary>
protected BaseButton()
{
Clickable = true;
IsQuiet = false;
_clickTimer = new CountdownTimer();
//by default, just play a sound when this item is selected
OnClick += PlaySelectedSound;
OnClick += ((obj, e) =>
{
_clickTimer.Start(ClickTimeDelta);
});
OnHighlight += PlayHighlightSound;
OnHighlight += ((obj, e) =>
{
IsHighlighted = true;
});
HighlightedSound = StyleSheet.HighlightedSoundResource;
ClickedSound = StyleSheet.ClickedSoundResource;
}
/// <summary>
/// Constructs a new button with the specified text.
/// </summary>
protected BaseButton(BaseButton inst) : base(inst)
{
Clickable = true;
_drawWhenInactive = inst._drawWhenInactive;
_size = inst._size;
Description = inst.Description;
OnClick = inst.OnClick;
IsQuiet = inst.IsQuiet;
HighlightedSoundEffect = inst.HighlightedSoundEffect;
ClickedSoundEffect = inst.ClickedSoundEffect;
_clickTimer = inst._clickTimer;
OnLeft = inst.OnLeft;
OnRight = inst.OnRight;
HighlightedSound = inst.HighlightedSound;
ClickedSound = inst.ClickedSound;
}
public override async Task LoadContent(IScreen screen)
{
if (null != screen.ScreenManager)
{
if (!string.IsNullOrEmpty(HighlightedSound))
{
HighlightedSoundEffect = screen.Content.Load<SoundEffect>(HighlightedSound);
}
if (!string.IsNullOrEmpty(ClickedSound))
{
ClickedSoundEffect = screen.Content.Load<SoundEffect>(ClickedSound);
}
}
await Layout.LoadContent(screen);
await base.LoadContent(screen);
}
public override void UnloadContent()
{
base.UnloadContent();
Layout?.UnloadContent();
Layout = null;
OnClick = null;
OnLeft = null;
OnRight = null;
}
#endregion //Initialization
#region Methods
public void AddItem(IScreenItem item)
{
Layout.AddItem(item);
CalculateRect();
var widget = item as ITransitionable;
if (null != widget)
{
widget.TransitionObject = TransitionObject;
}
}
public bool RemoveItem(IScreenItem item)
{
var result = Layout.RemoveItem(item);
CalculateRect();
return result;
}
public override void Update(IScreen screen, GameClock gameTime)
{
base.Update(screen, gameTime);
_clickTimer.Update(gameTime);
Layout.Update(screen, gameTime);
Layout.IsClicked = IsClicked;
}
public override void DrawBackground(IScreen screen, GameClock gameTime)
{
base.DrawBackground(screen, gameTime);
Layout.DrawBackground(screen, gameTime);
}
public override void Draw(IScreen screen, GameClock gameTime)
{
Layout.Draw(screen, gameTime);
}
protected override void CalculateRect()
{
_rect = Layout.Rect;
}
/// <summary>
/// Method for raising the Selected event.
/// </summary>
public void PlaySelectedSound(object obj, ClickEventArgs e)
{
//play the sound effect
if (!IsQuiet && (null != ClickedSoundEffect))
{
ClickedSoundEffect.Play();
}
}
public void PlayHighlightSound(object obj, HighlightEventArgs e)
{
if (!IsQuiet && (null != HighlightedSoundEffect))
{
//play menu noise
HighlightedSoundEffect.Play();
}
}
public virtual bool CheckClick(ClickEventArgs click)
{
//check if the widget was clicked
if (Rect.Contains(click.Position) && Clickable)
{
Clicked(this, click);
return true;
}
return false;
}
public virtual void Clicked(object obj, ClickEventArgs e)
{
if (OnClick != null)
{
OnClick(obj, e);
}
}
/// <summary>
/// Method for raising the Selected event.
/// </summary>
public virtual void OnLeftEntry()
{
if (OnLeft != null)
{
//play menu noise
PlayHighlightSound(this, new HighlightEventArgs(null));
OnLeft(this, new EventArgs());
}
}
/// <summary>
/// Method for raising the Selected event.
/// </summary>
public virtual void OnRightEntry()
{
if (OnRight != null)
{
//play menu noise
PlayHighlightSound(this, new HighlightEventArgs(null));
OnRight(this, new EventArgs());
}
}
#endregion //Methods
}
}
| |
// 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.Reflection.Metadata.Decoding;
using System.Reflection.Metadata.Ecma335;
namespace System.Reflection.Metadata
{
public struct CustomAttribute
{
private readonly MetadataReader _reader;
// Workaround: JIT doesn't generate good code for nested structures, so use RowId.
private readonly uint _treatmentAndRowId;
internal CustomAttribute(MetadataReader reader, uint treatmentAndRowId)
{
Debug.Assert(reader != null);
Debug.Assert(treatmentAndRowId != 0);
_reader = reader;
_treatmentAndRowId = treatmentAndRowId;
}
private int RowId
{
get { return (int)(_treatmentAndRowId & TokenTypeIds.RIDMask); }
}
private CustomAttributeHandle Handle
{
get { return CustomAttributeHandle.FromRowId(RowId); }
}
private MethodDefTreatment Treatment
{
get { return (MethodDefTreatment)(_treatmentAndRowId >> TokenTypeIds.RowIdBitCount); }
}
/// <summary>
/// The constructor (<see cref="MethodDefinitionHandle"/> or <see cref="MemberReferenceHandle"/>) of the custom attribute type.
/// </summary>
/// <remarks>
/// Corresponds to Type field of CustomAttribute table in ECMA-335 Standard.
/// </remarks>
public EntityHandle Constructor
{
get
{
return _reader.CustomAttributeTable.GetConstructor(Handle);
}
}
/// <summary>
/// The handle of the metadata entity the attribute is applied to.
/// </summary>
/// <remarks>
/// Corresponds to Parent field of CustomAttribute table in ECMA-335 Standard.
/// </remarks>
public EntityHandle Parent
{
get
{
return _reader.CustomAttributeTable.GetParent(Handle);
}
}
/// <summary>
/// The value of the attribute.
/// </summary>
/// <remarks>
/// Corresponds to Value field of CustomAttribute table in ECMA-335 Standard.
/// </remarks>
public BlobHandle Value
{
get
{
if (Treatment == 0)
{
return _reader.CustomAttributeTable.GetValue(Handle);
}
return GetProjectedValue();
}
}
/// <summary>
/// Decodes the arguments encoded in the value blob.
/// </summary>
#if FUTURE
public
#else
internal
#endif
CustomAttributeValue<TType> DecodeValue<TType>(ICustomAttributeTypeProvider<TType> provider)
{
var decoder = new CustomAttributeDecoder<TType>(provider, _reader);
return decoder.DecodeValue(Constructor, Value);
}
#region Projections
private BlobHandle GetProjectedValue()
{
// The usual pattern for accessing custom attributes differs from pattern for accessing e.g. TypeDef row fields.
// The value blob is only accessed when the consumer is about to decode it (which is a nontrivial process),
// while the Constructor and Parent fields are often accessed when searching for a particular attribute.
//
// The current WinMD projections only affect the blob and not the Constructor and Parent values.
// It is thus more efficient to calculate the treatment here (and make GetValue more expensive) and
// avoid calculating the treatment when the CustomAttributeHandle is looked up and CustomAttribute struct
// is initialized.
CustomAttributeValueTreatment treatment = _reader.CalculateCustomAttributeValueTreatment(Handle);
if (treatment == 0)
{
return _reader.CustomAttributeTable.GetValue(Handle);
}
return GetProjectedValue(treatment);
}
private BlobHandle GetProjectedValue(CustomAttributeValueTreatment treatment)
{
BlobHandle.VirtualIndex virtualIndex;
bool isVersionOrDeprecated;
switch (treatment)
{
case CustomAttributeValueTreatment.AttributeUsageVersionAttribute:
case CustomAttributeValueTreatment.AttributeUsageDeprecatedAttribute:
virtualIndex = BlobHandle.VirtualIndex.AttributeUsage_AllowMultiple;
isVersionOrDeprecated = true;
break;
case CustomAttributeValueTreatment.AttributeUsageAllowMultiple:
virtualIndex = BlobHandle.VirtualIndex.AttributeUsage_AllowMultiple;
isVersionOrDeprecated = false;
break;
case CustomAttributeValueTreatment.AttributeUsageAllowSingle:
virtualIndex = BlobHandle.VirtualIndex.AttributeUsage_AllowSingle;
isVersionOrDeprecated = false;
break;
default:
Debug.Assert(false);
return default(BlobHandle);
}
// Raw blob format:
// 01 00 - Fixed prolog for CA's
// xx xx xx xx - The Windows.Foundation.Metadata.AttributeTarget value
// 00 00 - Indicates 0 name/value pairs following.
var rawBlob = _reader.CustomAttributeTable.GetValue(Handle);
var rawBlobReader = _reader.GetBlobReader(rawBlob);
if (rawBlobReader.Length != 8)
{
return rawBlob;
}
if (rawBlobReader.ReadInt16() != 1)
{
return rawBlob;
}
AttributeTargets projectedValue = ProjectAttributeTargetValue(rawBlobReader.ReadUInt32());
if (isVersionOrDeprecated)
{
projectedValue |= AttributeTargets.Constructor | AttributeTargets.Property;
}
return BlobHandle.FromVirtualIndex(virtualIndex, (ushort)projectedValue);
}
private static AttributeTargets ProjectAttributeTargetValue(uint rawValue)
{
// Windows.Foundation.Metadata.AttributeTargets.All
if (rawValue == 0xffffffff)
{
return AttributeTargets.All;
}
AttributeTargets result = 0;
if ((rawValue & 0x00000001) != 0) result |= AttributeTargets.Delegate;
if ((rawValue & 0x00000002) != 0) result |= AttributeTargets.Enum;
if ((rawValue & 0x00000004) != 0) result |= AttributeTargets.Event;
if ((rawValue & 0x00000008) != 0) result |= AttributeTargets.Field;
if ((rawValue & 0x00000010) != 0) result |= AttributeTargets.Interface;
// InterfaceGroup (no equivalent in CLR)
if ((rawValue & 0x00000040) != 0) result |= AttributeTargets.Method;
if ((rawValue & 0x00000080) != 0) result |= AttributeTargets.Parameter;
if ((rawValue & 0x00000100) != 0) result |= AttributeTargets.Property;
if ((rawValue & 0x00000200) != 0) result |= AttributeTargets.Class;
if ((rawValue & 0x00000400) != 0) result |= AttributeTargets.Struct;
// InterfaceImpl (no equivalent in CLR)
return result;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
#if NETSTANDARD
using System.Reflection;
#endif
using System.Runtime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Orleans.CodeGeneration;
using Orleans.Core;
using Orleans.GrainDirectory;
using Orleans.LogConsistency;
using Orleans.Providers;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.ConsistentRing;
using Orleans.Runtime.Counters;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.LogConsistency;
using Orleans.Runtime.MembershipService;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.MultiClusterNetwork;
using Orleans.Runtime.Placement;
using Orleans.Runtime.Providers;
using Orleans.Runtime.ReminderService;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.Startup;
using Orleans.Runtime.Storage;
using Orleans.Runtime.TestHooks;
using Orleans.Runtime.Utilities;
using Orleans.Serialization;
using Orleans.Services;
using Orleans.Storage;
using Orleans.Streams;
using Orleans.Timers;
using Orleans.MultiCluster;
using Orleans.Runtime.Versions;
using Orleans.Runtime.Versions.Compatibility;
using Orleans.Streams.Core;
using Orleans.Versions.Compatibility;
using Orleans.Runtime.Versions.Selector;
using Orleans.Versions.Selector;
namespace Orleans.Runtime
{
/// <summary>
/// Orleans silo.
/// </summary>
public class Silo
{
/// <summary> Standard name for Primary silo. </summary>
public const string PrimarySiloName = "Primary";
/// <summary> Silo Types. </summary>
public enum SiloType
{
/// <summary> No silo type specified. </summary>
None = 0,
/// <summary> Primary silo. </summary>
Primary,
/// <summary> Secondary silo. </summary>
Secondary,
}
private readonly SiloInitializationParameters initializationParams;
private readonly ISiloMessageCenter messageCenter;
private readonly OrleansTaskScheduler scheduler;
private readonly LocalGrainDirectory localGrainDirectory;
private readonly ActivationDirectory activationDirectory;
private readonly IncomingMessageAgent incomingAgent;
private readonly IncomingMessageAgent incomingSystemAgent;
private readonly IncomingMessageAgent incomingPingAgent;
private readonly Logger logger;
private readonly GrainTypeManager grainTypeManager;
private TypeManager typeManager;
private readonly ManualResetEvent siloTerminatedEvent;
private readonly SiloStatisticsManager siloStatistics;
private readonly InsideRuntimeClient runtimeClient;
private readonly AssemblyProcessor assemblyProcessor;
private StorageProviderManager storageProviderManager;
private LogConsistencyProviderManager logConsistencyProviderManager;
private StatisticsProviderManager statisticsProviderManager;
private BootstrapProviderManager bootstrapProviderManager;
private IReminderService reminderService;
private ProviderManagerSystemTarget providerManagerSystemTarget;
private readonly IMembershipOracle membershipOracle;
private readonly IMultiClusterOracle multiClusterOracle;
private Watchdog platformWatchdog;
private readonly TimeSpan initTimeout;
private readonly TimeSpan stopTimeout = TimeSpan.FromMinutes(1);
private readonly Catalog catalog;
private readonly List<IHealthCheckParticipant> healthCheckParticipants = new List<IHealthCheckParticipant>();
private readonly object lockable = new object();
private readonly GrainFactory grainFactory;
private readonly IGrainRuntime grainRuntime;
private readonly List<IProvider> allSiloProviders = new List<IProvider>();
/// <summary>
/// Gets the type of this
/// </summary>
public SiloType Type => this.initializationParams.Type;
internal string Name => this.initializationParams.Name;
internal ClusterConfiguration OrleansConfig => this.initializationParams.ClusterConfig;
internal GlobalConfiguration GlobalConfig => this.initializationParams.GlobalConfig;
internal NodeConfiguration LocalConfig => this.initializationParams.NodeConfig;
internal OrleansTaskScheduler LocalScheduler { get { return scheduler; } }
internal GrainTypeManager LocalGrainTypeManager { get { return grainTypeManager; } }
internal ILocalGrainDirectory LocalGrainDirectory { get { return localGrainDirectory; } }
internal IMultiClusterOracle LocalMultiClusterOracle { get { return multiClusterOracle; } }
internal IConsistentRingProvider RingProvider { get; private set; }
internal ILogConsistencyProviderManager LogConsistencyProviderManager { get { return logConsistencyProviderManager; } }
internal IStorageProviderManager StorageProviderManager { get { return storageProviderManager; } }
internal IProviderManager StatisticsProviderManager { get { return statisticsProviderManager; } }
internal IStreamProviderManager StreamProviderManager { get { return grainRuntime.StreamProviderManager; } }
internal IList<IBootstrapProvider> BootstrapProviders { get; private set; }
internal ISiloPerformanceMetrics Metrics { get { return siloStatistics.MetricsTable; } }
internal IReadOnlyCollection<IProvider> AllSiloProviders
{
get { return allSiloProviders.AsReadOnly(); }
}
internal ICatalog Catalog => catalog;
internal SystemStatus SystemStatus { get; set; }
internal IServiceProvider Services { get; }
/// <summary> SiloAddress for this silo. </summary>
public SiloAddress SiloAddress => this.initializationParams.SiloAddress;
/// <summary>
/// Silo termination event used to signal shutdown of this silo.
/// </summary>
public WaitHandle SiloTerminatedEvent { get { return siloTerminatedEvent; } } // one event for all types of termination (shutdown, stop and fast kill).
/// <summary>
/// Test hook connection for white-box testing of silo.
/// </summary>
internal TestHooksSystemTarget testHook;
/// <summary>
/// Initializes a new instance of the <see cref="Silo"/> class.
/// </summary>
/// <param name="name">Name of this silo.</param>
/// <param name="siloType">Type of this silo.</param>
/// <param name="config">Silo config data to be used for this silo.</param>
public Silo(string name, SiloType siloType, ClusterConfiguration config)
: this(new SiloInitializationParameters(name, siloType, config))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Silo"/> class.
/// </summary>
/// <param name="initializationParams">
/// The silo initialization parameters.
/// </param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "Should not Dispose of messageCenter in this method because it continues to run / exist after this point.")]
internal Silo(SiloInitializationParameters initializationParams)
{
string name = initializationParams.Name;
ClusterConfiguration config = initializationParams.ClusterConfig;
this.initializationParams = initializationParams;
this.SystemStatus = SystemStatus.Creating;
AsynchAgent.IsStarting = true;
var startTime = DateTime.UtcNow;
siloTerminatedEvent = new ManualResetEvent(false);
if (!LogManager.IsInitialized)
LogManager.Initialize(LocalConfig);
config.OnConfigChange("Defaults/Tracing", () => LogManager.Initialize(LocalConfig, true), false);
StatisticsCollector.Initialize(LocalConfig);
initTimeout = GlobalConfig.MaxJoinAttemptTime;
if (Debugger.IsAttached)
{
initTimeout = StandardExtensions.Max(TimeSpan.FromMinutes(10), GlobalConfig.MaxJoinAttemptTime);
stopTimeout = initTimeout;
}
var localEndpoint = this.initializationParams.SiloAddress.Endpoint;
LogManager.MyIPEndPoint = localEndpoint;
logger = LogManager.GetLogger("Silo", LoggerType.Runtime);
logger.Info(ErrorCode.SiloGcSetting, "Silo starting with GC settings: ServerGC={0} GCLatencyMode={1}", GCSettings.IsServerGC, Enum.GetName(typeof(GCLatencyMode), GCSettings.LatencyMode));
if (!GCSettings.IsServerGC || !GCSettings.LatencyMode.Equals(GCLatencyMode.Batch))
{
logger.Warn(ErrorCode.SiloGcWarning, "Note: Silo not running with ServerGC turned on or with GCLatencyMode.Batch enabled - recommend checking app config : <configuration>-<runtime>-<gcServer enabled=\"true\"> and <configuration>-<runtime>-<gcConcurrent enabled=\"false\"/>");
logger.Warn(ErrorCode.SiloGcWarning, "Note: ServerGC only kicks in on multi-core systems (settings enabling ServerGC have no effect on single-core machines).");
}
logger.Info(ErrorCode.SiloInitializing, "-------------- Initializing {0} silo on host {1} MachineName {2} at {3}, gen {4} --------------",
this.initializationParams.Type, LocalConfig.DNSHostName, Environment.MachineName, localEndpoint, this.initializationParams.SiloAddress.Generation);
logger.Info(ErrorCode.SiloInitConfig, "Starting silo {0} with the following configuration= " + Environment.NewLine + "{1}",
name, config.ToString(name));
// Register system services.
var services = new ServiceCollection();
services.AddSingleton(this);
services.AddSingleton(initializationParams);
services.AddFromExisting<ILocalSiloDetails, SiloInitializationParameters>();
services.AddSingleton(initializationParams.ClusterConfig);
services.AddSingleton(initializationParams.GlobalConfig);
services.AddTransient(sp => initializationParams.NodeConfig);
services.AddTransient<Func<NodeConfiguration>>(sp => () => initializationParams.NodeConfig);
services.AddTransient(typeof(IStreamSubscriptionObserver<>),typeof(StreamSubscriptionObserverProxy<>));
services.AddFromExisting<IMessagingConfiguration, GlobalConfiguration>();
services.AddFromExisting<ITraceConfiguration, NodeConfiguration>();
services.AddSingleton<SerializationManager>();
services.AddSingleton<ITimerRegistry, TimerRegistry>();
services.AddSingleton<IReminderRegistry, ReminderRegistry>();
services.AddSingleton<IStreamProviderManager, StreamProviderManager>();
services.AddSingleton<GrainRuntime>();
services.AddSingleton<IGrainRuntime, GrainRuntime>();
services.AddSingleton<OrleansTaskScheduler>();
services.AddSingleton<GrainFactory>(sp => sp.GetService<InsideRuntimeClient>().ConcreteGrainFactory);
services.AddFromExisting<IGrainFactory, GrainFactory>();
services.AddFromExisting<IInternalGrainFactory, GrainFactory>();
services.AddFromExisting<IGrainReferenceConverter, GrainFactory>();
services.AddSingleton<TypeMetadataCache>();
services.AddSingleton<AssemblyProcessor>();
services.AddSingleton<ActivationDirectory>();
services.AddSingleton<LocalGrainDirectory>();
services.AddFromExisting<ILocalGrainDirectory, LocalGrainDirectory>();
services.AddSingleton(sp => sp.GetRequiredService<LocalGrainDirectory>().GsiActivationMaintainer);
services.AddSingleton<SiloStatisticsManager>();
services.AddSingleton<ISiloPerformanceMetrics>(sp => sp.GetRequiredService<SiloStatisticsManager>().MetricsTable);
services.AddFromExisting<ICorePerformanceMetrics, ISiloPerformanceMetrics>();
services.AddSingleton<SiloAssemblyLoader>();
services.AddSingleton<GrainTypeManager>();
services.AddFromExisting<IMessagingConfiguration, GlobalConfiguration>();
services.AddSingleton<MessageCenter>();
services.AddFromExisting<IMessageCenter, MessageCenter>();
services.AddFromExisting<ISiloMessageCenter, MessageCenter>();
services.AddSingleton(FactoryUtility.Create<MessageCenter, Gateway>);
services.AddSingleton<Dispatcher>(sp => sp.GetRequiredService<Catalog>().Dispatcher);
services.AddSingleton<InsideRuntimeClient>();
services.AddFromExisting<IRuntimeClient, InsideRuntimeClient>();
services.AddFromExisting<ISiloRuntimeClient, InsideRuntimeClient>();
services.AddSingleton<MultiClusterGossipChannelFactory>();
services.AddSingleton<MultiClusterOracle>();
services.AddSingleton<MultiClusterRegistrationStrategyManager>();
services.AddFromExisting<IMultiClusterOracle, MultiClusterOracle>();
services.AddSingleton<DeploymentLoadPublisher>();
services.AddSingleton<MembershipOracle>();
services.AddFromExisting<IMembershipOracle, MembershipOracle>();
services.AddFromExisting<ISiloStatusOracle, MembershipOracle>();
services.AddSingleton<MembershipTableFactory>();
services.AddSingleton<ReminderTableFactory>();
services.AddSingleton<IReminderTable>(sp => sp.GetRequiredService<ReminderTableFactory>().Create());
services.AddSingleton<LocalReminderServiceFactory>();
services.AddSingleton<ClientObserverRegistrar>();
services.AddSingleton<SiloProviderRuntime>();
services.AddFromExisting<IStreamProviderRuntime, SiloProviderRuntime>();
services.AddSingleton<ImplicitStreamSubscriberTable>();
services.AddSingleton<MessageFactory>();
services.AddSingleton<Factory<string, Logger>>(LogManager.GetLogger);
services.AddSingleton<CodeGeneratorManager>();
services.AddSingleton<IGrainRegistrar<GlobalSingleInstanceRegistration>, GlobalSingleInstanceRegistrar>();
services.AddSingleton<IGrainRegistrar<ClusterLocalRegistration>, ClusterLocalRegistrar>();
services.AddSingleton<RegistrarManager>();
services.AddSingleton(FactoryUtility.Create<Grain, IMultiClusterRegistrationStrategy, ProtocolServices>);
services.AddSingleton(FactoryUtility.Create<GrainDirectoryPartition>);
// Placement
services.AddSingleton<PlacementDirectorsManager>();
services.AddSingleton<IPlacementDirector<RandomPlacement>, RandomPlacementDirector>();
services.AddSingleton<IActivationSelector<RandomPlacement>, RandomPlacementDirector>();
services.AddSingleton<IPlacementDirector<PreferLocalPlacement>, PreferLocalPlacementDirector>();
services.AddSingleton<IPlacementDirector<StatelessWorkerPlacement>, StatelessWorkerDirector>();
services.AddSingleton<IActivationSelector<StatelessWorkerPlacement>, StatelessWorkerDirector>();
services.AddSingleton<IPlacementDirector<ActivationCountBasedPlacement>, ActivationCountPlacementDirector>();
services.AddSingleton<IPlacementDirector<HashBasedPlacement>, HashBasedPlacementDirector>();
services.AddSingleton<DefaultPlacementStrategy>();
services.AddSingleton<ClientObserversPlacementDirector>();
// Versions
services.AddSingleton<VersionSelectorManager>();
services.AddSingleton<IVersionSelector<MinimumVersion>, MinimumVersionSelector>();
services.AddSingleton<IVersionSelector<LatestVersion>, LatestVersionSelector>();
services.AddSingleton<IVersionSelector<AllCompatibleVersions>, AllCompatibleVersionsSelector>();
services.AddSingleton<CompatibilityDirectorManager>();
services.AddSingleton<ICompatibilityDirector<BackwardCompatible>, BackwardCompatilityDirector>();
services.AddSingleton<ICompatibilityDirector<AllVersionsCompatible>, AllVersionsCompatibilityDirector>();
services.AddSingleton<CachedVersionSelectorManager>();
services.AddSingleton<Func<IGrainRuntime>>(sp => () => sp.GetRequiredService<IGrainRuntime>());
// Grain activation
services.AddSingleton<Catalog>();
services.AddSingleton<GrainCreator>();
services.AddSingleton<IGrainActivator, DefaultGrainActivator>();
services.AddSingleton<IStreamSubscriptionManagerAdmin>(sp => new StreamSubscriptionManagerAdmin(sp.GetRequiredService<IStreamProviderRuntime>()));
if (initializationParams.GlobalConfig.UseVirtualBucketsConsistentRing)
{
services.AddSingleton<IConsistentRingProvider>(
sp =>
new VirtualBucketsRingProvider(
this.initializationParams.SiloAddress,
this.initializationParams.GlobalConfig.NumVirtualBucketsConsistentRing));
}
else
{
services.AddSingleton<IConsistentRingProvider>(
sp => new ConsistentRingProvider(this.initializationParams.SiloAddress));
}
// Configure DI using Startup type
this.Services = StartupBuilder.ConfigureStartup(this.LocalConfig.StartupTypeName, services);
this.assemblyProcessor = this.Services.GetRequiredService<AssemblyProcessor>();
this.assemblyProcessor.Initialize();
BufferPool.InitGlobalBufferPool(GlobalConfig);
if (!UnobservedExceptionsHandlerClass.TrySetUnobservedExceptionHandler(UnobservedExceptionHandler))
{
logger.Warn(ErrorCode.Runtime_Error_100153, "Unable to set unobserved exception handler because it was already set.");
}
AppDomain.CurrentDomain.UnhandledException += this.DomainUnobservedExceptionHandler;
try
{
grainFactory = Services.GetRequiredService<GrainFactory>();
}
catch (InvalidOperationException exc)
{
logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start, GrainFactory was not registered in Dependency Injection container", exc);
throw;
}
grainTypeManager = Services.GetRequiredService<GrainTypeManager>();
// Performance metrics
siloStatistics = Services.GetRequiredService<SiloStatisticsManager>();
// The scheduler
scheduler = Services.GetRequiredService<OrleansTaskScheduler>();
healthCheckParticipants.Add(scheduler);
runtimeClient = Services.GetRequiredService<InsideRuntimeClient>();
// Initialize the message center
messageCenter = Services.GetRequiredService<MessageCenter>();
var dispatcher = this.Services.GetRequiredService<Dispatcher>();
messageCenter.RerouteHandler = dispatcher.RerouteMessage;
messageCenter.SniffIncomingMessage = runtimeClient.SniffIncomingMessage;
// GrainRuntime can be created only here, after messageCenter was created.
grainRuntime = Services.GetRequiredService<IGrainRuntime>();
// Now the router/directory service
// This has to come after the message center //; note that it then gets injected back into the message center.;
localGrainDirectory = Services.GetRequiredService<LocalGrainDirectory>();
// Now the activation directory.
activationDirectory = Services.GetRequiredService<ActivationDirectory>();
// Now the consistent ring provider
RingProvider = Services.GetRequiredService<IConsistentRingProvider>();
catalog = Services.GetRequiredService<Catalog>();
siloStatistics.MetricsTable.Scheduler = scheduler;
siloStatistics.MetricsTable.ActivationDirectory = activationDirectory;
siloStatistics.MetricsTable.ActivationCollector = catalog.ActivationCollector;
siloStatistics.MetricsTable.MessageCenter = messageCenter;
// Now the incoming message agents
var messageFactory = this.Services.GetRequiredService<MessageFactory>();
incomingSystemAgent = new IncomingMessageAgent(Message.Categories.System, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory);
incomingPingAgent = new IncomingMessageAgent(Message.Categories.Ping, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory);
incomingAgent = new IncomingMessageAgent(Message.Categories.Application, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory);
membershipOracle = Services.GetRequiredService<IMembershipOracle>();
if (!this.GlobalConfig.HasMultiClusterNetwork)
{
logger.Info("Skip multicluster oracle creation (no multicluster network configured)");
}
else
{
multiClusterOracle = Services.GetRequiredService<IMultiClusterOracle>();
}
this.SystemStatus = SystemStatus.Created;
AsynchAgent.IsStarting = false;
StringValueStatistic.FindOrCreate(StatisticNames.SILO_START_TIME,
() => LogFormatter.PrintDate(startTime)); // this will help troubleshoot production deployment when looking at MDS logs.
logger.Info(ErrorCode.SiloInitializingFinished, "-------------- Started silo {0}, ConsistentHashCode {1:X} --------------", SiloAddress.ToLongString(), SiloAddress.GetConsistentHashCode());
}
private void CreateSystemTargets()
{
logger.Verbose("Creating System Targets for this silo.");
logger.Verbose("Creating {0} System Target", "SiloControl");
var siloControl = ActivatorUtilities.CreateInstance<SiloControl>(Services);
RegisterSystemTarget(siloControl);
logger.Verbose("Creating {0} System Target", "StreamProviderUpdateAgent");
RegisterSystemTarget(
new StreamProviderManagerAgent(this, allSiloProviders, Services.GetRequiredService<IStreamProviderRuntime>()));
logger.Verbose("Creating {0} System Target", "ProtocolGateway");
RegisterSystemTarget(new ProtocolGateway(this.SiloAddress));
logger.Verbose("Creating {0} System Target", "DeploymentLoadPublisher");
RegisterSystemTarget(Services.GetRequiredService<DeploymentLoadPublisher>());
logger.Verbose("Creating {0} System Target", "RemoteGrainDirectory + CacheValidator");
RegisterSystemTarget(LocalGrainDirectory.RemoteGrainDirectory);
RegisterSystemTarget(LocalGrainDirectory.CacheValidator);
logger.Verbose("Creating {0} System Target", "RemoteClusterGrainDirectory");
RegisterSystemTarget(LocalGrainDirectory.RemoteClusterGrainDirectory);
logger.Verbose("Creating {0} System Target", "ClientObserverRegistrar + TypeManager");
this.RegisterSystemTarget(this.Services.GetRequiredService<ClientObserverRegistrar>());
var implicitStreamSubscriberTable = Services.GetRequiredService<ImplicitStreamSubscriberTable>();
var versionDirectorManager = this.Services.GetRequiredService<CachedVersionSelectorManager>();
typeManager = new TypeManager(SiloAddress, this.grainTypeManager, membershipOracle, LocalScheduler, GlobalConfig.TypeMapRefreshInterval, implicitStreamSubscriberTable, this.grainFactory, versionDirectorManager);
this.RegisterSystemTarget(typeManager);
logger.Verbose("Creating {0} System Target", "MembershipOracle");
if (this.membershipOracle is SystemTarget)
{
RegisterSystemTarget((SystemTarget)membershipOracle);
}
if (multiClusterOracle != null && multiClusterOracle is SystemTarget)
{
logger.Verbose("Creating {0} System Target", "MultiClusterOracle");
RegisterSystemTarget((SystemTarget)multiClusterOracle);
}
logger.Verbose("Finished creating System Targets for this silo.");
}
internal void InitializeTestHooksSystemTarget()
{
testHook = new TestHooksSystemTarget(this);
RegisterSystemTarget(testHook);
}
private void InjectDependencies()
{
healthCheckParticipants.Add(membershipOracle);
catalog.SiloStatusOracle = this.membershipOracle;
localGrainDirectory.CatalogSiloStatusListener = catalog;
this.membershipOracle.SubscribeToSiloStatusEvents(localGrainDirectory);
messageCenter.SiloDeadOracle = this.membershipOracle.IsDeadSilo;
// consistentRingProvider is not a system target per say, but it behaves like the localGrainDirectory, so it is here
this.membershipOracle.SubscribeToSiloStatusEvents((ISiloStatusListener)RingProvider);
this.membershipOracle.SubscribeToSiloStatusEvents(typeManager);
this.membershipOracle.SubscribeToSiloStatusEvents(Services.GetRequiredService<DeploymentLoadPublisher>());
this.membershipOracle.SubscribeToSiloStatusEvents(Services.GetRequiredService<ClientObserverRegistrar>());
if (!GlobalConfig.ReminderServiceType.Equals(GlobalConfiguration.ReminderServiceProviderType.Disabled))
{
// start the reminder service system target
reminderService = Services.GetRequiredService<LocalReminderServiceFactory>()
.CreateReminderService(this, initTimeout, this.runtimeClient);
var reminderServiceSystemTarget = this.reminderService as SystemTarget;
if (reminderServiceSystemTarget != null) RegisterSystemTarget(reminderServiceSystemTarget);
}
RegisterSystemTarget(catalog);
scheduler.QueueAction(catalog.Start, catalog.SchedulingContext)
.WaitWithThrow(initTimeout);
// SystemTarget for provider init calls
providerManagerSystemTarget = new ProviderManagerSystemTarget(this);
RegisterSystemTarget(providerManagerSystemTarget);
}
/// <summary> Perform silo startup operations. </summary>
public void Start()
{
try
{
DoStart();
}
catch (Exception exc)
{
logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start", exc);
throw;
}
}
private void DoStart()
{
lock (lockable)
{
if (!this.SystemStatus.Equals(SystemStatus.Created))
throw new InvalidOperationException(String.Format("Calling Silo.Start() on a silo which is not in the Created state. This silo is in the {0} state.", this.SystemStatus));
this.SystemStatus = SystemStatus.Starting;
}
logger.Info(ErrorCode.SiloStarting, "Silo Start()");
// Hook up to receive notification of process exit / Ctrl-C events
AppDomain.CurrentDomain.ProcessExit += HandleProcessExit;
Console.CancelKeyPress += HandleProcessExit;
ConfigureThreadPoolAndServicePointSettings();
// This has to start first so that the directory system target factory gets loaded before we start the router.
grainTypeManager.Start();
runtimeClient.Start();
// The order of these 4 is pretty much arbitrary.
scheduler.Start();
messageCenter.Start();
incomingPingAgent.Start();
incomingSystemAgent.Start();
incomingAgent.Start();
LocalGrainDirectory.Start();
// Set up an execution context for this thread so that the target creation steps can use asynch values.
RuntimeContext.InitializeMainThread();
// Initialize the implicit stream subscribers table.
var implicitStreamSubscriberTable = Services.GetRequiredService<ImplicitStreamSubscriberTable>();
implicitStreamSubscriberTable.InitImplicitStreamSubscribers(this.grainTypeManager.GrainClassTypeData.Select(t => t.Value.Type).ToArray());
var siloProviderRuntime = Services.GetRequiredService<SiloProviderRuntime>();
runtimeClient.CurrentStreamProviderRuntime = siloProviderRuntime;
statisticsProviderManager = new StatisticsProviderManager(ProviderCategoryConfiguration.STATISTICS_PROVIDER_CATEGORY_NAME, siloProviderRuntime);
string statsProviderName = statisticsProviderManager.LoadProvider(GlobalConfig.ProviderConfigurations)
.WaitForResultWithThrow(initTimeout);
if (statsProviderName != null)
LocalConfig.StatisticsProviderName = statsProviderName;
allSiloProviders.AddRange(statisticsProviderManager.GetProviders());
// can call SetSiloMetricsTableDataManager only after MessageCenter is created (dependency on this.SiloAddress).
siloStatistics.SetSiloStatsTableDataManager(this, LocalConfig).WaitWithThrow(initTimeout);
siloStatistics.SetSiloMetricsTableDataManager(this, LocalConfig).WaitWithThrow(initTimeout);
// This has to follow the above steps that start the runtime components
CreateSystemTargets();
InjectDependencies();
// Validate the configuration.
GlobalConfig.Application.ValidateConfiguration(logger);
// Initialize storage providers once we have a basic silo runtime environment operating
storageProviderManager = new StorageProviderManager(grainFactory, Services, siloProviderRuntime);
scheduler.QueueTask(
() => storageProviderManager.LoadStorageProviders(GlobalConfig.ProviderConfigurations),
providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
catalog.SetStorageManager(storageProviderManager);
allSiloProviders.AddRange(storageProviderManager.GetProviders());
if (logger.IsVerbose) { logger.Verbose("Storage provider manager created successfully."); }
// Initialize log consistency providers once we have a basic silo runtime environment operating
logConsistencyProviderManager = new LogConsistencyProviderManager(grainFactory, Services, siloProviderRuntime);
scheduler.QueueTask(
() => logConsistencyProviderManager.LoadLogConsistencyProviders(GlobalConfig.ProviderConfigurations),
providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
catalog.SetLogConsistencyManager(logConsistencyProviderManager);
if (logger.IsVerbose) { logger.Verbose("Log consistency provider manager created successfully."); }
// Load and init stream providers before silo becomes active
var siloStreamProviderManager = (StreamProviderManager)grainRuntime.StreamProviderManager;
scheduler.QueueTask(
() => siloStreamProviderManager.LoadStreamProviders(GlobalConfig.ProviderConfigurations, siloProviderRuntime),
providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
runtimeClient.CurrentStreamProviderManager = siloStreamProviderManager;
allSiloProviders.AddRange(siloStreamProviderManager.GetProviders());
if (logger.IsVerbose) { logger.Verbose("Stream provider manager created successfully."); }
// Load and init grain services before silo becomes active.
CreateGrainServices(GlobalConfig.GrainServiceConfigurations);
ISchedulingContext statusOracleContext = (this.membershipOracle as SystemTarget)?.SchedulingContext;
scheduler.QueueTask(() => this.membershipOracle.Start(), statusOracleContext)
.WaitWithThrow(initTimeout);
if (logger.IsVerbose) { logger.Verbose("Local silo status oracle created successfully."); }
scheduler.QueueTask(this.membershipOracle.BecomeActive, statusOracleContext)
.WaitWithThrow(initTimeout);
if (logger.IsVerbose) { logger.Verbose("Local silo status oracle became active successfully."); }
//if running in multi cluster scenario, start the MultiClusterNetwork Oracle
if (GlobalConfig.HasMultiClusterNetwork)
{
logger.Info("Starting multicluster oracle with my ServiceId={0} and ClusterId={1}.",
GlobalConfig.ServiceId, GlobalConfig.ClusterId);
ISchedulingContext clusterStatusContext = (multiClusterOracle as SystemTarget)?.SchedulingContext;
scheduler.QueueTask(() => multiClusterOracle.Start(), clusterStatusContext)
.WaitWithThrow(initTimeout);
if (logger.IsVerbose) { logger.Verbose("multicluster oracle created successfully."); }
}
try
{
this.siloStatistics.Start(this.LocalConfig);
if (this.logger.IsVerbose) { this.logger.Verbose("Silo statistics manager started successfully."); }
// Finally, initialize the deployment load collector, for grains with load-based placement
var deploymentLoadPublisher = Services.GetRequiredService<DeploymentLoadPublisher>();
this.scheduler.QueueTask(deploymentLoadPublisher.Start, deploymentLoadPublisher.SchedulingContext)
.WaitWithThrow(this.initTimeout);
if (this.logger.IsVerbose) { this.logger.Verbose("Silo deployment load publisher started successfully."); }
// Start background timer tick to watch for platform execution stalls, such as when GC kicks in
this.platformWatchdog = new Watchdog(this.LocalConfig.StatisticsLogWriteInterval, this.healthCheckParticipants);
this.platformWatchdog.Start();
if (this.logger.IsVerbose) { this.logger.Verbose("Silo platform watchdog started successfully."); }
if (this.reminderService != null)
{
// so, we have the view of the membership in the consistentRingProvider. We can start the reminder service
this.scheduler.QueueTask(this.reminderService.Start, (this.reminderService as SystemTarget)?.SchedulingContext)
.WaitWithThrow(this.initTimeout);
if (this.logger.IsVerbose)
{
this.logger.Verbose("Reminder service started successfully.");
}
}
this.bootstrapProviderManager = new BootstrapProviderManager();
this.scheduler.QueueTask(
() => this.bootstrapProviderManager.LoadAppBootstrapProviders(siloProviderRuntime, this.GlobalConfig.ProviderConfigurations),
this.providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(this.initTimeout);
this.BootstrapProviders = this.bootstrapProviderManager.GetProviders(); // Data hook for testing & diagnotics
this.allSiloProviders.AddRange(this.BootstrapProviders);
if (this.logger.IsVerbose) { this.logger.Verbose("App bootstrap calls done successfully."); }
// Start stream providers after silo is active (so the pulling agents don't start sending messages before silo is active).
// also after bootstrap provider started so bootstrap provider can initialize everything stream before events from this silo arrive.
this.scheduler.QueueTask(siloStreamProviderManager.StartStreamProviders, this.providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(this.initTimeout);
if (this.logger.IsVerbose) { this.logger.Verbose("Stream providers started successfully."); }
// Now that we're active, we can start the gateway
var mc = this.messageCenter as MessageCenter;
mc?.StartGateway(this.Services.GetRequiredService<ClientObserverRegistrar>());
if (this.logger.IsVerbose) { this.logger.Verbose("Message gateway service started successfully."); }
this.SystemStatus = SystemStatus.Running;
}
catch (Exception exc)
{
this.SafeExecute(() => this.logger.Error(ErrorCode.Runtime_Error_100330, String.Format("Error starting silo {0}. Going to FastKill().", this.SiloAddress), exc));
this.FastKill(); // if failed after Membership became active, mark itself as dead in Membership abale.
throw;
}
if (logger.IsVerbose) { logger.Verbose("Silo.Start complete: System status = {0}", this.SystemStatus); }
}
private void CreateGrainServices(GrainServiceConfigurations grainServiceConfigurations)
{
foreach (var serviceConfig in grainServiceConfigurations.GrainServices)
{
// Construct the Grain Service
var serviceType = System.Type.GetType(serviceConfig.Value.ServiceType);
if (serviceType == null)
{
throw new Exception(String.Format("Cannot find Grain Service type {0} of Grain Service {1}", serviceConfig.Value.ServiceType, serviceConfig.Value.Name));
}
var grainServiceInterfaceType = serviceType.GetInterfaces().FirstOrDefault(x => x.GetInterfaces().Contains(typeof(IGrainService)));
if (grainServiceInterfaceType == null)
{
throw new Exception(String.Format("Cannot find an interface on {0} which implements IGrainService", serviceConfig.Value.ServiceType));
}
var typeCode = GrainInterfaceUtils.GetGrainClassTypeCode(grainServiceInterfaceType);
var grainId = (IGrainIdentity)GrainId.GetGrainServiceGrainId(0, typeCode);
var grainService = (GrainService)ActivatorUtilities.CreateInstance(this.Services, serviceType, grainId, serviceConfig.Value);
RegisterSystemTarget(grainService);
this.scheduler.QueueTask(() => grainService.Init(Services), grainService.SchedulingContext).WaitWithThrow(this.initTimeout);
this.scheduler.QueueTask(grainService.Start, grainService.SchedulingContext).WaitWithThrow(this.initTimeout);
if (this.logger.IsVerbose)
{
this.logger.Verbose(String.Format("{0} Grain Service started successfully.", serviceConfig.Value.Name));
}
}
}
/// <summary>
/// Load and initialize newly added stream providers. Remove providers that are not on the list that's being passed in.
/// </summary>
public async Task UpdateStreamProviders(IDictionary<string, ProviderCategoryConfiguration> streamProviderConfigurations)
{
IStreamProviderManagerAgent streamProviderUpdateAgent =
runtimeClient.InternalGrainFactory.GetSystemTarget<IStreamProviderManagerAgent>(Constants.StreamProviderManagerAgentSystemTargetId, this.SiloAddress);
await scheduler.QueueTask(() => streamProviderUpdateAgent.UpdateStreamProviders(streamProviderConfigurations), providerManagerSystemTarget.SchedulingContext)
.WithTimeout(initTimeout);
}
private void ConfigureThreadPoolAndServicePointSettings()
{
#if !NETSTANDARD_TODO
if (LocalConfig.MinDotNetThreadPoolSize > 0)
{
int workerThreads;
int completionPortThreads;
ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
if (LocalConfig.MinDotNetThreadPoolSize > workerThreads ||
LocalConfig.MinDotNetThreadPoolSize > completionPortThreads)
{
// if at least one of the new values is larger, set the new min values to be the larger of the prev. and new config value.
int newWorkerThreads = Math.Max(LocalConfig.MinDotNetThreadPoolSize, workerThreads);
int newCompletionPortThreads = Math.Max(LocalConfig.MinDotNetThreadPoolSize, completionPortThreads);
bool ok = ThreadPool.SetMinThreads(newWorkerThreads, newCompletionPortThreads);
if (ok)
{
logger.Info(ErrorCode.SiloConfiguredThreadPool,
"Configured ThreadPool.SetMinThreads() to values: {0},{1}. Previous values are: {2},{3}.",
newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads);
}
else
{
logger.Warn(ErrorCode.SiloFailedToConfigureThreadPool,
"Failed to configure ThreadPool.SetMinThreads(). Tried to set values to: {0},{1}. Previous values are: {2},{3}.",
newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads);
}
}
}
// Set .NET ServicePointManager settings to optimize throughput performance when using Azure storage
// http://blogs.msdn.com/b/windowsazurestorage/archive/2010/06/25/nagle-s-algorithm-is-not-friendly-towards-small-requests.aspx
logger.Info(ErrorCode.SiloConfiguredServicePointManager,
"Configured .NET ServicePointManager to Expect100Continue={0}, DefaultConnectionLimit={1}, UseNagleAlgorithm={2} to improve Azure storage performance.",
LocalConfig.Expect100Continue, LocalConfig.DefaultConnectionLimit, LocalConfig.UseNagleAlgorithm);
ServicePointManager.Expect100Continue = LocalConfig.Expect100Continue;
ServicePointManager.DefaultConnectionLimit = LocalConfig.DefaultConnectionLimit;
ServicePointManager.UseNagleAlgorithm = LocalConfig.UseNagleAlgorithm;
#endif
}
/// <summary>
/// Gracefully stop the run time system only, but not the application.
/// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible.
/// Grains are not deactivated.
/// </summary>
public void Stop()
{
Terminate(false);
}
/// <summary>
/// Gracefully stop the run time system and the application.
/// All grains will be properly deactivated.
/// All in-flight applications requests would be awaited and finished gracefully.
/// </summary>
public void Shutdown()
{
Terminate(true);
}
/// <summary>
/// Gracefully stop the run time system only, but not the application.
/// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible.
/// </summary>
private void Terminate(bool gracefully)
{
string operation = gracefully ? "Shutdown()" : "Stop()";
bool stopAlreadyInProgress = false;
lock (lockable)
{
if (this.SystemStatus.Equals(SystemStatus.Stopping) ||
this.SystemStatus.Equals(SystemStatus.ShuttingDown) ||
this.SystemStatus.Equals(SystemStatus.Terminated))
{
stopAlreadyInProgress = true;
// Drop through to wait below
}
else if (!this.SystemStatus.Equals(SystemStatus.Running))
{
throw new InvalidOperationException(String.Format("Calling Silo.{0} on a silo which is not in the Running state. This silo is in the {1} state.", operation, this.SystemStatus));
}
else
{
if (gracefully)
this.SystemStatus = SystemStatus.ShuttingDown;
else
this.SystemStatus = SystemStatus.Stopping;
}
}
if (stopAlreadyInProgress)
{
logger.Info(ErrorCode.SiloStopInProgress, "Silo termination is in progress - Will wait for it to finish");
var pause = TimeSpan.FromSeconds(1);
while (!this.SystemStatus.Equals(SystemStatus.Terminated))
{
logger.Info(ErrorCode.WaitingForSiloStop, "Waiting {0} for termination to complete", pause);
Thread.Sleep(pause);
}
return;
}
try
{
try
{
if (gracefully)
{
logger.Info(ErrorCode.SiloShuttingDown, "Silo starting to Shutdown()");
// 1: Write "ShutDown" state in the table + broadcast gossip msgs to re-read the table to everyone
scheduler.QueueTask(this.membershipOracle.ShutDown, (this.membershipOracle as SystemTarget)?.SchedulingContext)
.WaitWithThrow(stopTimeout);
}
else
{
logger.Info(ErrorCode.SiloStopping, "Silo starting to Stop()");
// 1: Write "Stopping" state in the table + broadcast gossip msgs to re-read the table to everyone
scheduler.QueueTask(this.membershipOracle.Stop, (this.membershipOracle as SystemTarget)?.SchedulingContext)
.WaitWithThrow(stopTimeout);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.SiloFailedToStopMembership, String.Format("Failed to {0} membership oracle. About to FastKill this silo.", operation), exc);
return; // will go to finally
}
if (reminderService != null)
{
// 2: Stop reminder service
scheduler.QueueTask(reminderService.Stop, (reminderService as SystemTarget)?.SchedulingContext)
.WaitWithThrow(stopTimeout);
}
if (gracefully)
{
// 3: Deactivate all grains
SafeExecute(() => catalog.DeactivateAllActivations().WaitWithThrow(stopTimeout));
}
// 3: Stop the gateway
SafeExecute(messageCenter.StopAcceptingClientMessages);
// 4: Start rejecting all silo to silo application messages
SafeExecute(messageCenter.BlockApplicationMessages);
// 5: Stop scheduling/executing application turns
SafeExecute(scheduler.StopApplicationTurns);
// 6: Directory: Speed up directory handoff
// will be started automatically when directory receives SiloStatusChangeNotification(Stopping)
// 7:
SafeExecute(() => LocalGrainDirectory.StopPreparationCompletion.WaitWithThrow(stopTimeout));
// The order of closing providers might be importan: Stats, streams, boostrap, storage.
// Stats first since no one depends on it.
// Storage should definitely be last since other providers ma ybe using it, potentilay indirectly.
// Streams and Bootstrap - the order is less clear. Seems like Bootstrap may indirecly depend on Streams, but not the other way around.
// 8:
SafeExecute(() =>
{
scheduler.QueueTask(() => statisticsProviderManager.CloseProviders(), providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
});
// 9:
SafeExecute(() =>
{
var siloStreamProviderManager = (StreamProviderManager)grainRuntime.StreamProviderManager;
scheduler.QueueTask(() => siloStreamProviderManager.CloseProviders(), providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
});
// 10:
SafeExecute(() =>
{
scheduler.QueueTask(() => bootstrapProviderManager.CloseProviders(), providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
});
// 11:
SafeExecute(() =>
{
scheduler.QueueTask(() => storageProviderManager.CloseProviders(), providerManagerSystemTarget.SchedulingContext)
.WaitWithThrow(initTimeout);
});
}
finally
{
// 10, 11, 12: Write Dead in the table, Drain scheduler, Stop msg center, ...
logger.Info(ErrorCode.SiloStopped, "Silo is Stopped()");
FastKill();
}
}
/// <summary>
/// Ungracefully stop the run time system and the application running on it.
/// Applications requests would be abruptly terminated, and the internal system state quickly stopped with minimal cleanup.
/// </summary>
private void FastKill()
{
if (!GlobalConfig.LivenessType.Equals(GlobalConfiguration.LivenessProviderType.MembershipTableGrain))
{
// do not execute KillMyself if using MembershipTableGrain, since it will fail, as we've already stopped app scheduler turns.
SafeExecute(() => scheduler.QueueTask( this.membershipOracle.KillMyself, (this.membershipOracle as SystemTarget)?.SchedulingContext)
.WaitWithThrow(stopTimeout));
}
// incoming messages
SafeExecute(incomingSystemAgent.Stop);
SafeExecute(incomingPingAgent.Stop);
SafeExecute(incomingAgent.Stop);
// timers
SafeExecute(runtimeClient.Stop);
if (platformWatchdog != null)
SafeExecute(platformWatchdog.Stop); // Silo may be dying before platformWatchdog was set up
SafeExecute(scheduler.Stop);
SafeExecute(scheduler.PrintStatistics);
SafeExecute(activationDirectory.PrintActivationDirectory);
SafeExecute(messageCenter.Stop);
SafeExecute(siloStatistics.Stop);
UnobservedExceptionsHandlerClass.ResetUnobservedExceptionHandler();
SafeExecute(() => this.SystemStatus = SystemStatus.Terminated);
SafeExecute(() => AppDomain.CurrentDomain.UnhandledException -= this.DomainUnobservedExceptionHandler);
SafeExecute(() => this.assemblyProcessor?.Dispose());
SafeExecute(() => (this.Services as IDisposable)?.Dispose());
SafeExecute(LogManager.Close);
// Setting the event should be the last thing we do.
// Do nothijng after that!
siloTerminatedEvent.Set();
}
private void SafeExecute(Action action)
{
Utils.SafeExecute(action, logger, "Silo.Stop");
}
private void HandleProcessExit(object sender, EventArgs e)
{
// NOTE: We need to minimize the amount of processing occurring on this code path -- we only have under approx 2-3 seconds before process exit will occur
logger.Warn(ErrorCode.Runtime_Error_100220, "Process is exiting");
LogManager.Flush();
try
{
lock (lockable)
{
if (!this.SystemStatus.Equals(SystemStatus.Running)) return;
this.SystemStatus = SystemStatus.Stopping;
}
logger.Info(ErrorCode.SiloStopping, "Silo.HandleProcessExit() - starting to FastKill()");
FastKill();
}
finally
{
LogManager.Close();
}
}
private void UnobservedExceptionHandler(ISchedulingContext context, Exception exception)
{
var schedulingContext = context as SchedulingContext;
if (schedulingContext == null)
{
if (context == null)
logger.Error(ErrorCode.Runtime_Error_100102, "Silo caught an UnobservedException with context==null.", exception);
else
logger.Error(ErrorCode.Runtime_Error_100103, String.Format("Silo caught an UnobservedException with context of type different than OrleansContext. The type of the context is {0}. The context is {1}",
context.GetType(), context), exception);
}
else
{
logger.Error(ErrorCode.Runtime_Error_100104, String.Format("Silo caught an UnobservedException thrown by {0}.", schedulingContext.Activation), exception);
}
}
private void DomainUnobservedExceptionHandler(object context, UnhandledExceptionEventArgs args)
{
var exception = (Exception)args.ExceptionObject;
if (context is ISchedulingContext)
UnobservedExceptionHandler(context as ISchedulingContext, exception);
else
logger.Error(ErrorCode.Runtime_Error_100324, String.Format("Called DomainUnobservedExceptionHandler with context {0}.", context), exception);
}
internal void RegisterSystemTarget(SystemTarget target)
{
var providerRuntime = this.Services.GetRequiredService<SiloProviderRuntime>();
providerRuntime.RegisterSystemTarget(target);
}
/// <summary> Return dump of diagnostic data from this silo. </summary>
/// <param name="all"></param>
/// <returns>Debug data for this silo.</returns>
public string GetDebugDump(bool all = true)
{
var sb = new StringBuilder();
foreach (var systemTarget in activationDirectory.AllSystemTargets())
sb.AppendFormat("System target {0}:", ((ISystemTargetBase)systemTarget).GrainId.ToString()).AppendLine();
var enumerator = activationDirectory.GetEnumerator();
while(enumerator.MoveNext())
{
Utils.SafeExecute(() =>
{
var activationData = enumerator.Current.Value;
var workItemGroup = scheduler.GetWorkItemGroup(activationData.SchedulingContext);
if (workItemGroup == null)
{
sb.AppendFormat("Activation with no work item group!! Grain {0}, activation {1}.",
activationData.Grain,
activationData.ActivationId);
sb.AppendLine();
return;
}
if (all || activationData.State.Equals(ActivationState.Valid))
{
sb.AppendLine(workItemGroup.DumpStatus());
sb.AppendLine(activationData.DumpStatus());
}
});
}
logger.Info(ErrorCode.SiloDebugDump, sb.ToString());
return sb.ToString();
}
/// <summary> Object.ToString override -- summary info for this silo. </summary>
public override string ToString()
{
return localGrainDirectory.ToString();
}
}
// A dummy system target to use for scheduling context for provider Init calls, to allow them to make grain calls
internal class ProviderManagerSystemTarget : SystemTarget
{
public ProviderManagerSystemTarget(Silo currentSilo)
: base(Constants.ProviderManagerSystemTargetId, currentSilo.SiloAddress)
{
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Framework.Input.StateChanges;
using osu.Framework.Logging;
using osu.Framework.Testing;
using osu.Framework.Timing;
using osu.Game.Beatmaps;
using osu.Game.Graphics.Sprites;
using osu.Game.Online.Spectator;
using osu.Game.Replays;
using osu.Game.Replays.Legacy;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Replays;
using osu.Game.Rulesets.Replays.Types;
using osu.Game.Rulesets.UI;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
using osu.Game.Tests.Visual.Spectator;
using osu.Game.Tests.Visual.UserInterface;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneSpectatorPlayback : OsuManualInputManagerTestScene
{
private TestRulesetInputManager playbackManager;
private TestRulesetInputManager recordingManager;
private Replay replay;
private TestSpectatorClient spectatorClient;
private ManualClock manualClock;
private TestReplayRecorder recorder;
private OsuSpriteText latencyDisplay;
private TestFramedReplayInputHandler replayHandler;
[SetUpSteps]
public void SetUpSteps()
{
AddStep("Setup containers", () =>
{
replay = new Replay();
manualClock = new ManualClock();
Child = new DependencyProvidingContainer
{
RelativeSizeAxes = Axes.Both,
CachedDependencies = new[]
{
(typeof(SpectatorClient), (object)(spectatorClient = new TestSpectatorClient())),
(typeof(GameplayState), new GameplayState(new Beatmap(), new OsuRuleset(), Array.Empty<Mod>()))
},
Children = new Drawable[]
{
spectatorClient,
new GridContainer
{
RelativeSizeAxes = Axes.Both,
Content = new[]
{
new Drawable[]
{
recordingManager = new TestRulesetInputManager(TestSceneModSettings.CreateTestRulesetInfo(), 0, SimultaneousBindingMode.Unique)
{
Recorder = recorder = new TestReplayRecorder
{
ScreenSpaceToGamefield = pos => recordingManager.ToLocalSpace(pos),
},
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box
{
Colour = Color4.Brown,
RelativeSizeAxes = Axes.Both,
},
new OsuSpriteText
{
Text = "Sending",
Scale = new Vector2(3),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
new TestInputConsumer()
}
},
}
},
new Drawable[]
{
playbackManager = new TestRulesetInputManager(TestSceneModSettings.CreateTestRulesetInfo(), 0, SimultaneousBindingMode.Unique)
{
Clock = new FramedClock(manualClock),
ReplayInputHandler = replayHandler = new TestFramedReplayInputHandler(replay)
{
GamefieldToScreenSpace = pos => playbackManager.ToScreenSpace(pos),
},
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box
{
Colour = Color4.DarkBlue,
RelativeSizeAxes = Axes.Both,
},
new OsuSpriteText
{
Text = "Receiving",
Scale = new Vector2(3),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
new TestInputConsumer()
}
},
}
}
}
},
latencyDisplay = new OsuSpriteText()
}
};
spectatorClient.OnNewFrames += onNewFrames;
});
}
[Test]
public void TestBasic()
{
AddUntilStep("received frames", () => replay.Frames.Count > 50);
AddStep("stop sending frames", () => recorder.Expire());
AddUntilStep("wait for all frames received", () => replay.Frames.Count == recorder.SentFrames.Count);
}
[Test]
public void TestWithSendFailure()
{
AddUntilStep("received frames", () => replay.Frames.Count > 50);
int framesReceivedSoFar = 0;
int frameSendAttemptsSoFar = 0;
AddStep("start failing sends", () =>
{
spectatorClient.ShouldFailSendingFrames = true;
framesReceivedSoFar = replay.Frames.Count;
frameSendAttemptsSoFar = spectatorClient.FrameSendAttempts;
});
AddUntilStep("wait for send attempts", () => spectatorClient.FrameSendAttempts > frameSendAttemptsSoFar + 5);
AddAssert("frames did not increase", () => framesReceivedSoFar == replay.Frames.Count);
AddStep("stop failing sends", () => spectatorClient.ShouldFailSendingFrames = false);
AddUntilStep("wait for next frames", () => framesReceivedSoFar < replay.Frames.Count);
AddStep("stop sending frames", () => recorder.Expire());
AddUntilStep("wait for all frames received", () => replay.Frames.Count == recorder.SentFrames.Count);
AddAssert("ensure frames were received in the correct sequence", () => replay.Frames.Select(f => f.Time).SequenceEqual(recorder.SentFrames.Select(f => f.Time)));
}
private void onNewFrames(int userId, FrameDataBundle frames)
{
foreach (var legacyFrame in frames.Frames)
{
var frame = new TestReplayFrame();
frame.FromLegacy(legacyFrame, null);
replay.Frames.Add(frame);
}
Logger.Log($"Received {frames.Frames.Count} new frames (total {replay.Frames.Count} of {recorder.SentFrames.Count})");
}
private double latency = SpectatorClient.TIME_BETWEEN_SENDS;
protected override void Update()
{
base.Update();
if (latencyDisplay == null) return;
// propagate initial time value
if (manualClock.CurrentTime == 0)
{
manualClock.CurrentTime = Time.Current;
return;
}
if (!replayHandler.HasFrames)
return;
var lastFrame = replay.Frames.LastOrDefault();
// this isn't perfect as we basically can't be aware of the rate-of-send here (the streamer is not sending data when not being moved).
// in gameplay playback, the case where NextFrame is null would pause gameplay and handle this correctly; it's strictly a test limitation / best effort implementation.
if (lastFrame != null)
latency = Math.Max(latency, Time.Current - lastFrame.Time);
latencyDisplay.Text = $"latency: {latency:N1}";
double proposedTime = Time.Current - latency + Time.Elapsed;
// this will either advance by one or zero frames.
double? time = replayHandler.SetFrameFromTime(proposedTime);
if (time == null)
return;
manualClock.CurrentTime = time.Value;
}
public class TestFramedReplayInputHandler : FramedReplayInputHandler<TestReplayFrame>
{
public TestFramedReplayInputHandler(Replay replay)
: base(replay)
{
}
protected override void CollectReplayInputs(List<IInput> inputs)
{
inputs.Add(new MousePositionAbsoluteInput { Position = GamefieldToScreenSpace(CurrentFrame?.Position ?? Vector2.Zero) });
inputs.Add(new ReplayState<TestAction> { PressedActions = CurrentFrame?.Actions ?? new List<TestAction>() });
}
}
public class TestInputConsumer : CompositeDrawable, IKeyBindingHandler<TestAction>
{
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => Parent.ReceivePositionalInputAt(screenSpacePos);
private readonly Box box;
public TestInputConsumer()
{
Size = new Vector2(30);
Origin = Anchor.Centre;
InternalChildren = new Drawable[]
{
box = new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both,
},
};
}
protected override bool OnMouseMove(MouseMoveEvent e)
{
Position = e.MousePosition;
return base.OnMouseMove(e);
}
public bool OnPressed(KeyBindingPressEvent<TestAction> e)
{
if (e.Repeat)
return false;
box.Colour = Color4.White;
return true;
}
public void OnReleased(KeyBindingReleaseEvent<TestAction> e)
{
box.Colour = Color4.Black;
}
}
public class TestRulesetInputManager : RulesetInputManager<TestAction>
{
public TestRulesetInputManager(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique)
: base(ruleset, variant, unique)
{
}
protected override KeyBindingContainer<TestAction> CreateKeyBindingContainer(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique)
=> new TestKeyBindingContainer();
internal class TestKeyBindingContainer : KeyBindingContainer<TestAction>
{
public override IEnumerable<IKeyBinding> DefaultKeyBindings => new[]
{
new KeyBinding(InputKey.MouseLeft, TestAction.Down),
};
}
}
public class TestReplayFrame : ReplayFrame, IConvertibleReplayFrame
{
public Vector2 Position;
public List<TestAction> Actions = new List<TestAction>();
public TestReplayFrame(double time, Vector2 position, params TestAction[] actions)
: base(time)
{
Position = position;
Actions.AddRange(actions);
}
public TestReplayFrame()
{
}
public void FromLegacy(LegacyReplayFrame currentFrame, IBeatmap beatmap, ReplayFrame lastFrame = null)
{
Position = currentFrame.Position;
Time = currentFrame.Time;
if (currentFrame.MouseLeft)
Actions.Add(TestAction.Down);
}
public LegacyReplayFrame ToLegacy(IBeatmap beatmap)
{
ReplayButtonState state = ReplayButtonState.None;
if (Actions.Contains(TestAction.Down))
state |= ReplayButtonState.Left1;
return new LegacyReplayFrame(Time, Position.X, Position.Y, state);
}
}
public enum TestAction
{
Down,
}
internal class TestReplayRecorder : ReplayRecorder<TestAction>
{
public List<ReplayFrame> SentFrames = new List<ReplayFrame>();
public TestReplayRecorder()
: base(new Score
{
ScoreInfo =
{
BeatmapInfo = new BeatmapInfo(),
Ruleset = new OsuRuleset().RulesetInfo,
}
})
{
}
protected override ReplayFrame HandleFrame(Vector2 mousePosition, List<TestAction> actions, ReplayFrame previousFrame)
{
var testReplayFrame = new TestReplayFrame(Time.Current, mousePosition, actions.ToArray());
SentFrames.Add(testReplayFrame);
return testReplayFrame;
}
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Cluster.Codecs {
public class ClusterMembersExtendedResponseDecoder
{
public const ushort BLOCK_LENGTH = 24;
public const ushort TEMPLATE_ID = 43;
public const ushort SCHEMA_ID = 111;
public const ushort SCHEMA_VERSION = 7;
private ClusterMembersExtendedResponseDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public ClusterMembersExtendedResponseDecoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public ClusterMembersExtendedResponseDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int CorrelationIdId()
{
return 1;
}
public static int CorrelationIdSinceVersion()
{
return 0;
}
public static int CorrelationIdEncodingOffset()
{
return 0;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public long CorrelationId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int CurrentTimeNsId()
{
return 2;
}
public static int CurrentTimeNsSinceVersion()
{
return 0;
}
public static int CurrentTimeNsEncodingOffset()
{
return 8;
}
public static int CurrentTimeNsEncodingLength()
{
return 8;
}
public static string CurrentTimeNsMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long CurrentTimeNsNullValue()
{
return -9223372036854775808L;
}
public static long CurrentTimeNsMinValue()
{
return -9223372036854775807L;
}
public static long CurrentTimeNsMaxValue()
{
return 9223372036854775807L;
}
public long CurrentTimeNs()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int LeaderMemberIdId()
{
return 3;
}
public static int LeaderMemberIdSinceVersion()
{
return 0;
}
public static int LeaderMemberIdEncodingOffset()
{
return 16;
}
public static int LeaderMemberIdEncodingLength()
{
return 4;
}
public static string LeaderMemberIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int LeaderMemberIdNullValue()
{
return -2147483648;
}
public static int LeaderMemberIdMinValue()
{
return -2147483647;
}
public static int LeaderMemberIdMaxValue()
{
return 2147483647;
}
public int LeaderMemberId()
{
return _buffer.GetInt(_offset + 16, ByteOrder.LittleEndian);
}
public static int MemberIdId()
{
return 4;
}
public static int MemberIdSinceVersion()
{
return 0;
}
public static int MemberIdEncodingOffset()
{
return 20;
}
public static int MemberIdEncodingLength()
{
return 4;
}
public static string MemberIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int MemberIdNullValue()
{
return -2147483648;
}
public static int MemberIdMinValue()
{
return -2147483647;
}
public static int MemberIdMaxValue()
{
return 2147483647;
}
public int MemberId()
{
return _buffer.GetInt(_offset + 20, ByteOrder.LittleEndian);
}
private ActiveMembersDecoder _ActiveMembers = new ActiveMembersDecoder();
public static long ActiveMembersDecoderId()
{
return 5;
}
public static int ActiveMembersDecoderSinceVersion()
{
return 0;
}
public ActiveMembersDecoder ActiveMembers()
{
_ActiveMembers.Wrap(_parentMessage, _buffer);
return _ActiveMembers;
}
public class ActiveMembersDecoder
{
private static int HEADER_SIZE = 4;
private GroupSizeEncodingDecoder _dimensions = new GroupSizeEncodingDecoder();
private ClusterMembersExtendedResponseDecoder _parentMessage;
private IDirectBuffer _buffer;
private int _count;
private int _index;
private int _offset;
private int _blockLength;
public void Wrap(
ClusterMembersExtendedResponseDecoder parentMessage, IDirectBuffer buffer)
{
this._parentMessage = parentMessage;
this._buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit());
_blockLength = _dimensions.BlockLength();
_count = _dimensions.NumInGroup();
_index = -1;
parentMessage.Limit(parentMessage.Limit() + HEADER_SIZE);
}
public static int SbeHeaderSize()
{
return HEADER_SIZE;
}
public static int SbeBlockLength()
{
return 28;
}
public int ActingBlockLength()
{
return _blockLength;
}
public int Count()
{
return _count;
}
public bool HasNext()
{
return (_index + 1) < _count;
}
public ActiveMembersDecoder Next()
{
if (_index + 1 >= _count)
{
throw new IndexOutOfRangeException();
}
_offset = _parentMessage.Limit();
_parentMessage.Limit(_offset + _blockLength);
++_index;
return this;
}
public static int LeadershipTermIdId()
{
return 6;
}
public static int LeadershipTermIdSinceVersion()
{
return 0;
}
public static int LeadershipTermIdEncodingOffset()
{
return 0;
}
public static int LeadershipTermIdEncodingLength()
{
return 8;
}
public static string LeadershipTermIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long LeadershipTermIdNullValue()
{
return -9223372036854775808L;
}
public static long LeadershipTermIdMinValue()
{
return -9223372036854775807L;
}
public static long LeadershipTermIdMaxValue()
{
return 9223372036854775807L;
}
public long LeadershipTermId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int LogPositionId()
{
return 7;
}
public static int LogPositionSinceVersion()
{
return 0;
}
public static int LogPositionEncodingOffset()
{
return 8;
}
public static int LogPositionEncodingLength()
{
return 8;
}
public static string LogPositionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long LogPositionNullValue()
{
return -9223372036854775808L;
}
public static long LogPositionMinValue()
{
return -9223372036854775807L;
}
public static long LogPositionMaxValue()
{
return 9223372036854775807L;
}
public long LogPosition()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int TimeOfLastAppendNsId()
{
return 8;
}
public static int TimeOfLastAppendNsSinceVersion()
{
return 0;
}
public static int TimeOfLastAppendNsEncodingOffset()
{
return 16;
}
public static int TimeOfLastAppendNsEncodingLength()
{
return 8;
}
public static string TimeOfLastAppendNsMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long TimeOfLastAppendNsNullValue()
{
return -9223372036854775808L;
}
public static long TimeOfLastAppendNsMinValue()
{
return -9223372036854775807L;
}
public static long TimeOfLastAppendNsMaxValue()
{
return 9223372036854775807L;
}
public long TimeOfLastAppendNs()
{
return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian);
}
public static int MemberIdId()
{
return 9;
}
public static int MemberIdSinceVersion()
{
return 0;
}
public static int MemberIdEncodingOffset()
{
return 24;
}
public static int MemberIdEncodingLength()
{
return 4;
}
public static string MemberIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int MemberIdNullValue()
{
return -2147483648;
}
public static int MemberIdMinValue()
{
return -2147483647;
}
public static int MemberIdMaxValue()
{
return 2147483647;
}
public int MemberId()
{
return _buffer.GetInt(_offset + 24, ByteOrder.LittleEndian);
}
public static int IngressEndpointId()
{
return 10;
}
public static int IngressEndpointSinceVersion()
{
return 0;
}
public static string IngressEndpointCharacterEncoding()
{
return "US-ASCII";
}
public static string IngressEndpointMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int IngressEndpointHeaderLength()
{
return 4;
}
public int IngressEndpointLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetIngressEndpoint(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetIngressEndpoint(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public string IngressEndpoint()
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
_parentMessage.Limit(limit + headerLength + dataLength);
byte[] tmp = new byte[dataLength];
_buffer.GetBytes(limit + headerLength, tmp, 0, dataLength);
return Encoding.ASCII.GetString(tmp);
}
public static int ConsensusEndpointId()
{
return 11;
}
public static int ConsensusEndpointSinceVersion()
{
return 0;
}
public static string ConsensusEndpointCharacterEncoding()
{
return "US-ASCII";
}
public static string ConsensusEndpointMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int ConsensusEndpointHeaderLength()
{
return 4;
}
public int ConsensusEndpointLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetConsensusEndpoint(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetConsensusEndpoint(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public string ConsensusEndpoint()
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
_parentMessage.Limit(limit + headerLength + dataLength);
byte[] tmp = new byte[dataLength];
_buffer.GetBytes(limit + headerLength, tmp, 0, dataLength);
return Encoding.ASCII.GetString(tmp);
}
public static int LogEndpointId()
{
return 12;
}
public static int LogEndpointSinceVersion()
{
return 0;
}
public static string LogEndpointCharacterEncoding()
{
return "US-ASCII";
}
public static string LogEndpointMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int LogEndpointHeaderLength()
{
return 4;
}
public int LogEndpointLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetLogEndpoint(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetLogEndpoint(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public string LogEndpoint()
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
_parentMessage.Limit(limit + headerLength + dataLength);
byte[] tmp = new byte[dataLength];
_buffer.GetBytes(limit + headerLength, tmp, 0, dataLength);
return Encoding.ASCII.GetString(tmp);
}
public static int CatchupEndpointId()
{
return 13;
}
public static int CatchupEndpointSinceVersion()
{
return 0;
}
public static string CatchupEndpointCharacterEncoding()
{
return "US-ASCII";
}
public static string CatchupEndpointMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int CatchupEndpointHeaderLength()
{
return 4;
}
public int CatchupEndpointLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetCatchupEndpoint(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetCatchupEndpoint(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public string CatchupEndpoint()
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
_parentMessage.Limit(limit + headerLength + dataLength);
byte[] tmp = new byte[dataLength];
_buffer.GetBytes(limit + headerLength, tmp, 0, dataLength);
return Encoding.ASCII.GetString(tmp);
}
public static int ArchiveEndpointId()
{
return 14;
}
public static int ArchiveEndpointSinceVersion()
{
return 0;
}
public static string ArchiveEndpointCharacterEncoding()
{
return "US-ASCII";
}
public static string ArchiveEndpointMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int ArchiveEndpointHeaderLength()
{
return 4;
}
public int ArchiveEndpointLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetArchiveEndpoint(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetArchiveEndpoint(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public string ArchiveEndpoint()
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
_parentMessage.Limit(limit + headerLength + dataLength);
byte[] tmp = new byte[dataLength];
_buffer.GetBytes(limit + headerLength, tmp, 0, dataLength);
return Encoding.ASCII.GetString(tmp);
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
builder.Append('(');
//Token{signal=BEGIN_FIELD, name='leadershipTermId', referencedName='null', description='null', id=6, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("LeadershipTermId=");
builder.Append(LeadershipTermId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='logPosition', referencedName='null', description='null', id=7, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("LogPosition=");
builder.Append(LogPosition());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='timeOfLastAppendNs', referencedName='null', description='null', id=8, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='time_t', referencedName='null', description='Epoch time since 1 Jan 1970 UTC.', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("TimeOfLastAppendNs=");
builder.Append(TimeOfLastAppendNs());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='memberId', referencedName='null', description='null', id=9, version=0, deprecated=0, encodedLength=0, offset=24, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=24, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("MemberId=");
builder.Append(MemberId());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='ingressEndpoint', referencedName='null', description='null', id=10, version=0, deprecated=0, encodedLength=0, offset=28, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("IngressEndpoint=");
builder.Append(IngressEndpoint());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='consensusEndpoint', referencedName='null', description='null', id=11, version=0, deprecated=0, encodedLength=0, offset=-1, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ConsensusEndpoint=");
builder.Append(ConsensusEndpoint());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='logEndpoint', referencedName='null', description='null', id=12, version=0, deprecated=0, encodedLength=0, offset=-1, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("LogEndpoint=");
builder.Append(LogEndpoint());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='catchupEndpoint', referencedName='null', description='null', id=13, version=0, deprecated=0, encodedLength=0, offset=-1, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CatchupEndpoint=");
builder.Append(CatchupEndpoint());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='archiveEndpoint', referencedName='null', description='null', id=14, version=0, deprecated=0, encodedLength=0, offset=-1, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ArchiveEndpoint=");
builder.Append(ArchiveEndpoint());
builder.Append(')');
return builder;
}
}
private PassiveMembersDecoder _PassiveMembers = new PassiveMembersDecoder();
public static long PassiveMembersDecoderId()
{
return 15;
}
public static int PassiveMembersDecoderSinceVersion()
{
return 0;
}
public PassiveMembersDecoder PassiveMembers()
{
_PassiveMembers.Wrap(_parentMessage, _buffer);
return _PassiveMembers;
}
public class PassiveMembersDecoder
{
private static int HEADER_SIZE = 4;
private GroupSizeEncodingDecoder _dimensions = new GroupSizeEncodingDecoder();
private ClusterMembersExtendedResponseDecoder _parentMessage;
private IDirectBuffer _buffer;
private int _count;
private int _index;
private int _offset;
private int _blockLength;
public void Wrap(
ClusterMembersExtendedResponseDecoder parentMessage, IDirectBuffer buffer)
{
this._parentMessage = parentMessage;
this._buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit());
_blockLength = _dimensions.BlockLength();
_count = _dimensions.NumInGroup();
_index = -1;
parentMessage.Limit(parentMessage.Limit() + HEADER_SIZE);
}
public static int SbeHeaderSize()
{
return HEADER_SIZE;
}
public static int SbeBlockLength()
{
return 28;
}
public int ActingBlockLength()
{
return _blockLength;
}
public int Count()
{
return _count;
}
public bool HasNext()
{
return (_index + 1) < _count;
}
public PassiveMembersDecoder Next()
{
if (_index + 1 >= _count)
{
throw new IndexOutOfRangeException();
}
_offset = _parentMessage.Limit();
_parentMessage.Limit(_offset + _blockLength);
++_index;
return this;
}
public static int LeadershipTermIdId()
{
return 16;
}
public static int LeadershipTermIdSinceVersion()
{
return 0;
}
public static int LeadershipTermIdEncodingOffset()
{
return 0;
}
public static int LeadershipTermIdEncodingLength()
{
return 8;
}
public static string LeadershipTermIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long LeadershipTermIdNullValue()
{
return -9223372036854775808L;
}
public static long LeadershipTermIdMinValue()
{
return -9223372036854775807L;
}
public static long LeadershipTermIdMaxValue()
{
return 9223372036854775807L;
}
public long LeadershipTermId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int LogPositionId()
{
return 17;
}
public static int LogPositionSinceVersion()
{
return 0;
}
public static int LogPositionEncodingOffset()
{
return 8;
}
public static int LogPositionEncodingLength()
{
return 8;
}
public static string LogPositionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long LogPositionNullValue()
{
return -9223372036854775808L;
}
public static long LogPositionMinValue()
{
return -9223372036854775807L;
}
public static long LogPositionMaxValue()
{
return 9223372036854775807L;
}
public long LogPosition()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int TimeOfLastAppendNsId()
{
return 18;
}
public static int TimeOfLastAppendNsSinceVersion()
{
return 0;
}
public static int TimeOfLastAppendNsEncodingOffset()
{
return 16;
}
public static int TimeOfLastAppendNsEncodingLength()
{
return 8;
}
public static string TimeOfLastAppendNsMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long TimeOfLastAppendNsNullValue()
{
return -9223372036854775808L;
}
public static long TimeOfLastAppendNsMinValue()
{
return -9223372036854775807L;
}
public static long TimeOfLastAppendNsMaxValue()
{
return 9223372036854775807L;
}
public long TimeOfLastAppendNs()
{
return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian);
}
public static int MemberIdId()
{
return 19;
}
public static int MemberIdSinceVersion()
{
return 0;
}
public static int MemberIdEncodingOffset()
{
return 24;
}
public static int MemberIdEncodingLength()
{
return 4;
}
public static string MemberIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int MemberIdNullValue()
{
return -2147483648;
}
public static int MemberIdMinValue()
{
return -2147483647;
}
public static int MemberIdMaxValue()
{
return 2147483647;
}
public int MemberId()
{
return _buffer.GetInt(_offset + 24, ByteOrder.LittleEndian);
}
public static int IngressEndpointId()
{
return 20;
}
public static int IngressEndpointSinceVersion()
{
return 0;
}
public static string IngressEndpointCharacterEncoding()
{
return "US-ASCII";
}
public static string IngressEndpointMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int IngressEndpointHeaderLength()
{
return 4;
}
public int IngressEndpointLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetIngressEndpoint(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetIngressEndpoint(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public string IngressEndpoint()
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
_parentMessage.Limit(limit + headerLength + dataLength);
byte[] tmp = new byte[dataLength];
_buffer.GetBytes(limit + headerLength, tmp, 0, dataLength);
return Encoding.ASCII.GetString(tmp);
}
public static int ConsensusEndpointId()
{
return 21;
}
public static int ConsensusEndpointSinceVersion()
{
return 0;
}
public static string ConsensusEndpointCharacterEncoding()
{
return "US-ASCII";
}
public static string ConsensusEndpointMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int ConsensusEndpointHeaderLength()
{
return 4;
}
public int ConsensusEndpointLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetConsensusEndpoint(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetConsensusEndpoint(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public string ConsensusEndpoint()
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
_parentMessage.Limit(limit + headerLength + dataLength);
byte[] tmp = new byte[dataLength];
_buffer.GetBytes(limit + headerLength, tmp, 0, dataLength);
return Encoding.ASCII.GetString(tmp);
}
public static int LogEndpointId()
{
return 22;
}
public static int LogEndpointSinceVersion()
{
return 0;
}
public static string LogEndpointCharacterEncoding()
{
return "US-ASCII";
}
public static string LogEndpointMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int LogEndpointHeaderLength()
{
return 4;
}
public int LogEndpointLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetLogEndpoint(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetLogEndpoint(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public string LogEndpoint()
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
_parentMessage.Limit(limit + headerLength + dataLength);
byte[] tmp = new byte[dataLength];
_buffer.GetBytes(limit + headerLength, tmp, 0, dataLength);
return Encoding.ASCII.GetString(tmp);
}
public static int CatchupEndpointId()
{
return 23;
}
public static int CatchupEndpointSinceVersion()
{
return 0;
}
public static string CatchupEndpointCharacterEncoding()
{
return "US-ASCII";
}
public static string CatchupEndpointMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int CatchupEndpointHeaderLength()
{
return 4;
}
public int CatchupEndpointLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetCatchupEndpoint(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetCatchupEndpoint(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public string CatchupEndpoint()
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
_parentMessage.Limit(limit + headerLength + dataLength);
byte[] tmp = new byte[dataLength];
_buffer.GetBytes(limit + headerLength, tmp, 0, dataLength);
return Encoding.ASCII.GetString(tmp);
}
public static int ArchiveEndpointId()
{
return 24;
}
public static int ArchiveEndpointSinceVersion()
{
return 0;
}
public static string ArchiveEndpointCharacterEncoding()
{
return "US-ASCII";
}
public static string ArchiveEndpointMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int ArchiveEndpointHeaderLength()
{
return 4;
}
public int ArchiveEndpointLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetArchiveEndpoint(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetArchiveEndpoint(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public string ArchiveEndpoint()
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
_parentMessage.Limit(limit + headerLength + dataLength);
byte[] tmp = new byte[dataLength];
_buffer.GetBytes(limit + headerLength, tmp, 0, dataLength);
return Encoding.ASCII.GetString(tmp);
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
builder.Append('(');
//Token{signal=BEGIN_FIELD, name='leadershipTermId', referencedName='null', description='null', id=16, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("LeadershipTermId=");
builder.Append(LeadershipTermId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='logPosition', referencedName='null', description='null', id=17, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("LogPosition=");
builder.Append(LogPosition());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='timeOfLastAppendNs', referencedName='null', description='null', id=18, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='time_t', referencedName='null', description='Epoch time since 1 Jan 1970 UTC.', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("TimeOfLastAppendNs=");
builder.Append(TimeOfLastAppendNs());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='memberId', referencedName='null', description='null', id=19, version=0, deprecated=0, encodedLength=0, offset=24, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=24, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("MemberId=");
builder.Append(MemberId());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='ingressEndpoint', referencedName='null', description='null', id=20, version=0, deprecated=0, encodedLength=0, offset=28, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("IngressEndpoint=");
builder.Append(IngressEndpoint());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='consensusEndpoint', referencedName='null', description='null', id=21, version=0, deprecated=0, encodedLength=0, offset=-1, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ConsensusEndpoint=");
builder.Append(ConsensusEndpoint());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='logEndpoint', referencedName='null', description='null', id=22, version=0, deprecated=0, encodedLength=0, offset=-1, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("LogEndpoint=");
builder.Append(LogEndpoint());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='catchupEndpoint', referencedName='null', description='null', id=23, version=0, deprecated=0, encodedLength=0, offset=-1, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CatchupEndpoint=");
builder.Append(CatchupEndpoint());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='archiveEndpoint', referencedName='null', description='null', id=24, version=0, deprecated=0, encodedLength=0, offset=-1, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ArchiveEndpoint=");
builder.Append(ArchiveEndpoint());
builder.Append(')');
return builder;
}
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[ClusterMembersExtendedResponse](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CorrelationId=");
builder.Append(CorrelationId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='currentTimeNs', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='time_t', referencedName='null', description='Epoch time since 1 Jan 1970 UTC.', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CurrentTimeNs=");
builder.Append(CurrentTimeNs());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='leaderMemberId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("LeaderMemberId=");
builder.Append(LeaderMemberId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='memberId', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=20, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=20, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("MemberId=");
builder.Append(MemberId());
builder.Append('|');
//Token{signal=BEGIN_GROUP, name='activeMembers', referencedName='null', description='Members of the cluster which have voting rights.', id=5, version=0, deprecated=0, encodedLength=28, offset=24, componentTokenCount=48, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='null', timeUnit=null, semanticType='null'}}
builder.Append("ActiveMembers=[");
ActiveMembersDecoder ActiveMembers = this.ActiveMembers();
if (ActiveMembers.Count() > 0)
{
while (ActiveMembers.HasNext())
{
ActiveMembers.Next().AppendTo(builder);
builder.Append(',');
}
builder.Length = builder.Length - 1;
}
builder.Append(']');
builder.Append('|');
//Token{signal=BEGIN_GROUP, name='passiveMembers', referencedName='null', description='Members of the cluster which do not have voting rights but could become active members.', id=15, version=0, deprecated=0, encodedLength=28, offset=-1, componentTokenCount=48, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='null', timeUnit=null, semanticType='null'}}
builder.Append("PassiveMembers=[");
PassiveMembersDecoder PassiveMembers = this.PassiveMembers();
if (PassiveMembers.Count() > 0)
{
while (PassiveMembers.HasNext())
{
PassiveMembers.Next().AppendTo(builder);
builder.Append(',');
}
builder.Length = builder.Length - 1;
}
builder.Append(']');
Limit(originalLimit);
return builder;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.