context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Configuration; using System.Runtime.Serialization; namespace DDay.iCal { /// <summary> /// A class that represents an RFC 2445 VALARM component. /// FIXME: move GetOccurrences() logic into an AlarmEvaluator. /// </summary> #if !SILVERLIGHT [Serializable] #endif public class Alarm : CalendarComponent, IAlarm { #region Private Fields private List<AlarmOccurrence> m_Occurrences; #endregion #region Public Properties virtual public AlarmAction Action { get { return Properties.Get<AlarmAction>("ACTION"); } set { Properties.Set("ACTION", value); } } virtual public IAttachment Attachment { get { return Properties.Get<IAttachment>("ATTACH"); } set { Properties.Set("ATTACH", value); } } virtual public IList<IAttendee> Attendees { get { return Properties.GetMany<IAttendee>("ATTENDEE"); } set { Properties.Set("ATTENDEE", value); } } virtual public string Description { get { return Properties.Get<string>("DESCRIPTION"); } set { Properties.Set("DESCRIPTION", value); } } virtual public TimeSpan Duration { get { return Properties.Get<TimeSpan>("DURATION"); } set { Properties.Set("DURATION", value); } } virtual public int Repeat { get { return Properties.Get<int>("REPEAT"); } set { Properties.Set("REPEAT", value); } } virtual public string Summary { get { return Properties.Get<string>("SUMMARY"); } set { Properties.Set("SUMMARY", value); } } virtual public ITrigger Trigger { get { return Properties.Get<ITrigger>("TRIGGER"); } set { Properties.Set("TRIGGER", value); } } #endregion #region Protected Properties virtual protected List<AlarmOccurrence> Occurrences { get { return m_Occurrences; } set { m_Occurrences = value; } } #endregion #region Constructors public Alarm() { Initialize(); } void Initialize() { Name = Components.ALARM; Occurrences = new List<AlarmOccurrence>(); } #endregion #region Public Methods /// <summary> /// Gets a list of alarm occurrences for the given recurring component, <paramref name="rc"/> /// that occur between <paramref name="FromDate"/> and <paramref name="ToDate"/>. /// </summary> virtual public IList<AlarmOccurrence> GetOccurrences(IRecurringComponent rc, IDateTime FromDate, IDateTime ToDate) { Occurrences.Clear(); if (Trigger != null) { // If the trigger is relative, it can recur right along with // the recurring items, otherwise, it happens once and // only once (at a precise time). if (Trigger.IsRelative) { // Ensure that "FromDate" has already been set if (FromDate == null) FromDate = rc.Start.Copy<IDateTime>(); TimeSpan d = default(TimeSpan); foreach (Occurrence o in rc.GetOccurrences(FromDate, ToDate)) { IDateTime dt = o.Period.StartTime; if (Trigger.Related == TriggerRelation.End) { if (o.Period.EndTime != null) { dt = o.Period.EndTime; if (d == default(TimeSpan)) d = o.Period.Duration; } // Use the "last-found" duration as a reference point else if (d != default(TimeSpan)) dt = o.Period.StartTime.Add(d); else throw new ArgumentException("Alarm trigger is relative to the END of the occurrence; however, the occurence has no discernible end."); } Occurrences.Add(new AlarmOccurrence(this, dt.Add(Trigger.Duration.Value), rc)); } } else { IDateTime dt = Trigger.DateTime.Copy<IDateTime>(); dt.AssociatedObject = this; Occurrences.Add(new AlarmOccurrence(this, dt, rc)); } // If a REPEAT and DURATION value were specified, // then handle those repetitions here. AddRepeatedItems(); } return Occurrences; } /// <summary> /// Polls the <see cref="Alarm"/> component for alarms that have been triggered /// since the provided <paramref name="Start"/> date/time. If <paramref name="Start"/> /// is null, all triggered alarms will be returned. /// </summary> /// <param name="Start">The earliest date/time to poll trigerred alarms for.</param> /// <returns>A list of <see cref="AlarmOccurrence"/> objects, each containing a triggered alarm.</returns> virtual public IList<AlarmOccurrence> Poll(IDateTime Start, IDateTime End) { List<AlarmOccurrence> Results = new List<AlarmOccurrence>(); // Evaluate the alarms to determine the recurrences RecurringComponent rc = Parent as RecurringComponent; if (rc != null) { Results.AddRange(GetOccurrences(rc, Start, End)); Results.Sort(); } return Results; } #endregion #region Protected Methods /// <summary> /// Handles the repetitions that occur from the <c>REPEAT</c> and /// <c>DURATION</c> properties. Each recurrence of the alarm will /// have its own set of generated repetitions. /// </summary> virtual protected void AddRepeatedItems() { if (Repeat != null) { int len = Occurrences.Count; for (int i = 0; i < len; i++) { AlarmOccurrence ao = Occurrences[i]; IDateTime alarmTime = ao.DateTime.Copy<IDateTime>(); for (int j = 0; j < Repeat; j++) { alarmTime = alarmTime.Add(Duration); Occurrences.Add(new AlarmOccurrence(this, alarmTime.Copy<IDateTime>(), ao.Component)); } } } } #endregion #region Overrides protected override void OnDeserializing(StreamingContext context) { base.OnDeserializing(context); Initialize(); } #endregion } }
namespace android.widget { [global::MonoJavaBridge.JavaClass()] public partial class Gallery : android.widget.AbsSpinner, android.view.GestureDetector.OnGestureListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Gallery() { InitJNI(); } protected Gallery(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public new partial class LayoutParams : android.view.ViewGroup.LayoutParams { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static LayoutParams() { InitJNI(); } protected LayoutParams(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _LayoutParams11311; public LayoutParams(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.Gallery.LayoutParams.staticClass, global::android.widget.Gallery.LayoutParams._LayoutParams11311, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _LayoutParams11312; public LayoutParams(int arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.Gallery.LayoutParams.staticClass, global::android.widget.Gallery.LayoutParams._LayoutParams11312, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _LayoutParams11313; public LayoutParams(android.view.ViewGroup.LayoutParams arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.Gallery.LayoutParams.staticClass, global::android.widget.Gallery.LayoutParams._LayoutParams11313, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.Gallery.LayoutParams.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/Gallery$LayoutParams")); global::android.widget.Gallery.LayoutParams._LayoutParams11311 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.LayoutParams.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::android.widget.Gallery.LayoutParams._LayoutParams11312 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.LayoutParams.staticClass, "<init>", "(II)V"); global::android.widget.Gallery.LayoutParams._LayoutParams11313 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.LayoutParams.staticClass, "<init>", "(Landroid/view/ViewGroup$LayoutParams;)V"); } } internal static global::MonoJavaBridge.MethodId _onKeyDown11314; public override bool onKeyDown(int arg0, android.view.KeyEvent arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.Gallery._onKeyDown11314, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._onKeyDown11314, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _onKeyUp11315; public override bool onKeyUp(int arg0, android.view.KeyEvent arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.Gallery._onKeyUp11315, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._onKeyUp11315, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _onTouchEvent11316; public override bool onTouchEvent(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.Gallery._onTouchEvent11316, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._onTouchEvent11316, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _dispatchKeyEvent11317; public override bool dispatchKeyEvent(android.view.KeyEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.Gallery._dispatchKeyEvent11317, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._dispatchKeyEvent11317, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setGravity11318; public virtual void setGravity(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.Gallery._setGravity11318, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._setGravity11318, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _showContextMenu11319; public override bool showContextMenu() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.Gallery._showContextMenu11319); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._showContextMenu11319); } internal static global::MonoJavaBridge.MethodId _onFocusChanged11320; protected override void onFocusChanged(bool arg0, int arg1, android.graphics.Rect arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.Gallery._onFocusChanged11320, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._onFocusChanged11320, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _dispatchSetPressed11321; protected override void dispatchSetPressed(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.Gallery._dispatchSetPressed11321, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._dispatchSetPressed11321, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getContextMenuInfo11322; protected override global::android.view.ContextMenu_ContextMenuInfo getContextMenuInfo() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.ContextMenu_ContextMenuInfo>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.Gallery._getContextMenuInfo11322)) as android.view.ContextMenu_ContextMenuInfo; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.ContextMenu_ContextMenuInfo>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._getContextMenuInfo11322)) as android.view.ContextMenu_ContextMenuInfo; } internal static global::MonoJavaBridge.MethodId _computeHorizontalScrollRange11323; protected override int computeHorizontalScrollRange() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.Gallery._computeHorizontalScrollRange11323); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._computeHorizontalScrollRange11323); } internal static global::MonoJavaBridge.MethodId _computeHorizontalScrollOffset11324; protected override int computeHorizontalScrollOffset() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.Gallery._computeHorizontalScrollOffset11324); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._computeHorizontalScrollOffset11324); } internal static global::MonoJavaBridge.MethodId _computeHorizontalScrollExtent11325; protected override int computeHorizontalScrollExtent() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.Gallery._computeHorizontalScrollExtent11325); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._computeHorizontalScrollExtent11325); } internal static global::MonoJavaBridge.MethodId _onLayout11326; protected override void onLayout(bool arg0, int arg1, int arg2, int arg3, int arg4) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.Gallery._onLayout11326, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._onLayout11326, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } internal static global::MonoJavaBridge.MethodId _dispatchSetSelected11327; public override void dispatchSetSelected(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.Gallery._dispatchSetSelected11327, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._dispatchSetSelected11327, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _showContextMenuForChild11328; public override bool showContextMenuForChild(android.view.View arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.Gallery._showContextMenuForChild11328, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._showContextMenuForChild11328, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getChildDrawingOrder11329; protected override int getChildDrawingOrder(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.Gallery._getChildDrawingOrder11329, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._getChildDrawingOrder11329, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getChildStaticTransformation11330; protected override bool getChildStaticTransformation(android.view.View arg0, android.view.animation.Transformation arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.Gallery._getChildStaticTransformation11330, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._getChildStaticTransformation11330, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _checkLayoutParams11331; protected override bool checkLayoutParams(android.view.ViewGroup.LayoutParams arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.Gallery._checkLayoutParams11331, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._checkLayoutParams11331, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _generateLayoutParams11332; public override global::android.view.ViewGroup.LayoutParams generateLayoutParams(android.util.AttributeSet arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.Gallery._generateLayoutParams11332, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.ViewGroup.LayoutParams; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._generateLayoutParams11332, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.ViewGroup.LayoutParams; } internal static global::MonoJavaBridge.MethodId _generateLayoutParams11333; protected override global::android.view.ViewGroup.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.Gallery._generateLayoutParams11333, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.ViewGroup.LayoutParams; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._generateLayoutParams11333, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.ViewGroup.LayoutParams; } internal static global::MonoJavaBridge.MethodId _generateDefaultLayoutParams11334; protected override global::android.view.ViewGroup.LayoutParams generateDefaultLayoutParams() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.Gallery._generateDefaultLayoutParams11334)) as android.view.ViewGroup.LayoutParams; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._generateDefaultLayoutParams11334)) as android.view.ViewGroup.LayoutParams; } internal static global::MonoJavaBridge.MethodId _onLongPress11335; public virtual void onLongPress(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.Gallery._onLongPress11335, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._onLongPress11335, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onSingleTapUp11336; public virtual bool onSingleTapUp(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.Gallery._onSingleTapUp11336, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._onSingleTapUp11336, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onScroll11337; public virtual bool onScroll(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.Gallery._onScroll11337, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._onScroll11337, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _onFling11338; public virtual bool onFling(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.Gallery._onFling11338, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._onFling11338, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _onShowPress11339; public virtual void onShowPress(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.Gallery._onShowPress11339, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._onShowPress11339, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onDown11340; public virtual bool onDown(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.Gallery._onDown11340, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._onDown11340, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setCallbackDuringFling11341; public virtual void setCallbackDuringFling(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.Gallery._setCallbackDuringFling11341, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._setCallbackDuringFling11341, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setAnimationDuration11342; public virtual void setAnimationDuration(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.Gallery._setAnimationDuration11342, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._setAnimationDuration11342, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setSpacing11343; public virtual void setSpacing(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.Gallery._setSpacing11343, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._setSpacing11343, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setUnselectedAlpha11344; public virtual void setUnselectedAlpha(float arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.Gallery._setUnselectedAlpha11344, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.Gallery.staticClass, global::android.widget.Gallery._setUnselectedAlpha11344, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _Gallery11345; public Gallery(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.Gallery.staticClass, global::android.widget.Gallery._Gallery11345, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Gallery11346; public Gallery(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.Gallery.staticClass, global::android.widget.Gallery._Gallery11346, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Gallery11347; public Gallery(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.Gallery.staticClass, global::android.widget.Gallery._Gallery11347, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.Gallery.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/Gallery")); global::android.widget.Gallery._onKeyDown11314 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "onKeyDown", "(ILandroid/view/KeyEvent;)Z"); global::android.widget.Gallery._onKeyUp11315 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "onKeyUp", "(ILandroid/view/KeyEvent;)Z"); global::android.widget.Gallery._onTouchEvent11316 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)Z"); global::android.widget.Gallery._dispatchKeyEvent11317 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "dispatchKeyEvent", "(Landroid/view/KeyEvent;)Z"); global::android.widget.Gallery._setGravity11318 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "setGravity", "(I)V"); global::android.widget.Gallery._showContextMenu11319 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "showContextMenu", "()Z"); global::android.widget.Gallery._onFocusChanged11320 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "onFocusChanged", "(ZILandroid/graphics/Rect;)V"); global::android.widget.Gallery._dispatchSetPressed11321 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "dispatchSetPressed", "(Z)V"); global::android.widget.Gallery._getContextMenuInfo11322 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "getContextMenuInfo", "()Landroid/view/ContextMenu$ContextMenuInfo;"); global::android.widget.Gallery._computeHorizontalScrollRange11323 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "computeHorizontalScrollRange", "()I"); global::android.widget.Gallery._computeHorizontalScrollOffset11324 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "computeHorizontalScrollOffset", "()I"); global::android.widget.Gallery._computeHorizontalScrollExtent11325 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "computeHorizontalScrollExtent", "()I"); global::android.widget.Gallery._onLayout11326 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "onLayout", "(ZIIII)V"); global::android.widget.Gallery._dispatchSetSelected11327 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "dispatchSetSelected", "(Z)V"); global::android.widget.Gallery._showContextMenuForChild11328 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "showContextMenuForChild", "(Landroid/view/View;)Z"); global::android.widget.Gallery._getChildDrawingOrder11329 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "getChildDrawingOrder", "(II)I"); global::android.widget.Gallery._getChildStaticTransformation11330 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "getChildStaticTransformation", "(Landroid/view/View;Landroid/view/animation/Transformation;)Z"); global::android.widget.Gallery._checkLayoutParams11331 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "checkLayoutParams", "(Landroid/view/ViewGroup$LayoutParams;)Z"); global::android.widget.Gallery._generateLayoutParams11332 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "generateLayoutParams", "(Landroid/util/AttributeSet;)Landroid/view/ViewGroup$LayoutParams;"); global::android.widget.Gallery._generateLayoutParams11333 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "generateLayoutParams", "(Landroid/view/ViewGroup$LayoutParams;)Landroid/view/ViewGroup$LayoutParams;"); global::android.widget.Gallery._generateDefaultLayoutParams11334 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "generateDefaultLayoutParams", "()Landroid/view/ViewGroup$LayoutParams;"); global::android.widget.Gallery._onLongPress11335 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "onLongPress", "(Landroid/view/MotionEvent;)V"); global::android.widget.Gallery._onSingleTapUp11336 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "onSingleTapUp", "(Landroid/view/MotionEvent;)Z"); global::android.widget.Gallery._onScroll11337 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "onScroll", "(Landroid/view/MotionEvent;Landroid/view/MotionEvent;FF)Z"); global::android.widget.Gallery._onFling11338 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "onFling", "(Landroid/view/MotionEvent;Landroid/view/MotionEvent;FF)Z"); global::android.widget.Gallery._onShowPress11339 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "onShowPress", "(Landroid/view/MotionEvent;)V"); global::android.widget.Gallery._onDown11340 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "onDown", "(Landroid/view/MotionEvent;)Z"); global::android.widget.Gallery._setCallbackDuringFling11341 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "setCallbackDuringFling", "(Z)V"); global::android.widget.Gallery._setAnimationDuration11342 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "setAnimationDuration", "(I)V"); global::android.widget.Gallery._setSpacing11343 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "setSpacing", "(I)V"); global::android.widget.Gallery._setUnselectedAlpha11344 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "setUnselectedAlpha", "(F)V"); global::android.widget.Gallery._Gallery11345 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V"); global::android.widget.Gallery._Gallery11346 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "<init>", "(Landroid/content/Context;)V"); global::android.widget.Gallery._Gallery11347 = @__env.GetMethodIDNoThrow(global::android.widget.Gallery.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); } } }
using System; using System.Collections.Generic; using System.Drawing; using L10NSharp; namespace SIL.Windows.Forms.ClearShare { /// <summary> /// !!!!!!!!!!!!!! To keep from losing edits (having the owning metaccess not know that changes should be saved) these need to be immutable /// </summary> public abstract class LicenseInfo { public static LicenseInfo FromXmp(Dictionary<string, string> properties) { if(properties.ContainsKey("license") && properties["license"].Contains("creativecommons")) { return CreativeCommonsLicense.FromMetadata(properties); } else if ( properties.ContainsKey("rights (en)")) { return CustomLicense.FromMetadata(properties); } return new NullLicense(); } /// <summary> /// A compact form of of this license that doesn't introduce any new text (though the license may itself have text) /// E.g. CC-BY-NC /// </summary> public abstract string GetMinimalFormForCredits(IEnumerable<string> languagePriorityIds, out string idOfLanguageUsed); public abstract string GetDescription(IEnumerable<string> languagePriorityIds, out string idOfLanguageUsed); /// <summary> /// A string that is a good short indication of the license type, and can be used in FromToken. /// </summary> public abstract string Token { get; } //Review (JH asks in Oct 2016): Why does this exist? The only uses in libpalaso are in tests and examples. Bloom does not use it. // Why is From Url not sufficient? public static LicenseInfo FromToken(string abbr) { switch (abbr) { case "ask": return new NullLicense(); case "custom": return new CustomLicense(); default: return CreativeCommonsLicense.FromToken(abbr); } } virtual public Image GetImage() { return null; } /// <summary> /// It doesn't make sense to let the user edit the description of a well-known license, even if the meta data is unlocked. /// </summary> public virtual bool EditingAllowed { get { return false; }//we don't konw } public abstract string Url { get; set; } public bool HasChanges { get; set; } /// <summary> /// custom or extra rights. Note that accoring to Creative Commons, "extra" rights are expressly dissallowed by section 7 a: /// http://creativecommons.org/licenses/by-nc/4.0/legalcode#s7a /// "The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed." /// /// However, consider the case of one application that uses this library, Bloom. A significant portion of the material it is trying to /// help people license is restricted to the country of origin. Niether CC nor anyone else is going to allow for that, so we're /// allowing people to express that restriction in this field, but the UI also makes it clear that these are /// not legally enforceable if they are choosing a CC license. While not legally enforcable, they are not worthless, as they define /// what is ethical. We expect that the vast majority of people are going to abide by them. /// </summary> public string RightsStatement {get; set; } protected virtual string GetBestLicenseTranslation(string idSuffix, string englishText, string comment, IEnumerable<string> languagePriorityIds, out string idOfLanguageUsed) { idSuffix = "MetadataDisplay.Licenses."+idSuffix; foreach (var targetLanguage in languagePriorityIds) { if (targetLanguage == "en") { //do the query to make sure the string is there to be translated someday var unused = LocalizationManager.GetDynamicString("Palaso", idSuffix, englishText, comment); idOfLanguageUsed = "en"; return englishText; } //otherwise, see if we have a translation if (LocalizationManager.GetIsStringAvailableForLangId(idSuffix, targetLanguage)) { idOfLanguageUsed = targetLanguage; return LocalizationManager.GetDynamicStringOrEnglish("Palaso", idSuffix, englishText, comment, targetLanguage); } } idOfLanguageUsed = string.Empty; return "[Missing translation for " + idSuffix + "]"; } } public class NullLicense : LicenseInfo { /// <summary> /// Get a simple, non-legal summary of the license, using the "best" language for which we can find a translation. /// </summary> /// <param name="languagePriorityIds"></param> /// <param name="idOfLanguageUsed">The idSuffix of the language we were able to use. Unreliable if we had to use a mix of languages.</param> /// <returns>The description of the license.</returns> public override string GetDescription(IEnumerable<string> languagePriorityIds, out string idOfLanguageUsed) { const string englishText = "For permission to reuse, contact the copyright holder."; const string comment = "This is used when all we have is a copyright, no other license."; return GetBestLicenseTranslation("NullLicense", englishText, comment, languagePriorityIds, out idOfLanguageUsed); } public override string Token { //do not think of changing this, there is data out there that could get messed up get { return "ask"; } } public override string GetMinimalFormForCredits(IEnumerable<string> languagePriorityIds, out string idOfLanguageUsed) { idOfLanguageUsed = "*"; return ""; // that is, the license is unknown. We might be tempted to return "used by permission", but... was it? } public override string ToString() { return ""; } public override string Url { get { return ""; } set { } } } public class CustomLicense : LicenseInfo { // public void SetDescription(string iso639_3LanguageCode, string description) // { // RightsStatement = description; // } public override string ToString() { return "Custom License"; } public override string GetMinimalFormForCredits(IEnumerable<string> languagePriorityIds, out string idOfLanguageUsed) { return GetDescription(languagePriorityIds, out idOfLanguageUsed); } ///<summary></summary> /// <remarks> /// Currently, we don't know the language of custom license strings, so we the ISO 639-2 code for undetermined, "und" /// </remarks> /// <param name="languagePriorityIds"></param> /// <param name="idOfLanguageUsed"></param> /// <returns></returns> public override string GetDescription(IEnumerable<string> languagePriorityIds, out string idOfLanguageUsed) { //if we're empty, we're equivalent to a NullLicense if (string.IsNullOrEmpty(RightsStatement)) { return new NullLicense().GetDescription(languagePriorityIds, out idOfLanguageUsed); } //We don't actually have a way of knowing what language this is, so we use "und", from http://www.loc.gov/standards/iso639-2/faq.html#25 //I hearby coin "Zook's First Law": Eventually any string entered by a user will wish it had been tagged with a language identifier //"Zook's Second Law" can be: Eventually any string entered by a user will wish it was a multi-string (multiple (language,value) pairs) idOfLanguageUsed = "und"; return RightsStatement; } public override string Token { //do not think of changing this, there is data out there that could get messed up get { return "custom"; } } public override Image GetImage() { return null; } public override bool EditingAllowed { get { return false; } //it may be ok, but we can't read the description. } public override string Url { get; set; } public static LicenseInfo FromMetadata(Dictionary<string, string> properties) { if (!properties.ContainsKey("rights (en)")) throw new ApplicationException("A license property is required in order to make a Custom License from metadata."); var license = new CustomLicense(); license.RightsStatement = properties["rights (en)"]; return license; } } }
// 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.IO; using System.Collections.Generic; using System.CommandLine; using System.Reflection; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Text; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; using Internal.IL; using Internal.CommandLine; using System.Text.RegularExpressions; namespace ILVerify { class Program { private bool _help; private Dictionary<string, string> _inputFilePaths = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); private Dictionary<string, string> _referenceFilePaths = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); private IReadOnlyList<Regex> _includePatterns = Array.Empty<Regex>(); private IReadOnlyList<Regex> _excludePatterns = Array.Empty<Regex>(); private SimpleTypeSystemContext _typeSystemContext; private int _numErrors; private Program() { } private void Help(string helpText) { Console.WriteLine("ILVerify version " + typeof(Program).Assembly.GetName().Version.ToString()); Console.WriteLine(); Console.WriteLine("-help Display this usage message (Short form: -?)"); Console.WriteLine("-reference Reference metadata from the specified assembly (Short form: -r)"); Console.WriteLine("-include Use only methods/types/namespaces, which match the given regular expression(s)"); Console.WriteLine("-exclude Skip methods/types/namespaces, which match the given regular expression(s)"); } public static IReadOnlyList<Regex> StringPatternsToRegexList(IReadOnlyList<string> patterns) { List<Regex> patternList = new List<Regex>(); foreach (var pattern in patterns) patternList.Add(new Regex(pattern)); return patternList; } private ArgumentSyntax ParseCommandLine(string[] args) { IReadOnlyList<string> inputFiles = Array.Empty<string>(); IReadOnlyList<string> referenceFiles = Array.Empty<string>(); IReadOnlyList<string> includePatterns = Array.Empty<string>(); IReadOnlyList<string> excludePatterns = Array.Empty<string>(); AssemblyName name = typeof(Program).GetTypeInfo().Assembly.GetName(); ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax => { syntax.ApplicationName = name.Name.ToString(); // HandleHelp writes to error, fails fast with crash dialog and lacks custom formatting. syntax.HandleHelp = false; syntax.HandleErrors = true; syntax.DefineOption("h|help", ref _help, "Help message for ILC"); syntax.DefineOptionList("r|reference", ref referenceFiles, "Reference file(s) for compilation"); syntax.DefineOptionList("i|include", ref includePatterns, "Use only methods/types/namespaces, which match the given regular expression(s)"); syntax.DefineOptionList("e|exclude", ref excludePatterns, "Skip methods/types/namespaces, which match the given regular expression(s)"); syntax.DefineParameterList("in", ref inputFiles, "Input file(s) to compile"); }); foreach (var input in inputFiles) Helpers.AppendExpandedPaths(_inputFilePaths, input, true); foreach (var reference in referenceFiles) Helpers.AppendExpandedPaths(_referenceFilePaths, reference, false); _includePatterns = StringPatternsToRegexList(includePatterns); _excludePatterns = StringPatternsToRegexList(excludePatterns); return argSyntax; } private void VerifyMethod(MethodDesc method, MethodIL methodIL) { // Console.WriteLine("Verifying: " + method.ToString()); try { var importer = new ILImporter(method, methodIL); importer.ReportVerificationError = (args) => { var message = new StringBuilder(); message.Append("[IL]: Error: "); message.Append("["); message.Append(_typeSystemContext.GetModulePath(((EcmaMethod)method).Module)); message.Append(" : "); message.Append(((EcmaType)method.OwningType).Name); message.Append("::"); message.Append(method.Name); message.Append("]"); message.Append("[offset 0x"); message.Append(args.Offset.ToString("X8")); message.Append("]"); if (args.Found != null) { message.Append("[found "); message.Append(args.Found); message.Append("]"); } if (args.Expected != null) { message.Append("[expected "); message.Append(args.Expected); message.Append("]"); } if (args.Token != 0) { message.Append("[token 0x"); message.Append(args.Token.ToString("X8")); message.Append("]"); } message.Append(" "); message.Append(SR.GetResourceString(args.Code.ToString(), null) ?? args.Code.ToString()); Console.WriteLine(message); _numErrors++; }; importer.Verify(); } catch (VerificationException) { } catch (BadImageFormatException) { Console.WriteLine("Unable to resolve token"); } catch (PlatformNotSupportedException e) { Console.WriteLine(e.Message); } } private void VerifyModule(EcmaModule module) { foreach (var methodHandle in module.MetadataReader.MethodDefinitions) { var method = (EcmaMethod)module.GetMethod(methodHandle); var methodIL = EcmaMethodIL.Create(method); if (methodIL == null) continue; var methodName = method.ToString(); if (_includePatterns.Count > 0 && !_includePatterns.Any(p => p.IsMatch(methodName))) continue; if (_excludePatterns.Any(p => p.IsMatch(methodName))) continue; VerifyMethod(method, methodIL); } } private int Run(string[] args) { ArgumentSyntax syntax = ParseCommandLine(args); if (_help) { Help(syntax.GetHelpText()); return 1; } if (_inputFilePaths.Count == 0) throw new CommandLineException("No input files specified"); _typeSystemContext = new SimpleTypeSystemContext(); _typeSystemContext.InputFilePaths = _inputFilePaths; _typeSystemContext.ReferenceFilePaths = _referenceFilePaths; _typeSystemContext.SetSystemModule(_typeSystemContext.GetModuleForSimpleName("mscorlib")); foreach (var inputPath in _inputFilePaths.Values) { _numErrors = 0; VerifyModule(_typeSystemContext.GetModuleFromPath(inputPath)); if (_numErrors > 0) Console.WriteLine(_numErrors + " Error(s) Verifying " + inputPath); else Console.WriteLine("All Classes and Methods in " + inputPath + " Verified."); } return 0; } private static int Main(string[] args) { try { return new Program().Run(args); } catch (Exception e) { Console.Error.WriteLine("Error: " + e.Message); return 1; } } } }
namespace Orleans.CodeGenerator { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.CodeGeneration; using Orleans.CodeGenerator.Utilities; using Orleans.Concurrency; using Orleans.Runtime; using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils; using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory; /// <summary> /// Code generator which generates <see cref="GrainReference"/>s for grains. /// </summary> public static class GrainReferenceGenerator { /// <summary> /// The suffix appended to the name of generated classes. /// </summary> private const string ClassSuffix = "Reference"; /// <summary> /// A reference to the CheckGrainObserverParamInternal method. /// </summary> private static readonly Expression<Action> CheckGrainObserverParamInternalExpression = () => GrainFactoryBase.CheckGrainObserverParamInternal(null); /// <summary> /// Generates the class for the provided grain types. /// </summary> /// <param name="grainType"> /// The grain interface type. /// </param> /// <param name="onEncounteredType"> /// The callback which is invoked when a type is encountered. /// </param> /// <returns> /// The generated class. /// </returns> internal static TypeDeclarationSyntax GenerateClass(Type grainType, Action<Type> onEncounteredType) { var grainTypeInfo = grainType.GetTypeInfo(); var genericTypes = grainTypeInfo.IsGenericTypeDefinition ? grainTypeInfo.GetGenericArguments() .Select(_ => SF.TypeParameter(_.ToString())) .ToArray() : new TypeParameterSyntax[0]; // Create the special marker attribute. var markerAttribute = SF.Attribute(typeof(GrainReferenceAttribute).GetNameSyntax()) .AddArgumentListArguments( SF.AttributeArgument( SF.TypeOfExpression(grainType.GetTypeSyntax(includeGenericParameters: false)))); var attributes = SF.AttributeList() .AddAttributes( CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(), SF.Attribute(typeof(SerializableAttribute).GetNameSyntax()), #if !NETSTANDARD_TODO //ExcludeFromCodeCoverageAttribute became an internal class in netstandard SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()), #endif markerAttribute); var className = CodeGeneratorCommon.ClassPrefix + TypeUtils.GetSuitableClassName(grainType) + ClassSuffix; var classDeclaration = SF.ClassDeclaration(className) .AddModifiers(SF.Token(SyntaxKind.InternalKeyword)) .AddBaseListTypes( SF.SimpleBaseType(typeof(GrainReference).GetTypeSyntax()), SF.SimpleBaseType(grainType.GetTypeSyntax())) .AddConstraintClauses(grainType.GetTypeConstraintSyntax()) .AddMembers(GenerateConstructors(className)) .AddMembers( GenerateInterfaceIdProperty(grainType), GenerateInterfaceVersionProperty(grainType), GenerateInterfaceNameProperty(grainType), GenerateIsCompatibleMethod(grainType), GenerateGetMethodNameMethod(grainType)) .AddMembers(GenerateInvokeMethods(grainType, onEncounteredType)) .AddAttributeLists(attributes); if (genericTypes.Length > 0) { classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes); } return classDeclaration; } /// <summary> /// Generates constructors. /// </summary> /// <param name="className">The class name.</param> /// <returns>Constructor syntax for the provided class name.</returns> private static MemberDeclarationSyntax[] GenerateConstructors(string className) { var baseConstructors = typeof(GrainReference).GetTypeInfo().GetConstructors( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).Where(_ => !_.IsPrivate); var constructors = new List<MemberDeclarationSyntax>(); foreach (var baseConstructor in baseConstructors) { var args = baseConstructor.GetParameters() .Select(arg => SF.Argument(arg.Name.ToIdentifierName())) .ToArray(); var declaration = baseConstructor.GetDeclarationSyntax(className) .WithInitializer( SF.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer) .AddArgumentListArguments(args)) .AddBodyStatements(); constructors.Add(declaration); } return constructors.ToArray(); } /// <summary> /// Generates invoker methods. /// </summary> /// <param name="grainType">The grain type.</param> /// <param name="onEncounteredType"> /// The callback which is invoked when a type is encountered. /// </param> /// <returns>Invoker methods for the provided grain type.</returns> private static MemberDeclarationSyntax[] GenerateInvokeMethods(Type grainType, Action<Type> onEncounteredType) { var baseReference = SF.BaseExpression(); var methods = GrainInterfaceUtils.GetMethods(grainType); var members = new List<MemberDeclarationSyntax>(); foreach (var method in methods) { onEncounteredType(method.ReturnType); var methodId = GrainInterfaceUtils.ComputeMethodId(method); var methodIdArgument = SF.Argument(SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(methodId))); // Construct a new object array from all method arguments. var parameters = method.GetParameters(); var body = new List<StatementSyntax>(); foreach (var parameter in parameters) { onEncounteredType(parameter.ParameterType); if (typeof(IGrainObserver).GetTypeInfo().IsAssignableFrom(parameter.ParameterType)) { body.Add( SF.ExpressionStatement( CheckGrainObserverParamInternalExpression.Invoke() .AddArgumentListArguments(SF.Argument(parameter.Name.ToIdentifierName())))); } } // Get the parameters argument value. ExpressionSyntax args; if (method.IsGenericMethodDefinition) { // Create an arguments array which includes the method's type parameters followed by the method's parameter list. var allParameters = new List<ExpressionSyntax>(); foreach (var typeParameter in method.GetGenericArguments()) { allParameters.Add(SF.TypeOfExpression(typeParameter.GetTypeSyntax())); } allParameters.AddRange(parameters.Select(GetParameterForInvocation)); args = SF.ArrayCreationExpression(typeof(object).GetArrayTypeSyntax()) .WithInitializer( SF.InitializerExpression(SyntaxKind.ArrayInitializerExpression) .AddExpressions(allParameters.ToArray())); } else if (parameters.Length == 0) { args = SF.LiteralExpression(SyntaxKind.NullLiteralExpression); } else { args = SF.ArrayCreationExpression(typeof(object).GetArrayTypeSyntax()) .WithInitializer( SF.InitializerExpression(SyntaxKind.ArrayInitializerExpression) .AddExpressions(parameters.Select(GetParameterForInvocation).ToArray())); } var options = GetInvokeOptions(method); // Construct the invocation call. var isOneWayTask = method.GetCustomAttribute<OneWayAttribute>() != null; if (method.ReturnType == typeof(void) || isOneWayTask) { var invocation = SF.InvocationExpression(baseReference.Member("InvokeOneWayMethod")) .AddArgumentListArguments(methodIdArgument) .AddArgumentListArguments(SF.Argument(args)); if (options != null) { invocation = invocation.AddArgumentListArguments(options); } body.Add(SF.ExpressionStatement(invocation)); if (isOneWayTask) { if (method.ReturnType != typeof(Task)) { throw new CodeGenerationException( $"Method {grainType.GetParseableName()}.{method.Name} is marked with [{nameof(OneWayAttribute)}], " + $"but has a return type which is not assignable from {typeof(Task)}"); } var done = typeof(Task).GetNameSyntax(true).Member((object _) => Task.CompletedTask); body.Add(SF.ReturnStatement(done)); } } else { var returnType = method.ReturnType == typeof(Task) ? typeof(object) : method.ReturnType.GenericTypeArguments[0]; var invocation = SF.InvocationExpression(baseReference.Member("InvokeMethodAsync", returnType)) .AddArgumentListArguments(methodIdArgument) .AddArgumentListArguments(SF.Argument(args)); if (options != null) { invocation = invocation.AddArgumentListArguments(options); } body.Add(SF.ReturnStatement(invocation)); } members.Add(method.GetDeclarationSyntax().AddBodyStatements(body.ToArray())); } return members.ToArray(); } /// <summary> /// Returns syntax for the options argument to <see cref="GrainReference.InvokeMethodAsync{T}"/> and <see cref="GrainReference.InvokeOneWayMethod"/>. /// </summary> /// <param name="method">The method which an invoke call is being generated for.</param> /// <returns> /// Argument syntax for the options argument to <see cref="GrainReference.InvokeMethodAsync{T}"/> and /// <see cref="GrainReference.InvokeOneWayMethod"/>, or <see langword="null"/> if no options are to be specified. /// </returns> private static ArgumentSyntax GetInvokeOptions(MethodInfo method) { var options = new List<ExpressionSyntax>(); if (GrainInterfaceUtils.IsReadOnly(method)) { options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.ReadOnly.ToString())); } if (GrainInterfaceUtils.IsUnordered(method)) { options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.Unordered.ToString())); } if (GrainInterfaceUtils.IsAlwaysInterleave(method)) { options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.AlwaysInterleave.ToString())); } ExpressionSyntax allOptions; if (options.Count <= 1) { allOptions = options.FirstOrDefault(); } else { allOptions = options.Aggregate((a, b) => SF.BinaryExpression(SyntaxKind.BitwiseOrExpression, a, b)); } if (allOptions == null) { return null; } return SF.Argument(SF.NameColon("options"), SF.Token(SyntaxKind.None), allOptions); } private static ExpressionSyntax GetParameterForInvocation(ParameterInfo arg, int argIndex) { var argIdentifier = arg.GetOrCreateName(argIndex).ToIdentifierName(); // Addressable arguments must be converted to references before passing. if (typeof(IAddressable).GetTypeInfo().IsAssignableFrom(arg.ParameterType) && arg.ParameterType.GetTypeInfo().IsInterface) { return SF.ConditionalExpression( SF.BinaryExpression(SyntaxKind.IsExpression, argIdentifier, typeof(Grain).GetTypeSyntax()), SF.InvocationExpression(argIdentifier.Member("AsReference", arg.ParameterType)), argIdentifier); } return argIdentifier; } private static MemberDeclarationSyntax GenerateInterfaceIdProperty(Type grainType) { var property = TypeUtils.Member((GrainReference _) => _.InterfaceId); var returnValue = SF.LiteralExpression( SyntaxKind.NumericLiteralExpression, SF.Literal(GrainInterfaceUtils.GetGrainInterfaceId(grainType))); return SF.PropertyDeclaration(typeof(int).GetTypeSyntax(), property.Name) .AddAccessorListAccessors( SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(SF.ReturnStatement(returnValue))) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.OverrideKeyword)); } private static MemberDeclarationSyntax GenerateInterfaceVersionProperty(Type grainType) { var property = TypeUtils.Member((GrainReference _) => _.InterfaceVersion); var returnValue = SF.LiteralExpression( SyntaxKind.NumericLiteralExpression, SF.Literal(GrainInterfaceUtils.GetGrainInterfaceVersion(grainType))); return SF.PropertyDeclaration(typeof(ushort).GetTypeSyntax(), property.Name) .AddAccessorListAccessors( SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(SF.ReturnStatement(returnValue))) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.OverrideKeyword)); } private static MemberDeclarationSyntax GenerateIsCompatibleMethod(Type grainType) { var method = TypeUtils.Method((GrainReference _) => _.IsCompatible(default(int))); var methodDeclaration = method.GetDeclarationSyntax(); var interfaceIdParameter = method.GetParameters()[0].Name.ToIdentifierName(); var interfaceIds = new HashSet<int>( new[] { GrainInterfaceUtils.GetGrainInterfaceId(grainType) }.Concat( GrainInterfaceUtils.GetRemoteInterfaces(grainType).Keys)); var returnValue = default(BinaryExpressionSyntax); foreach (var interfaceId in interfaceIds) { var check = SF.BinaryExpression( SyntaxKind.EqualsExpression, interfaceIdParameter, SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(interfaceId))); // If this is the first check, assign it, otherwise OR this check with the previous checks. returnValue = returnValue == null ? check : SF.BinaryExpression(SyntaxKind.LogicalOrExpression, returnValue, check); } return methodDeclaration.AddBodyStatements(SF.ReturnStatement(returnValue)) .AddModifiers(SF.Token(SyntaxKind.OverrideKeyword)); } private static MemberDeclarationSyntax GenerateInterfaceNameProperty(Type grainType) { var propertyName = TypeUtils.Member((GrainReference _) => _.InterfaceName); var returnValue = grainType.GetParseableName().GetLiteralExpression(); return SF.PropertyDeclaration(typeof(string).GetTypeSyntax(), propertyName.Name) .AddAccessorListAccessors( SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(SF.ReturnStatement(returnValue))) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.OverrideKeyword)); } private static MethodDeclarationSyntax GenerateGetMethodNameMethod(Type grainType) { var method = TypeUtils.Method((GrainReference _) => _.GetMethodName(default(int), default(int))); var methodDeclaration = method.GetDeclarationSyntax() .AddModifiers(SF.Token(SyntaxKind.OverrideKeyword)); var parameters = method.GetParameters(); var interfaceIdArgument = parameters[0].Name.ToIdentifierName(); var methodIdArgument = parameters[1].Name.ToIdentifierName(); var interfaceCases = CodeGeneratorCommon.GenerateGrainInterfaceAndMethodSwitch( grainType, methodIdArgument, methodType => new StatementSyntax[] { SF.ReturnStatement(methodType.Name.GetLiteralExpression()) }); // Generate the default case, which will throw a NotImplementedException. var errorMessage = SF.BinaryExpression( SyntaxKind.AddExpression, "interfaceId=".GetLiteralExpression(), interfaceIdArgument); var throwStatement = SF.ThrowStatement( SF.ObjectCreationExpression(typeof(NotImplementedException).GetTypeSyntax()) .AddArgumentListArguments(SF.Argument(errorMessage))); var defaultCase = SF.SwitchSection().AddLabels(SF.DefaultSwitchLabel()).AddStatements(throwStatement); var interfaceIdSwitch = SF.SwitchStatement(interfaceIdArgument).AddSections(interfaceCases.ToArray()).AddSections(defaultCase); return methodDeclaration.AddBodyStatements(interfaceIdSwitch); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Orleans.Concurrency; using Orleans.Runtime; namespace Orleans.CodeGeneration { internal static class GrainInterfaceUtils { private static readonly IEqualityComparer<MethodInfo> MethodComparer = new MethodInfoComparer(); [Serializable] internal class RulesViolationException : ArgumentException { public RulesViolationException(string message, List<string> violations) : base(message) { Violations = violations; } public List<string> Violations { get; private set; } } public static bool IsGrainInterface(Type t) { if (t.GetTypeInfo().IsClass) return false; if (t == typeof(IGrainObserver) || t == typeof(IAddressable) || t == typeof(IGrainExtension)) return false; if (t == typeof(IGrain) || t == typeof(IGrainWithGuidKey) || t == typeof(IGrainWithIntegerKey) || t == typeof(IGrainWithGuidCompoundKey) || t == typeof(IGrainWithIntegerCompoundKey)) return false; if (t == typeof (ISystemTarget)) return false; return typeof (IAddressable).IsAssignableFrom(t); } public static MethodInfo[] GetMethods(Type grainType, bool bAllMethods = true) { var methodInfos = new List<MethodInfo>(); GetMethodsImpl(grainType, grainType, methodInfos); var flags = BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance; if (!bAllMethods) flags |= BindingFlags.DeclaredOnly; MethodInfo[] infos = grainType.GetMethods(flags); foreach (var methodInfo in infos) if (!methodInfos.Contains(methodInfo, MethodComparer)) methodInfos.Add(methodInfo); return methodInfos.ToArray(); } public static string GetParameterName(ParameterInfo info) { var n = info.Name; return string.IsNullOrEmpty(n) ? "arg" + info.Position : n; } public static bool IsTaskType(Type t) { var typeInfo = t.GetTypeInfo(); return t == typeof (Task) || (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition().FullName == "System.Threading.Tasks.Task`1"); } /// <summary> /// Whether method is read-only, i.e. does not modify grain state, /// a method marked with [ReadOnly]. /// </summary> /// <param name="info"></param> /// <returns></returns> public static bool IsReadOnly(MethodInfo info) { return info.GetCustomAttributes(typeof (ReadOnlyAttribute), true).Any(); } public static bool IsAlwaysInterleave(MethodInfo methodInfo) { return methodInfo.GetCustomAttributes(typeof (AlwaysInterleaveAttribute), true).Any(); } public static bool IsUnordered(MethodInfo methodInfo) { var declaringTypeInfo = methodInfo.DeclaringType.GetTypeInfo(); return declaringTypeInfo.GetCustomAttributes(typeof(UnorderedAttribute), true).Any() || (declaringTypeInfo.GetInterfaces().Any( i => i.GetTypeInfo().GetCustomAttributes(typeof(UnorderedAttribute), true).Any() && declaringTypeInfo.GetRuntimeInterfaceMap(i).TargetMethods.Contains(methodInfo))) || IsStatelessWorker(methodInfo); } public static bool IsStatelessWorker(TypeInfo grainTypeInfo) { return grainTypeInfo.GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Any() || grainTypeInfo.GetInterfaces() .Any(i => i.GetTypeInfo().GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Any()); } public static bool IsStatelessWorker(MethodInfo methodInfo) { var declaringTypeInfo = methodInfo.DeclaringType.GetTypeInfo(); return declaringTypeInfo.GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Any() || (declaringTypeInfo.GetInterfaces().Any( i => i.GetTypeInfo().GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Any() && declaringTypeInfo.GetRuntimeInterfaceMap(i).TargetMethods.Contains(methodInfo))); } public static Dictionary<int, Type> GetRemoteInterfaces(Type type, bool checkIsGrainInterface = true) { var dict = new Dictionary<int, Type>(); if (IsGrainInterface(type)) dict.Add(GetGrainInterfaceId(type), type); Type[] interfaces = type.GetInterfaces(); foreach (Type interfaceType in interfaces.Where(i => !checkIsGrainInterface || IsGrainInterface(i))) dict.Add(GetGrainInterfaceId(interfaceType), interfaceType); return dict; } public static int ComputeMethodId(MethodInfo methodInfo) { var attr = methodInfo.GetCustomAttribute<MethodIdAttribute>(true); if (attr != null) return attr.MethodId; var strMethodId = new StringBuilder(methodInfo.Name); if (methodInfo.IsGenericMethodDefinition) { strMethodId.Append('<'); var first = true; foreach (var arg in methodInfo.GetGenericArguments()) { if (!first) strMethodId.Append(','); else first = false; strMethodId.Append(arg.Name); } strMethodId.Append('>'); } strMethodId.Append('('); ParameterInfo[] parameters = methodInfo.GetParameters(); bool bFirstTime = true; foreach (ParameterInfo info in parameters) { if (!bFirstTime) strMethodId.Append(','); strMethodId.Append(info.ParameterType.Name); var typeInfo = info.ParameterType.GetTypeInfo(); if (typeInfo.IsGenericType) { Type[] args = typeInfo.GetGenericArguments(); foreach (Type arg in args) strMethodId.Append(arg.Name); } bFirstTime = false; } strMethodId.Append(')'); return Utils.CalculateIdHash(strMethodId.ToString()); } public static int GetGrainInterfaceId(Type grainInterface) { return GetTypeCode(grainInterface); } public static ushort GetGrainInterfaceVersion(Type grainInterface) { if (typeof(IGrainExtension).IsAssignableFrom(grainInterface)) return 0; var attr = grainInterface.GetTypeInfo().GetCustomAttribute<VersionAttribute>(); return attr?.Version ?? Constants.DefaultInterfaceVersion; } public static bool IsTaskBasedInterface(Type type) { var methods = type.GetMethods(); // An interface is task-based if it has at least one method that returns a Task or at least one parent that's task-based. return methods.Any(m => IsTaskType(m.ReturnType)) || type.GetInterfaces().Any(IsTaskBasedInterface); } public static bool IsGrainType(Type grainType) { return typeof (IGrain).IsAssignableFrom(grainType); } public static int GetGrainClassTypeCode(Type grainClass) { return GetTypeCode(grainClass); } internal static bool TryValidateInterfaceRules(Type type, out List<string> violations) { violations = new List<string>(); bool success = ValidateInterfaceMethods(type, violations); return success && ValidateInterfaceProperties(type, violations); } internal static void ValidateInterfaceRules(Type type) { List<string> violations; if (!TryValidateInterfaceRules(type, out violations)) { if (ConsoleText.IsConsoleAvailable) { foreach (var violation in violations) ConsoleText.WriteLine("ERROR: " + violation); } throw new RulesViolationException( string.Format("{0} does not conform to the grain interface rules.", type.FullName), violations); } } internal static void ValidateInterface(Type type) { if (!IsGrainInterface(type)) throw new ArgumentException(String.Format("{0} is not a grain interface", type.FullName)); ValidateInterfaceRules(type); } private static bool ValidateInterfaceMethods(Type type, List<string> violations) { bool success = true; MethodInfo[] methods = type.GetMethods(); foreach (MethodInfo method in methods) { if (method.IsSpecialName) continue; if (IsPureObserverInterface(method.DeclaringType)) { if (method.ReturnType != typeof (void)) { success = false; violations.Add(String.Format("Method {0}.{1} must return void because it is defined within an observer interface.", type.FullName, method.Name)); } } else if (!IsTaskType(method.ReturnType)) { success = false; violations.Add(String.Format("Method {0}.{1} must return Task or Task<T> because it is defined within a grain interface.", type.FullName, method.Name)); } ParameterInfo[] parameters = method.GetParameters(); foreach (ParameterInfo parameter in parameters) { if (parameter.IsOut) { success = false; violations.Add(String.Format("Argument {0} of method {1}.{2} is an output parameter. Output parameters are not allowed in grain interfaces.", GetParameterName(parameter), type.FullName, method.Name)); } if (parameter.ParameterType.GetTypeInfo().IsByRef) { success = false; violations.Add(String.Format("Argument {0} of method {1}.{2} is an a reference parameter. Reference parameters are not allowed.", GetParameterName(parameter), type.FullName, method.Name)); } } } return success; } private static bool ValidateInterfaceProperties(Type type, List<string> violations) { bool success = true; PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { success = false; violations.Add(String.Format("Properties are not allowed on grain interfaces: {0}.{1}.", type.FullName, property.Name)); } return success; } /// <summary> /// decide whether the class is derived from Grain /// </summary> private static bool IsPureObserverInterface(Type t) { if (!typeof (IGrainObserver).IsAssignableFrom(t)) return false; if (t == typeof (IGrainObserver)) return true; if (t == typeof (IAddressable)) return false; bool pure = false; foreach (Type iface in t.GetInterfaces()) { if (iface == typeof (IAddressable)) // skip IAddressable that will be in the list regardless continue; if (iface == typeof (IGrainExtension)) // Skip IGrainExtension, it's just a marker that can go on observer or grain interfaces continue; pure = IsPureObserverInterface(iface); if (!pure) return false; } return pure; } private class MethodInfoComparer : IEqualityComparer<MethodInfo> { #region IEqualityComparer<InterfaceInfo> Members public bool Equals(MethodInfo x, MethodInfo y) { return string.Equals(GetSignature(x), GetSignature(y), StringComparison.Ordinal); } private static string GetSignature(MethodInfo method) { var result = new StringBuilder(method.Name); if (method.IsGenericMethodDefinition) { foreach (var arg in method.GetGenericArguments()) { result.Append(arg.Name); } } var parms = method.GetParameters(); foreach (var info in parms) { var typeInfo = info.ParameterType.GetTypeInfo(); result.Append(typeInfo.Name); if (typeInfo.IsGenericType) { var args = info.ParameterType.GetGenericArguments(); foreach (var arg in args) { result.Append(arg.Name); } } } return result.ToString(); } public int GetHashCode(MethodInfo obj) { throw new NotImplementedException(); } #endregion } /// <summary> /// Recurses through interface graph accumulating methods /// </summary> /// <param name="grainType">Grain type</param> /// <param name="serviceType">Service interface type</param> /// <param name="methodInfos">Accumulated </param> private static void GetMethodsImpl(Type grainType, Type serviceType, List<MethodInfo> methodInfos) { Type[] iTypes = GetRemoteInterfaces(serviceType, false).Values.ToArray(); IEqualityComparer<MethodInfo> methodComparer = new MethodInfoComparer(); var typeInfo = grainType.GetTypeInfo(); foreach (Type iType in iTypes) { var mapping = new InterfaceMapping(); if (typeInfo.IsClass) mapping = typeInfo.GetRuntimeInterfaceMap(iType); if (typeInfo.IsInterface || mapping.TargetType == grainType) { foreach (var methodInfo in iType.GetMethods()) { if (typeInfo.IsClass) { var mi = methodInfo; var match = mapping.TargetMethods.Any(info => methodComparer.Equals(mi, info) && info.DeclaringType == grainType); if (match) if (!methodInfos.Contains(mi, methodComparer)) methodInfos.Add(mi); } else if (!methodInfos.Contains(methodInfo, methodComparer)) { methodInfos.Add(methodInfo); } } } } } private static int GetTypeCode(Type grainInterfaceOrClass) { var typeInfo = grainInterfaceOrClass.GetTypeInfo(); var attr = typeInfo.GetCustomAttributes<TypeCodeOverrideAttribute>(false).FirstOrDefault(); if (attr != null && attr.TypeCode > 0) { return attr.TypeCode; } var fullName = TypeUtils.GetTemplatedName( TypeUtils.GetFullName(grainInterfaceOrClass), grainInterfaceOrClass, grainInterfaceOrClass.GetGenericArguments(), t => false); return Utils.CalculateIdHash(fullName); } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using NUnit.Framework.Internal; namespace NUnit.Framework.Constraints { [TestFixture] public class DictionaryContainsKeyConstraintTests { [Test] public void SucceedsWhenKeyIsPresent() { var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, new DictionaryContainsKeyConstraint("Hello")); } [Test] public void SucceedsWhenKeyIsPresentUsingContainKey() { var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, Does.ContainKey("Hola")); } [Test] public void SucceedsWhenKeyIsNotPresentUsingContainKey() { var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, Does.Not.ContainKey("NotKey")); } [Test] public void FailsWhenKeyIsMissing() { var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } }; TestDelegate act = () => Assert.That(dictionary, new DictionaryContainsKeyConstraint("Hallo")); Assert.That(act, Throws.Exception.TypeOf<AssertionException>()); } [Test] public void FailsWhenNotUsedAgainstADictionary() { List<KeyValuePair<string, string>> keyValuePairs = new List<KeyValuePair<string, string>>( new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } }); TestDelegate act = () => Assert.That(keyValuePairs, new DictionaryContainsKeyConstraint("Hallo")); Assert.That(act, Throws.ArgumentException.With.Message.Contains("ContainsKey")); } [Test] public void WorksWithNonGenericDictionary() { var dictionary = new Hashtable { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, new DictionaryContainsKeyConstraint("Hello")); } [Test] public void SucceedsWhenKeyIsPresentWhenDictionaryUsingCustomComparer() { var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, new DictionaryContainsKeyConstraint("hello")); } [Test] public void SucceedsWhenKeyIsPresentUsingContainsKeyWhenDictionaryUsingCustomComparer() { var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, Does.ContainKey("hola")); } [Test] public void SucceedsWhenKeyIsPresentUsingContainsKeyWhenUsingLookupCustomComparer() { var list = new List<string> { "ALICE", "BOB", "CATHERINE" }; ILookup<string, string> lookup = list.ToLookup(x => x, StringComparer.OrdinalIgnoreCase); Assert.That(lookup, Does.ContainKey("catherine")); } [Test] public void SucceedsWhenKeyIsNotPresentUsingContainsKeyUsingLookupDefaultComparer() { var list = new List<string> { "ALICE", "BOB", "CATHERINE" }; ILookup<string, string> lookup = list.ToLookup(x => x); Assert.That(lookup, !Does.ContainKey("alice")); } [Test] public void SucceedsWhenKeyIsPresentUsingContainsKeyWhenUsingKeyedCollectionCustomComparer() { var list = new TestKeyedCollection(StringComparer.OrdinalIgnoreCase) { "ALICE", "BOB", "CALUM" }; Assert.That(list, Does.ContainKey("calum")); } [Test] public void KeyIsNotPresentUsingContainsKeyUsingKeyedCollectionDefaultComparer() { var list = new TestKeyedCollection { "ALICE", "BOB", "CALUM" }; Assert.That(list, !Does.ContainKey("alice")); } [Test] public void SucceedsWhenKeyIsPresentUsingContainsKeyUsingHashtableCustomComparer() { var table = new Hashtable(StringComparer.OrdinalIgnoreCase) { { "ALICE", "BOB" }, { "CALUM", "DENNIS" } }; Assert.That(table, Does.ContainKey("alice")); } [Test] public void SucceedsWhenKeyIsPresentUsingContainsKeyUsingHashtableDefaultComparer() { var table = new Hashtable { { "ALICE", "BOB" }, { "CALUM", "DENNIS" } }; Assert.That(table, !Does.ContainKey("calum")); } [Test] public void ShouldCallContainsKeysMethodWithTKeyParameterOnNewMethod() { var dictionary = new TestDictionaryGeneric<string, string> { { "ALICE", "BOB" }, { "CALUM", "DENNIS" } }; Assert.That(dictionary, Does.ContainKey("BOB")); } [Test] public void ShouldCallContainsKeysMethodOnDictionary() { var dictionary = new TestDictionary(20); Assert.That(dictionary, Does.ContainKey(20)); Assert.That(dictionary, !Does.ContainKey(10)); } [Test] public void ShouldCallContainsKeysMethodOnPlainDictionary() { var dictionary = new TestNonGenericDictionary(99); Assert.That(dictionary, Does.ContainKey(99)); Assert.That(dictionary, !Does.ContainKey(35)); } [Test] public void ShouldCallContainsKeysMethodOnObject() { var poco = new TestPlainContainsKey("David"); Assert.DoesNotThrow(() => Assert.That(poco, Does.ContainKey("David"))); } [Test] public void ShouldThrowWhenUsedOnObjectWithNonGenericContains() { var poco = new TestPlainObjectContainsNonGeneric("Peter"); Assert.Catch<ArgumentException>(() => Assert.That(poco, Does.ContainKey("Peter"))); } [Test] public void ShouldCallContainsWhenUsedOnObjectWithGenericContains() { var poco = new TestPlainObjectContainsGeneric<string>("Peter"); Assert.DoesNotThrow(() => Assert.That(poco, Does.ContainKey("Peter"))); } [Test] public void ShouldCallContainsKeysMethodOnReadOnlyInterface() { var dictionary = new TestReadOnlyDictionary("BOB"); Assert.That(dictionary, Does.ContainKey("BOB")); Assert.That(dictionary, !Does.ContainKey("ALICE")); } [Test] public void ShouldThrowWhenUsedWithISet() { var set = new TestSet(); Assert.Catch<ArgumentException>(() => Assert.That(set, Does.ContainKey("NotHappening"))); } [Test] public void ShouldCallContainsKeysMethodOnLookupInterface() { var dictionary = new TestLookup(20); Assert.That(dictionary, Does.ContainKey(20)); Assert.That(dictionary, !Does.ContainKey(43)); } #region Test Assets public class TestPlainContainsKey { private readonly string _key; public TestPlainContainsKey(string key) { _key = key; } public bool ContainsKey(string key) { return _key.Equals(key); } } public class TestPlainObjectContainsNonGeneric { private readonly string _key; public TestPlainObjectContainsNonGeneric(string key) { _key = key; } public bool Contains(string key) { return _key.Equals(key); } } public class TestPlainObjectContainsGeneric<TKey> { private readonly TKey _key; public TestPlainObjectContainsGeneric(TKey key) { _key = key; } public bool Contains(TKey key) { return _key.Equals(key); } } public class TestKeyedCollection : KeyedCollection<string, string> { public TestKeyedCollection() { } public TestKeyedCollection(IEqualityComparer<string> comparer) : base(comparer) { } protected override string GetKeyForItem(string item) { return item; } } public class TestDictionaryGeneric<TKey, TItem> : Dictionary<TKey, TItem> { public new bool ContainsKey(TKey key) { return base.Values.Any(x => x.Equals(key)); } } public class TestDictionary : IDictionary<int, string> { private readonly int _key; public TestDictionary(int key) { _key = key; } public IEnumerator<KeyValuePair<int, string>> GetEnumerator() { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Add(KeyValuePair<int, string> item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(KeyValuePair<int, string> item) { throw new NotImplementedException(); } public void CopyTo(KeyValuePair<int, string>[] array, int arrayIndex) { throw new NotImplementedException(); } public bool Remove(KeyValuePair<int, string> item) { throw new NotImplementedException(); } public int Count { get; } public bool IsReadOnly { get; } public bool ContainsKey(int key) { return key == _key; } public void Add(int key, string value) { throw new NotImplementedException(); } public bool Remove(int key) { throw new NotImplementedException(); } public bool TryGetValue(int key, out string value) { throw new NotImplementedException(); } public string this[int key] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public ICollection<int> Keys { get; } public ICollection<string> Values { get; } } public class TestNonGenericDictionary : IDictionary { private readonly int _key; public TestNonGenericDictionary(int key) { _key = key; } public bool Contains(object key) { return _key == (int)key; } public void Add(object key, object value) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public IDictionaryEnumerator GetEnumerator() { throw new NotImplementedException(); } public void Remove(object key) { throw new NotImplementedException(); } public object this[object key] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public ICollection Keys { get; } public ICollection Values { get; } public bool IsReadOnly { get; } public bool IsFixedSize { get; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void CopyTo(Array array, int index) { throw new NotImplementedException(); } public int Count { get; } public object SyncRoot { get; } public bool IsSynchronized { get; } } public class TestLookup : ILookup<int, string> { private readonly int _key; public TestLookup(int key) { _key = key; } public IEnumerator<IGrouping<int, string>> GetEnumerator() { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public bool Contains(int key) { return key == _key; } public int Count { get; } public IEnumerable<string> this[int key] { get { throw new NotImplementedException(); } } } public class TestReadOnlyDictionary : IReadOnlyDictionary<string, string> { private readonly string _key; public TestReadOnlyDictionary(string key) { _key = key; } public IEnumerator<KeyValuePair<string, string>> GetEnumerator() { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count { get; } public bool ContainsKey(string key) { return _key == key; } public bool TryGetValue(string key, out string value) { throw new NotImplementedException(); } public string this[string key] { get { throw new NotImplementedException(); } } public IEnumerable<string> Keys { get; } public IEnumerable<string> Values { get; } } public class TestSet : ISet<int> { public IEnumerator<int> GetEnumerator() { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } void ICollection<int>.Add(int item) { throw new NotImplementedException(); } public void UnionWith(IEnumerable<int> other) { throw new NotImplementedException(); } public void IntersectWith(IEnumerable<int> other) { throw new NotImplementedException(); } public void ExceptWith(IEnumerable<int> other) { throw new NotImplementedException(); } public void SymmetricExceptWith(IEnumerable<int> other) { throw new NotImplementedException(); } public bool IsSubsetOf(IEnumerable<int> other) { throw new NotImplementedException(); } public bool IsSupersetOf(IEnumerable<int> other) { throw new NotImplementedException(); } public bool IsProperSupersetOf(IEnumerable<int> other) { throw new NotImplementedException(); } public bool IsProperSubsetOf(IEnumerable<int> other) { throw new NotImplementedException(); } public bool Overlaps(IEnumerable<int> other) { throw new NotImplementedException(); } public bool SetEquals(IEnumerable<int> other) { throw new NotImplementedException(); } bool ISet<int>.Add(int item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(int item) { throw new NotImplementedException(); } public void CopyTo(int[] array, int arrayIndex) { throw new NotImplementedException(); } public bool Remove(int item) { throw new NotImplementedException(); } public int Count { get; } public bool IsReadOnly { get; } } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.11.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyComplex { using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// Polymorphicrecursive operations. /// </summary> public partial class Polymorphicrecursive : IServiceOperations<AutoRestComplexTestService>, IPolymorphicrecursive { /// <summary> /// Initializes a new instance of the Polymorphicrecursive class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> public Polymorphicrecursive(AutoRestComplexTestService client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestComplexTestService /// </summary> public AutoRestComplexTestService Client { get; private set; } /// <summary> /// Get complex types that are polymorphic and have recursive references /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<Fish>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetValid", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/complex/polymorphicrecursive/valid").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<Fish>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<Fish>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Put complex types that are polymorphic and have recursive references /// </summary> /// <param name='complexBody'> /// Please put a salmon that looks like this: /// { /// "dtype": "salmon", /// "species": "king", /// "length": 1, /// "age": 1, /// "location": "alaska", /// "iswild": true, /// "siblings": [ /// { /// "dtype": "shark", /// "species": "predator", /// "length": 20, /// "age": 6, /// "siblings": [ /// { /// "dtype": "salmon", /// "species": "coho", /// "length": 2, /// "age": 2, /// "location": "atlantic", /// "iswild": true, /// "siblings": [ /// { /// "dtype": "shark", /// "species": "predator", /// "length": 20, /// "age": 6 /// }, /// { /// "dtype": "sawshark", /// "species": "dangerous", /// "length": 10, /// "age": 105 /// } /// ] /// }, /// { /// "dtype": "sawshark", /// "species": "dangerous", /// "length": 10, /// "age": 105 /// } /// ] /// }, /// { /// "dtype": "sawshark", /// "species": "dangerous", /// "length": 10, /// "age": 105 /// } /// ] /// } /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(Fish complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } if (complexBody != null) { complexBody.Validate(); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "PutValid", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/complex/polymorphicrecursive/valid").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PUT"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } } }
#region File Description //----------------------------------------------------------------------------- // SmokePlumeParticleSystem.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; #endregion namespace ParticleSample { /// <summary> /// ParticleSystem is an abstract class that provides the basic functionality to /// create a particle effect. Different subclasses will have different effects, /// such as fire, explosions, and plumes of smoke. To use these subclasses, /// simply call AddParticles, and pass in where the particles should exist /// </summary> public abstract class ParticleSystem : DrawableGameComponent { // these two values control the order that particle systems are drawn in. // typically, particles that use additive blending should be drawn on top of // particles that use regular alpha blending. ParticleSystems should therefore // set their DrawOrder to the appropriate value in InitializeConstants, though // it is possible to use other values for more advanced effects. public const int AlphaBlendDrawOrder = 100; public const int AdditiveDrawOrder = 200; // a reference to the main game; we'll keep this around because it exposes a // content manager and a sprite batch for us to use. private ParticleSampleGame game; // the texture this particle system will use. private Texture2D texture; // the origin when we're drawing textures. this will be the middle of the // texture. private Vector2 origin; // this number represents the maximum number of effects this particle system // will be expected to draw at one time. this is set in the constructor and is // used to calculate how many particles we will need. private int howManyEffects; // the array of particles used by this system. these are reused, so that calling // AddParticles will not cause any allocations. Particle[] particles; // the queue of free particles keeps track of particles that are not curently // being used by an effect. when a new effect is requested, particles are taken // from this queue. when particles are finished they are put onto this queue. Queue<Particle> freeParticles; /// <summary> /// returns the number of particles that are available for a new effect. /// </summary> public int FreeParticleCount { get { return freeParticles.Count; } } // This region of values control the "look" of the particle system, and should // be set by deriving particle systems in the InitializeConstants method. The // values are then used by the virtual function InitializeParticle. Subclasses // can override InitializeParticle for further // customization. #region constants to be set by subclasses /// <summary> /// minNumParticles and maxNumParticles control the number of particles that are /// added when AddParticles is called. The number of particles will be a random /// number between minNumParticles and maxNumParticles. /// </summary> protected int minNumParticles; protected int maxNumParticles; /// <summary> /// this controls the texture that the particle system uses. It will be used as /// an argument to ContentManager.Load. /// </summary> protected string textureFilename; /// <summary> /// minInitialSpeed and maxInitialSpeed are used to control the initial velocity /// of the particles. The particle's initial speed will be a random number /// between these two. The direction is determined by the function /// PickRandomDirection, which can be overriden. /// </summary> protected float minInitialSpeed; protected float maxInitialSpeed; /// <summary> /// minAcceleration and maxAcceleration are used to control the acceleration of /// the particles. The particle's acceleration will be a random number between /// these two. By default, the direction of acceleration is the same as the /// direction of the initial velocity. /// </summary> protected float minAcceleration; protected float maxAcceleration; /// <summary> /// minRotationSpeed and maxRotationSpeed control the particles' angular /// velocity: the speed at which particles will rotate. Each particle's rotation /// speed will be a random number between minRotationSpeed and maxRotationSpeed. /// Use smaller numbers to make particle systems look calm and wispy, and large /// numbers for more violent effects. /// </summary> protected float minRotationSpeed; protected float maxRotationSpeed; /// <summary> /// minLifetime and maxLifetime are used to control the lifetime. Each /// particle's lifetime will be a random number between these two. Lifetime /// is used to determine how long a particle "lasts." Also, in the base /// implementation of Draw, lifetime is also used to calculate alpha and scale /// values to avoid particles suddenly "popping" into view /// </summary> protected float minLifetime; protected float maxLifetime; /// <summary> /// to get some additional variance in the appearance of the particles, we give /// them all random scales. the scale is a value between minScale and maxScale, /// and is additionally affected by the particle's lifetime to avoid particles /// "popping" into view. /// </summary> protected float minScale; protected float maxScale; /// <summary> /// different effects can use different blend states. fire and explosions work /// well with additive blending, for example. /// </summary> protected BlendState blendState; #endregion /// <summary> /// Constructs a new ParticleSystem. /// </summary> /// <param name="game">The host for this particle system. The game keeps the /// content manager and sprite batch for us.</param> /// <param name="howManyEffects">the maximum number of particle effects that /// are expected on screen at once.</param> /// <remarks>it is tempting to set the value of howManyEffects very high. /// However, this value should be set to the minimum possible, because /// it has a large impact on the amount of memory required, and slows down the /// Update and Draw functions.</remarks> protected ParticleSystem(ParticleSampleGame game, int howManyEffects) : base(game) { this.game = game; this.howManyEffects = howManyEffects; } /// <summary> /// override the base class's Initialize to do some additional work; we want to /// call InitializeConstants to let subclasses set the constants that we'll use. /// /// also, the particle array and freeParticles queue are set up here. /// </summary> public override void Initialize() { InitializeConstants(); // calculate the total number of particles we will ever need, using the // max number of effects and the max number of particles per effect. // once these particles are allocated, they will be reused, so that // we don't put any pressure on the garbage collector. particles = new Particle[howManyEffects * maxNumParticles]; freeParticles = new Queue<Particle>(howManyEffects * maxNumParticles); for (int i = 0; i < particles.Length; i++) { particles[i] = new Particle(); freeParticles.Enqueue(particles[i]); } base.Initialize(); } /// <summary> /// this abstract function must be overriden by subclasses of ParticleSystem. /// It's here that they should set all the constants marked in the region /// "constants to be set by subclasses", which give each ParticleSystem its /// specific flavor. /// </summary> protected abstract void InitializeConstants(); /// <summary> /// Override the base class LoadContent to load the texture. once it's /// loaded, calculate the origin. /// </summary> protected override void LoadContent() { // make sure sub classes properly set textureFilename. if (string.IsNullOrEmpty(textureFilename)) { string message = "textureFilename wasn't set properly, so the " + "particle system doesn't know what texture to load. Make " + "sure your particle system's InitializeConstants function " + "properly sets textureFilename."; throw new InvalidOperationException(message); } // load the texture.... texture = game.Content.Load<Texture2D>(textureFilename); // ... and calculate the center. this'll be used in the draw call, we // always want to rotate and scale around this point. origin.X = texture.Width / 2; origin.Y = texture.Height / 2; base.LoadContent(); } /// <summary> /// AddParticles's job is to add an effect somewhere on the screen. If there /// aren't enough particles in the freeParticles queue, it will use as many as /// it can. This means that if there not enough particles available, calling /// AddParticles will have no effect. /// </summary> /// <param name="where">where the particle effect should be created</param> public void AddParticles(Vector2 where) { // the number of particles we want for this effect is a random number // somewhere between the two constants specified by the subclasses. int numParticles = ParticleSampleGame.Random.Next(minNumParticles, maxNumParticles); // create that many particles, if you can. for (int i = 0; i < numParticles && freeParticles.Count > 0; i++) { // grab a particle from the freeParticles queue, and Initialize it. Particle p = freeParticles.Dequeue(); InitializeParticle(p, where); } } /// <summary> /// InitializeParticle randomizes some properties for a particle, then /// calls initialize on it. It can be overriden by subclasses if they /// want to modify the way particles are created. For example, /// SmokePlumeParticleSystem overrides this function make all particles /// accelerate to the right, simulating wind. /// </summary> /// <param name="p">the particle to initialize</param> /// <param name="where">the position on the screen that the particle should be /// </param> protected virtual void InitializeParticle(Particle p, Vector2 where) { // first, call PickRandomDirection to figure out which way the particle // will be moving. velocity and acceleration's values will come from this. Vector2 direction = PickRandomDirection(); // pick some random values for our particle float velocity = ParticleSampleGame.RandomBetween(minInitialSpeed, maxInitialSpeed); float acceleration = ParticleSampleGame.RandomBetween(minAcceleration, maxAcceleration); float lifetime = ParticleSampleGame.RandomBetween(minLifetime, maxLifetime); float scale = ParticleSampleGame.RandomBetween(minScale, maxScale); float rotationSpeed = ParticleSampleGame.RandomBetween(minRotationSpeed, maxRotationSpeed); // then initialize it with those random values. initialize will save those, // and make sure it is marked as active. p.Initialize( where, velocity * direction, acceleration * direction, lifetime, scale, rotationSpeed); } /// <summary> /// PickRandomDirection is used by InitializeParticles to decide which direction /// particles will move. The default implementation is a random vector in a /// circular pattern. /// </summary> protected virtual Vector2 PickRandomDirection() { float angle = ParticleSampleGame.RandomBetween(0, MathHelper.TwoPi); return new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle)); } /// <summary> /// overriden from DrawableGameComponent, Update will update all of the active /// particles. /// </summary> public override void Update(GameTime gameTime) { // calculate dt, the change in the since the last frame. the particle // updates will use this value. float dt = (float)gameTime.ElapsedGameTime.TotalSeconds; // go through all of the particles... foreach (Particle p in particles) { if (p.Active) { // ... and if they're active, update them. p.Update(dt); // if that update finishes them, put them onto the free particles // queue. if (!p.Active) { freeParticles.Enqueue(p); } } } base.Update(gameTime); } /// <summary> /// overriden from DrawableGameComponent, Draw will use ParticleSampleGame's /// sprite batch to render all of the active particles. /// </summary> public override void Draw(GameTime gameTime) { // tell sprite batch to begin, using the spriteBlendMode specified in // initializeConstants game.SpriteBatch.Begin(SpriteSortMode.Deferred, blendState); foreach (Particle p in particles) { // skip inactive particles if (!p.Active) continue; // normalized lifetime is a value from 0 to 1 and represents how far // a particle is through its life. 0 means it just started, .5 is half // way through, and 1.0 means it's just about to be finished. // this value will be used to calculate alpha and scale, to avoid // having particles suddenly appear or disappear. float normalizedLifetime = p.TimeSinceStart / p.Lifetime; // we want particles to fade in and fade out, so we'll calculate alpha // to be (normalizedLifetime) * (1-normalizedLifetime). this way, when // normalizedLifetime is 0 or 1, alpha is 0. the maximum value is at // normalizedLifetime = .5, and is // (normalizedLifetime) * (1-normalizedLifetime) // (.5) * (1-.5) // .25 // since we want the maximum alpha to be 1, not .25, we'll scale the // entire equation by 4. float alpha = 4 * normalizedLifetime * (1 - normalizedLifetime); Color color = Color.White * alpha; // make particles grow as they age. they'll start at 75% of their size, // and increase to 100% once they're finished. float scale = p.Scale * (.75f + .25f * normalizedLifetime); game.SpriteBatch.Draw(texture, p.Position, null, color, p.Rotation, origin, scale, SpriteEffects.None, 0.0f); } game.SpriteBatch.End(); base.Draw(gameTime); } } }
// 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 Xunit; namespace LinkedList_LinkedList_RemoveTests { public class LinkedList_RemoveTests { private static int s_currentCharAsInt = 32; private static readonly Func<string> s_generateString = () => { char item = (char)s_currentCharAsInt; s_currentCharAsInt++; return item.ToString(); }; private static int s_currentInt = -5; private static readonly Func<int> s_generateInt = () => { int current = s_currentInt; s_currentInt++; return current; }; [Fact] public static void Remove_T() { LinkedList_T_Tests<string> helper = new LinkedList_T_Tests<string>(); helper.Remove_T(s_generateString); LinkedList_T_Tests<int> helper2 = new LinkedList_T_Tests<int>(); helper2.Remove_T(s_generateInt); } [Fact] public static void Remove_Duplicates_T() { LinkedList_T_Tests<string> helper = new LinkedList_T_Tests<string>(); helper.Remove_Duplicates_T(s_generateString); LinkedList_T_Tests<int> helper2 = new LinkedList_T_Tests<int>(); helper2.Remove_Duplicates_T(s_generateInt); } [Fact] public static void Remove_LLNode() { LinkedList_T_Tests<string> helper = new LinkedList_T_Tests<string>(); helper.Remove_LLNode(s_generateString); LinkedList_T_Tests<int> helper2 = new LinkedList_T_Tests<int>(); helper2.Remove_LLNode(s_generateInt); } [Fact] public static void Remove_Duplicates_LLNode() { LinkedList_T_Tests<string> helper = new LinkedList_T_Tests<string>(); helper.Remove_Duplicates_LLNode(s_generateString); LinkedList_T_Tests<int> helper2 = new LinkedList_T_Tests<int>(); helper2.Remove_Duplicates_LLNode(s_generateInt); } [Fact] public static void Remove_LLNode_Negative() { LinkedList_T_Tests<string> helper = new LinkedList_T_Tests<string>(); helper.Remove_LLNode_Negative(s_generateString); LinkedList_T_Tests<int> helper2 = new LinkedList_T_Tests<int>(); helper2.Remove_LLNode_Negative(s_generateInt); } [Fact] public static void RemoveFirst_Tests() { LinkedList_T_Tests<string> helper = new LinkedList_T_Tests<string>(); helper.RemoveFirst_Tests(s_generateString); LinkedList_T_Tests<int> helper2 = new LinkedList_T_Tests<int>(); helper2.RemoveFirst_Tests(s_generateInt); } [Fact] public static void RemoveFirst_Tests_Negative() { LinkedList_T_Tests<string> helper = new LinkedList_T_Tests<string>(); helper.RemoveFirst_Tests_Negative(); } [Fact] public static void RemoveLast_Tests() { LinkedList_T_Tests<string> helper = new LinkedList_T_Tests<string>(); helper.RemoveLast_Tests(s_generateString); LinkedList_T_Tests<int> helper2 = new LinkedList_T_Tests<int>(); helper2.RemoveLast_Tests(s_generateInt); } [Fact] public static void RemoveLast_Tests_Negative() { LinkedList_T_Tests<string> helper = new LinkedList_T_Tests<string>(); helper.RemoveLast_Tests_Negative(); } } /// <summary> /// Helper class that verifies some properties of the linked list. /// </summary> internal class LinkedList_T_Tests<T> { internal void Remove_T(Func<T> generateItem) { LinkedList<T> linkedList = new LinkedList<T>(); int arraySize = 16; T[] headItems, headItemsReverse, tailItems, tempItems; LinkedListNode<T> tempNode1, tempNode2, tempNode3; headItems = new T[arraySize]; tailItems = new T[arraySize]; for (int i = 0; i < arraySize; i++) { headItems[i] = generateItem(); tailItems[i] = generateItem(); } headItemsReverse = new T[arraySize]; Array.Copy(headItems, headItemsReverse, headItems.Length); Array.Reverse(headItemsReverse); //[] Call Remove an empty collection linkedList = new LinkedList<T>(); Assert.False(linkedList.Remove(headItems[0])); //"Err_1518eaid Remove retunred true with a non null " Assert.False(linkedList.Remove(default(T))); //"Err_45485eajid Remove retunred true with a null " InitialItems_Tests(linkedList, new T[0]); //[] Call Remove with an item that does not exist in the collection size=1 linkedList = new LinkedList<T>(); linkedList.AddLast(headItems[0]); Assert.False(linkedList.Remove(headItems[1])); //"Err_1188aeid Remove retunred true with a non null item " Assert.False(linkedList.Remove(default(T))); //"Err_3188eajid Remove retunred true with a null item " InitialItems_Tests(linkedList, new T[] { headItems[0] }); //[] Call Remove with an item that does not exist in the collection size=1 linkedList = new LinkedList<T>(); linkedList.AddLast(headItems[0]); tempNode1 = linkedList.First; Assert.True(linkedList.Remove(headItems[0])); //"Err_25188ehiad Remove retunred false with the head item " InitialItems_Tests(linkedList, new T[0]); VerifyRemovedNode(tempNode1, headItems[0]); //[] Call Remove with an item that does not exist in the collection size=2 linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); Assert.False(linkedList.Remove(headItems[2])); //"Err_39484ehiuad Remove retunred true with a non null item " Assert.False(linkedList.Remove(default(T))); //"Err_0548ieae Remove retunred true with a null item " InitialItems_Tests(linkedList, new T[] { headItems[0], headItems[1] }); //[] Call Remove with the Head collection size=2 linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); tempNode1 = linkedList.First; Assert.True(linkedList.Remove(headItems[0])); //"Err_3188eajid Remove retunred false with the head item " InitialItems_Tests(linkedList, new T[] { headItems[1] }); VerifyRemovedNode(tempNode1, headItems[0]); //[] Call Remove with the Tail collection size=2 linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); tempNode1 = linkedList.Last; Assert.True(linkedList.Remove(headItems[1])); //"Err_97525ehad Remove retunred false with the tail item " InitialItems_Tests(linkedList, new T[] { headItems[0] }); VerifyRemovedNode(tempNode1, headItems[1]); //[] Call Remove all the items collection size=2 linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); tempNode1 = linkedList.First; tempNode2 = linkedList.Last; Assert.True(linkedList.Remove(headItems[0])); //"Err_413882qoea Remove retunred false with the head item " Assert.True(linkedList.Remove(headItems[1])); //"Err_31288qiae Remove retunred false with the tail item " InitialItems_Tests(linkedList, new T[0]); VerifyRemovedNode(linkedList, new T[0], tempNode1, headItems[0]); VerifyRemovedNode(linkedList, new T[0], tempNode2, headItems[1]); //[] Call Remove with an item that does not exist in the collection size=3 linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); linkedList.AddLast(headItems[2]); Assert.False(linkedList.Remove(headItems[3])); //"Err_84900aeua Remove retunred true with a non null item " Assert.False(linkedList.Remove(default(T))); //"Err_5388iqiqa Remove retunred true with a null item on a empty " InitialItems_Tests(linkedList, new T[] { headItems[0], headItems[1], headItems[2] }); //[] Call Remove with the Head collection size=3 linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); linkedList.AddLast(headItems[2]); tempNode1 = linkedList.First; Assert.True(linkedList.Remove(headItems[0])); //"Err_30884qrzo Remove retunred false with the head item, " InitialItems_Tests(linkedList, new T[] { headItems[1], headItems[2] }); VerifyRemovedNode(linkedList, new T[] { headItems[1], headItems[2] }, tempNode1, headItems[0]); //[] Call Remove with the middle item collection size=3 linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); linkedList.AddLast(headItems[2]); tempNode1 = linkedList.First.Next; Assert.True(linkedList.Remove(headItems[1])); //"Err_988158quiozq Remove retunred false with the middle item " InitialItems_Tests(linkedList, new T[] { headItems[0], headItems[2] }); VerifyRemovedNode(linkedList, new T[] { headItems[0], headItems[2] }, tempNode1, headItems[1]); //[] Call Remove with the Tail collection size=3 linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); linkedList.AddLast(headItems[2]); tempNode1 = linkedList.Last; Assert.True(linkedList.Remove(headItems[2])); //"Expected to be able to remove item: " + headItems[2] + "from the list." InitialItems_Tests(linkedList, new T[] { headItems[0], headItems[1] }); VerifyRemovedNode(linkedList, new T[] { headItems[0], headItems[1] }, tempNode1, headItems[2]); //[] Call Remove all the items collection size=3 linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); linkedList.AddLast(headItems[2]); tempNode1 = linkedList.First; tempNode2 = linkedList.First.Next; tempNode3 = linkedList.Last; Assert.True(linkedList.Remove(headItems[2])); //"Err_5488oiwis Remove retunred false with the Tail item " Assert.True(linkedList.Remove(headItems[1])); //"Err_2808ajide Remove retunred false with the middle item " Assert.True(linkedList.Remove(headItems[0])); //"Err_1888ajiw Remove retunred false with the Head item " InitialItems_Tests(linkedList, new T[0]); VerifyRemovedNode(tempNode1, headItems[0]); VerifyRemovedNode(tempNode2, headItems[1]); VerifyRemovedNode(tempNode3, headItems[2]); //[] Call Remove all the items starting with the first collection size=16 linkedList = new LinkedList<T>(); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(headItems[i]); for (int i = 0; i < arraySize; ++i) { Assert.True(linkedList.Remove(headItems[i]), "Err_5688ajidi Remove to returned false index= " + i); int startIndex = i + 1; int length = arraySize - i - 1; T[] expectedItems = new T[length]; Array.Copy(headItems, startIndex, expectedItems, 0, length); InitialItems_Tests(linkedList, expectedItems); } //[] Call Remove all the items starting with the last collection size=16 linkedList = new LinkedList<T>(); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(headItems[i]); for (int i = arraySize - 1; 0 <= i; --i) { Assert.True(linkedList.Remove(headItems[i]), "Err_51888ajhid Remove to returned false index=" + 1); T[] expectedItems = new T[i]; Array.Copy(headItems, 0, expectedItems, 0, i); InitialItems_Tests(linkedList, expectedItems); } //[] Remove some items in the middle linkedList = new LinkedList<T>(); for (int i = 0; i < arraySize; ++i) linkedList.AddFirst(headItems[i]); Assert.True(linkedList.Remove(headItems[2])); //"Err_6488akod Remove 3rd item " Assert.True(linkedList.Remove(headItems[headItems.Length - 3])); //"Err_15188ajei Remove 3rd from last item " Assert.True(linkedList.Remove(headItems[1])); //"Err_1588ajoied Remove 2nd item " Assert.True(linkedList.Remove(headItems[headItems.Length - 2])); //"Err_1888ajied Remove 2nd from last item " Assert.True(linkedList.Remove(headItems[0])); //"Err_402558aide Remove first item returned false " Assert.True(linkedList.Remove(headItems[headItems.Length - 1])); //"Err_56588eajidi Remove last item returned false " //With the above remove we should have removed the first and last 3 items tempItems = new T[headItemsReverse.Length - 6]; Array.Copy(headItemsReverse, 3, tempItems, 0, headItemsReverse.Length - 6); InitialItems_Tests(linkedList, tempItems); //[] Remove an item with a value of default(T) linkedList = new LinkedList<T>(); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(headItems[i]); linkedList.AddLast(default(T)); Assert.True(linkedList.Remove(default(T))); //"Err_29829ahid Remove default(T) " InitialItems_Tests(linkedList, headItems); } internal void Remove_Duplicates_T(Func<T> generateItem) { LinkedList<T> linkedList = new LinkedList<T>(); int arraySize = 16; T[] items; LinkedListNode<T>[] nodes = new LinkedListNode<T>[arraySize * 2]; LinkedListNode<T> currentNode; int index; items = new T[arraySize]; for (int i = 0; i < arraySize; i++) { items[i] = generateItem(); } for (int i = 0; i < arraySize; ++i) linkedList.AddLast(items[i]); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(items[i]); currentNode = linkedList.First; index = 0; while (currentNode != null) { nodes[index] = currentNode; currentNode = currentNode.Next; ++index; } Assert.True(linkedList.Remove(items[2])); //"Err_58088ajode Remove 3rd item " Assert.True(linkedList.Remove(items[items.Length - 3])); //"Err_15188ajei Remove 3rd from last item " Assert.True(linkedList.Remove(items[1])); //"Err_9945aied Err_92872 Remove 2nd item " Assert.True(linkedList.Remove(items[items.Length - 2])); //"Err_1888ajied Remove 2nd from last item " Assert.True(linkedList.Remove(items[0])); //"Err_08486aiepz Remove first item returned false " Assert.True(linkedList.Remove(items[items.Length - 1])); //"Err_56588eajidi Remove last item returned false " //[] Verify that the duplicates were removed from the begining of the collection currentNode = linkedList.First; //Verify the duplicates that should have been removed for (int i = 3; i < arraySize - 3; ++i) { Assert.NotNull(currentNode); //"Err_48588ahid CurrentNode is null index= " + i Assert.Equal(currentNode, nodes[i]); //"Err_5488ahid CurrentNode is not the expected node index= " + i Assert.Equal(items[i], currentNode.Value); //"Err_16588ajide CurrentNode value index=" + i currentNode = currentNode.Next; } //Verify the duplicates that should NOT have been removed for (int i = 0; i < arraySize; ++i) { Assert.NotNull(currentNode); //"Err_5658ajidi CurrentNode is null index= " + i Assert.Equal(currentNode, nodes[arraySize + i]); //"Err_4865423aidie CurrentNode is not the expected node index= " + i Assert.Equal(items[i], currentNode.Value); //"Err_54808ajoid CurrentNode value index=" + i currentNode = currentNode.Next; } Assert.Null(currentNode); //"Err_30878ajid Expceted CurrentNode to be null after moving through entire list" } internal void Remove_LLNode(Func<T> generateItem) { LinkedList<T> linkedList = new LinkedList<T>(); int arraySize = 16; T[] headItems, tailItems, tempItems; LinkedListNode<T> tempNode1, tempNode2, tempNode3; headItems = new T[arraySize]; tailItems = new T[arraySize]; for (int i = 0; i < arraySize; i++) { headItems[i] = generateItem(); tailItems[i] = generateItem(); } //[] Call Remove with an item that exists in the collection size=1 linkedList = new LinkedList<T>(); linkedList.AddLast(headItems[0]); tempNode1 = linkedList.First; linkedList.Remove(linkedList.First); //Remove when VS Whidbey: 234648 is resolved VerifyRemovedNode(linkedList, new T[0], tempNode1, headItems[0]); InitialItems_Tests(linkedList, new T[0]); //[] Call Remove with the Head collection size=2 linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); tempNode1 = linkedList.First; linkedList.Remove(linkedList.First); //Remove when VS Whidbey: 234648 is resolved InitialItems_Tests(linkedList, new T[] { headItems[1] }); VerifyRemovedNode(tempNode1, headItems[0]); //[] Call Remove with the Tail collection size=2 linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); tempNode1 = linkedList.Last; linkedList.Remove(linkedList.Last); //Remove when VS Whidbey: 234648 is resolved InitialItems_Tests(linkedList, new T[] { headItems[0] }); VerifyRemovedNode(tempNode1, headItems[1]); //[] Call Remove all the items collection size=2 linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); tempNode1 = linkedList.First; tempNode2 = linkedList.Last; linkedList.Remove(linkedList.First); //Remove when VS Whidbey: 234648 is resolved linkedList.Remove(linkedList.Last); //Remove when VS Whidbey: 234648 is resolved InitialItems_Tests(linkedList, new T[0]); VerifyRemovedNode(linkedList, new T[0], tempNode1, headItems[0]); VerifyRemovedNode(linkedList, new T[0], tempNode2, headItems[1]); //[] Call Remove with the Head collection size=3 linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); linkedList.AddLast(headItems[2]); tempNode1 = linkedList.First; linkedList.Remove(linkedList.First); //Remove when VS Whidbey: 234648 is resolved InitialItems_Tests(linkedList, new T[] { headItems[1], headItems[2] }); VerifyRemovedNode(linkedList, new T[] { headItems[1], headItems[2] }, tempNode1, headItems[0]); //[] Call Remove with the middle item collection size=3 linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); linkedList.AddLast(headItems[2]); tempNode1 = linkedList.First.Next; linkedList.Remove(linkedList.First.Next); //Remove when VS Whidbey: 234648 is resolved InitialItems_Tests(linkedList, new T[] { headItems[0], headItems[2] }); VerifyRemovedNode(linkedList, new T[] { headItems[0], headItems[2] }, tempNode1, headItems[1]); //[] Call Remove with the Tail collection size=3 linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); linkedList.AddLast(headItems[2]); tempNode1 = linkedList.Last; linkedList.Remove(linkedList.Last); //Remove when VS Whidbey: 234648 is resolved InitialItems_Tests(linkedList, new T[] { headItems[0], headItems[1] }); VerifyRemovedNode(linkedList, new T[] { headItems[0], headItems[1] }, tempNode1, headItems[2]); //[] Call Remove all the items collection size=3 linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); linkedList.AddLast(headItems[2]); tempNode1 = linkedList.First; tempNode2 = linkedList.First.Next; tempNode3 = linkedList.Last; linkedList.Remove(linkedList.First.Next.Next); //Remove when VS Whidbey: 234648 is resolved linkedList.Remove(linkedList.First.Next); //Remove when VS Whidbey: 234648 is resolved linkedList.Remove(linkedList.First); //Remove when VS Whidbey: 234648 is resolved InitialItems_Tests(linkedList, new T[0]); VerifyRemovedNode(tempNode1, headItems[0]); VerifyRemovedNode(tempNode2, headItems[1]); VerifyRemovedNode(tempNode3, headItems[2]); //[] Call Remove all the items starting with the first collection size=16 linkedList = new LinkedList<T>(); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(headItems[i]); for (int i = 0; i < arraySize; ++i) { linkedList.Remove(linkedList.First); //Remove when VS Whidbey: 234648 is resolved int startIndex = i + 1; int length = arraySize - i - 1; T[] expectedItems = new T[length]; Array.Copy(headItems, startIndex, expectedItems, 0, length); InitialItems_Tests(linkedList, expectedItems); } //[] Call Remove all the items starting with the last collection size=16 linkedList = new LinkedList<T>(); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(headItems[i]); for (int i = arraySize - 1; 0 <= i; --i) { linkedList.Remove(linkedList.Last); //Remove when VS Whidbey: 234648 is resolved T[] expectedItems = new T[i]; Array.Copy(headItems, 0, expectedItems, 0, i); InitialItems_Tests(linkedList, expectedItems); } //[] Remove some items in the middle linkedList = new LinkedList<T>(); for (int i = 0; i < arraySize; ++i) linkedList.AddFirst(headItems[i]); linkedList.Remove(linkedList.First.Next.Next); //Remove when VS Whidbey: 234648 is resolved linkedList.Remove(linkedList.Last.Previous.Previous); //Remove when VS Whidbey: 234648 is resolved linkedList.Remove(linkedList.First.Next); //Remove when VS Whidbey: 234648 is resolved linkedList.Remove(linkedList.Last.Previous); linkedList.Remove(linkedList.First); //Remove when VS Whidbey: 234648 is resolved linkedList.Remove(linkedList.Last); //Remove when VS Whidbey: 234648 is resolved //With the above remove we should have removed the first and last 3 items T[] headItemsReverse = new T[arraySize]; Array.Copy(headItems, headItemsReverse, headItems.Length); Array.Reverse(headItemsReverse); tempItems = new T[headItemsReverse.Length - 6]; Array.Copy(headItemsReverse, 3, tempItems, 0, headItemsReverse.Length - 6); InitialItems_Tests(linkedList, tempItems); //[] Remove an item with a value of default(T) linkedList = new LinkedList<T>(); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(headItems[i]); linkedList.AddLast(default(T)); linkedList.Remove(linkedList.Last); //Remove when VS Whidbey: 234648 is resolved InitialItems_Tests(linkedList, headItems); } internal void Remove_Duplicates_LLNode(Func<T> generateItem) { LinkedList<T> linkedList = new LinkedList<T>(); int arraySize = 16; T[] items; LinkedListNode<T>[] nodes = new LinkedListNode<T>[arraySize * 2]; LinkedListNode<T> currentNode; int index; items = new T[arraySize]; for (int i = 0; i < arraySize; i++) { items[i] = generateItem(); } for (int i = 0; i < arraySize; ++i) linkedList.AddLast(items[i]); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(items[i]); currentNode = linkedList.First; index = 0; while (currentNode != null) { nodes[index] = currentNode; currentNode = currentNode.Next; ++index; } linkedList.Remove(linkedList.First.Next.Next); //Remove when VS Whidbey: 234648 is resolved linkedList.Remove(linkedList.Last.Previous.Previous); //Remove when VS Whidbey: 234648 is resolved linkedList.Remove(linkedList.First.Next); //Remove when VS Whidbey: 234648 is resolved linkedList.Remove(linkedList.Last.Previous); linkedList.Remove(linkedList.First); //Remove when VS Whidbey: 234648 is resolved linkedList.Remove(linkedList.Last); //Remove when VS Whidbey: 234648 is resolved //[] Verify that the duplicates were removed from the begining of the collection currentNode = linkedList.First; //Verify the duplicates that should have been removed for (int i = 3; i < nodes.Length - 3; ++i) { Assert.NotNull(currentNode); //"Err_48588ahid CurrentNode is null index=" + i Assert.Equal(currentNode, nodes[i]); //"Err_5488ahid CurrentNode is not the expected node index=" + i Assert.Equal(items[i % items.Length], currentNode.Value); //"Err_16588ajide CurrentNode value index=" + i currentNode = currentNode.Next; } Assert.Null(currentNode); //"Err_30878ajid Expceted CurrentNode to be null after moving through entire list" } internal void Remove_LLNode_Negative(Func<T> generateItem) { LinkedList<T> linkedList = new LinkedList<T>(); LinkedList<T> tempLinkedList = new LinkedList<T>(); T[] items; //[] Verify Null node linkedList = new LinkedList<T>(); Assert.Throws<ArgumentNullException>(() => linkedList.Remove(null)); //"Err_858ahia Expected null node to throws ArgumentNullException\n" InitialItems_Tests(linkedList, new T[0]); //[] Verify Node that is a new Node linkedList = new LinkedList<T>(); items = new T[] { generateItem() }; linkedList.AddLast(items[0]); Assert.Throws<InvalidOperationException>(() => linkedList.Remove(new LinkedListNode<T>(generateItem()))); //"Err_0568ajods Expected Node that is a new Node throws InvalidOperationException\n" InitialItems_Tests(linkedList, items); //[] Verify Node that already exists in another collection linkedList = new LinkedList<T>(); items = new T[] { generateItem(), generateItem() }; linkedList.AddLast(items[0]); linkedList.AddLast(items[1]); tempLinkedList.Clear(); tempLinkedList.AddLast(generateItem()); tempLinkedList.AddLast(generateItem()); Assert.Throws<InvalidOperationException>(() => linkedList.Remove(tempLinkedList.Last)); //"Err_98809ahied Node that already exists in another collection throws InvalidOperationException\n" InitialItems_Tests(linkedList, items); } internal void RemoveFirst_Tests(Func<T> generateItem) { LinkedList<T> linkedList = new LinkedList<T>(); int arraySize = 16; T[] headItems, tailItems; LinkedListNode<T> tempNode1, tempNode2, tempNode3; headItems = new T[arraySize]; tailItems = new T[arraySize]; for (int i = 0; i < arraySize; i++) { headItems[i] = generateItem(); tailItems[i] = generateItem(); } //[] Call RemoveHead on a collection with one item in it linkedList = new LinkedList<T>(); linkedList.AddLast(headItems[0]); tempNode1 = linkedList.First; linkedList.RemoveFirst(); InitialItems_Tests(linkedList, new T[0]); VerifyRemovedNode(tempNode1, headItems[0]); //[] Call RemoveHead on a collection with two items in it linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); tempNode1 = linkedList.First; tempNode2 = linkedList.Last; linkedList.RemoveFirst(); InitialItems_Tests(linkedList, new T[] { headItems[1] }); linkedList.RemoveFirst(); InitialItems_Tests(linkedList, new T[0]); VerifyRemovedNode(linkedList, tempNode1, headItems[0]); VerifyRemovedNode(linkedList, tempNode2, headItems[1]); //[] Call RemoveHead on a collection with three items in it linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); linkedList.AddLast(headItems[2]); tempNode1 = linkedList.First; tempNode2 = linkedList.First.Next; tempNode3 = linkedList.Last; linkedList.RemoveFirst(); InitialItems_Tests(linkedList, new T[] { headItems[1], headItems[2] }); linkedList.RemoveFirst(); InitialItems_Tests(linkedList, new T[] { headItems[2] }); linkedList.RemoveFirst(); InitialItems_Tests(linkedList, new T[0]); VerifyRemovedNode(tempNode1, headItems[0]); VerifyRemovedNode(tempNode2, headItems[1]); VerifyRemovedNode(tempNode3, headItems[2]); //[] Call RemoveHead on a collection with 16 items in it linkedList = new LinkedList<T>(); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(headItems[i]); for (int i = 0; i < arraySize; ++i) { linkedList.RemoveFirst(); int startIndex = i + 1; int length = arraySize - i - 1; T[] expectedItems = new T[length]; Array.Copy(headItems, startIndex, expectedItems, 0, length); InitialItems_Tests(linkedList, expectedItems); } //[] Mix RemoveHead and RemoveTail call linkedList = new LinkedList<T>(); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(headItems[i]); for (int i = 0; i < arraySize; ++i) { if ((i & 1) == 0) linkedList.RemoveFirst(); else linkedList.RemoveLast(); int startIndex = (i / 2) + 1; int length = arraySize - i - 1; T[] expectedItems = new T[length]; Array.Copy(headItems, startIndex, expectedItems, 0, length); InitialItems_Tests(linkedList, expectedItems); } } internal void RemoveFirst_Tests_Negative() { //[] Call RemoveHead an empty collection LinkedList<T> linkedList = new LinkedList<T>(); Assert.Throws<InvalidOperationException>(() => linkedList.RemoveFirst()); //"Expected invalidoperation exception removing from empty list." InitialItems_Tests(linkedList, new T[0]); } internal void RemoveLast_Tests(Func<T> generateItem) { LinkedList<T> linkedList = new LinkedList<T>(); int arraySize = 16; T[] headItems, tailItems; LinkedListNode<T> tempNode1, tempNode2, tempNode3; headItems = new T[arraySize]; tailItems = new T[arraySize]; for (int i = 0; i < arraySize; i++) { headItems[i] = generateItem(); tailItems[i] = generateItem(); } //[] Call RemoveHead on a collection with one item in it linkedList = new LinkedList<T>(); linkedList.AddLast(headItems[0]); tempNode1 = linkedList.Last; linkedList.RemoveLast(); InitialItems_Tests(linkedList, new T[0]); VerifyRemovedNode(tempNode1, headItems[0]); //[] Call RemoveHead on a collection with two items in it linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); tempNode1 = linkedList.Last; tempNode2 = linkedList.First; linkedList.RemoveLast(); InitialItems_Tests(linkedList, new T[] { headItems[0] }); linkedList.RemoveLast(); InitialItems_Tests(linkedList, new T[0]); VerifyRemovedNode(linkedList, tempNode1, headItems[1]); VerifyRemovedNode(linkedList, tempNode2, headItems[0]); //[] Call RemoveHead on a collection with three items in it linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); linkedList.AddLast(headItems[2]); tempNode1 = linkedList.Last; tempNode2 = linkedList.Last.Previous; tempNode3 = linkedList.First; linkedList.RemoveLast(); InitialItems_Tests(linkedList, new T[] { headItems[0], headItems[1] }); linkedList.RemoveLast(); InitialItems_Tests(linkedList, new T[] { headItems[0] }); linkedList.RemoveLast(); InitialItems_Tests(linkedList, new T[0]); VerifyRemovedNode(tempNode1, headItems[2]); VerifyRemovedNode(tempNode2, headItems[1]); VerifyRemovedNode(tempNode3, headItems[0]); //[] Call RemoveHead on a collection with 16 items in it linkedList = new LinkedList<T>(); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(headItems[i]); for (int i = 0; i < arraySize; ++i) { linkedList.RemoveLast(); int length = arraySize - i - 1; T[] expectedItems = new T[length]; Array.Copy(headItems, 0, expectedItems, 0, length); InitialItems_Tests(linkedList, expectedItems); } //[] Mix RemoveHead and RemoveTail call linkedList = new LinkedList<T>(); for (int i = 0; i < arraySize; ++i) linkedList.AddLast(headItems[i]); for (int i = 0; i < arraySize; ++i) { if ((i & 1) == 0) linkedList.RemoveFirst(); else linkedList.RemoveLast(); int startIndex = (i / 2) + 1; int length = arraySize - i - 1; T[] expectedItems = new T[length]; Array.Copy(headItems, startIndex, expectedItems, 0, length); InitialItems_Tests(linkedList, expectedItems); } } internal void RemoveLast_Tests_Negative() { LinkedList<T> linkedList = new LinkedList<T>(); Assert.Throws<InvalidOperationException>(() => linkedList.RemoveLast()); //"Expected invalidoperation exception removing from empty list." InitialItems_Tests(linkedList, new T[0]); } #region Helper Methods private void VerifyRemovedNode(LinkedListNode<T> node, T expectedValue) { LinkedList<T> tempLinkedList = new LinkedList<T>(); LinkedListNode<T> headNode, tailNode; tempLinkedList.AddLast(default(T)); tempLinkedList.AddLast(default(T)); headNode = tempLinkedList.First; tailNode = tempLinkedList.Last; Assert.Null(node.List); //"Err_298298anied Node.LinkedList returned non null" Assert.Null(node.Previous); //"Err_298298anied Node.Previous returned non null" Assert.Null(node.Next); //"Err_298298anied Node.Next returned non null" Assert.Equal(expectedValue, node.Value); //"Err_969518aheoia Node.Value" tempLinkedList.AddAfter(tempLinkedList.First, node); Assert.Equal(tempLinkedList, node.List); //"Err_7894ahioed Node.LinkedList" Assert.Equal(headNode, node.Previous); //"Err_14520aheoak Node.Previous" Assert.Equal(tailNode, node.Next); //"Err_42358aujea Node.Next" Assert.Equal(expectedValue, node.Value); //"Err_64888joqaxz Node.Value" InitialItems_Tests(tempLinkedList, new T[] { default(T), expectedValue, default(T) }); } private void VerifyRemovedNode(LinkedList<T> linkedList, LinkedListNode<T> node, T expectedValue) { LinkedListNode<T> tailNode = linkedList.Last; Assert.Null(node.List); //"Err_564898ajid Node.LinkedList returned non null" Assert.Null(node.Previous); //"Err_30808wia Node.Previous returned non null" Assert.Null(node.Next); //"Err_78280aoiea Node.Next returned non null" Assert.Equal(expectedValue, node.Value); //"Err_98234aued Node.Value" linkedList.AddLast(node); Assert.Equal(linkedList, node.List); //"Err_038369aihead Node.LinkedList" Assert.Equal(tailNode, node.Previous); //"Err_789108aiea Node.Previous" Assert.Null(node.Next); //"Err_37896riad Node.Next returned non null" linkedList.RemoveLast(); } private void VerifyRemovedNode(LinkedList<T> linkedList, T[] linkedListValues, LinkedListNode<T> node, T expectedValue) { LinkedListNode<T> tailNode = linkedList.Last; Assert.Null(node.List); //"Err_564898ajid Node.LinkedList returned non null" Assert.Null(node.Previous); //"Err_30808wia Node.Previous returned non null" Assert.Null(node.Next); //"Err_78280aoiea Node.Next returned non null" Assert.Equal(expectedValue, node.Value); //"Err_98234aued Node.Value" linkedList.AddLast(node); Assert.Equal(linkedList, node.List); //"Err_038369aihead Node.LinkedList" Assert.Equal(tailNode, node.Previous); //"Err_789108aiea Node.Previous" Assert.Null(node.Next); //"Err_37896riad Node.Next returned non null" Assert.Equal(expectedValue, node.Value); //"Err_823902jaied Node.Value" T[] expected = new T[linkedListValues.Length + 1]; Array.Copy(linkedListValues, 0, expected, 0, linkedListValues.Length); expected[linkedListValues.Length] = expectedValue; InitialItems_Tests(linkedList, expected); linkedList.RemoveLast(); } /// <summary> /// Tests the items in the list to make sure they are the same. /// </summary> private void InitialItems_Tests(LinkedList<T> collection, T[] expectedItems) { VerifyState(collection, expectedItems); VerifyGenericEnumerator(collection, expectedItems); VerifyEnumerator(collection, expectedItems); } /// <summary> /// Verifies that the tail/head properties are valid and /// can iterate through the list (backwards and forwards) to /// verify the contents of the list. /// </summary> private static void VerifyState(LinkedList<T> linkedList, T[] expectedItems) { T[] tempArray; int index; LinkedListNode<T> currentNode, previousNode, nextNode; //[] Verify Count Assert.Equal(expectedItems.Length, linkedList.Count); //"Err_0821279 List.Count" //[] Verify Head/Tail if (expectedItems.Length == 0) { Assert.Null(linkedList.First); //"Err_48928ahid Expected Head to be null\n" Assert.Null(linkedList.Last); //"Err_56418ahjidi Expected Tail to be null\n" } else if (expectedItems.Length == 1) { VerifyLinkedListNode(linkedList.First, expectedItems[0], linkedList, null, null); VerifyLinkedListNode(linkedList.Last, expectedItems[0], linkedList, null, null); } else { VerifyLinkedListNode(linkedList.First, expectedItems[0], linkedList, true, false); VerifyLinkedListNode(linkedList.Last, expectedItems[expectedItems.Length - 1], linkedList, false, true); } //[] Moving forward throught he collection starting at head currentNode = linkedList.First; previousNode = null; index = 0; while (currentNode != null) { nextNode = currentNode.Next; VerifyLinkedListNode(currentNode, expectedItems[index], linkedList, previousNode, nextNode); previousNode = currentNode; currentNode = currentNode.Next; ++index; } //[] Moving backword throught he collection starting at Tail currentNode = linkedList.Last; nextNode = null; index = 0; while (currentNode != null) { previousNode = currentNode.Previous; VerifyLinkedListNode(currentNode, expectedItems[expectedItems.Length - 1 - index], linkedList, previousNode, nextNode); nextNode = currentNode; currentNode = currentNode.Previous; ++index; } //[] Verify Contains for (int i = 0; i < expectedItems.Length; i++) { Assert.True(linkedList.Contains(expectedItems[i]), "Err_9872haid Expected Contains with item=" + expectedItems[i] + " to return true"); } //[] Verify CopyTo tempArray = new T[expectedItems.Length]; linkedList.CopyTo(tempArray, 0); for (int i = 0; i < expectedItems.Length; i++) { Assert.Equal(expectedItems[i], tempArray[i]); //"Err_0310auazp After CopyTo index=" + i.ToString() } //[] Verify Enumerator() index = 0; foreach (T item in linkedList) { Assert.Equal(expectedItems[index], item); //"Err_0310auazp Enumerator index=" + index.ToString() ++index; } } /// <summary> /// Verifies that the generic enumerator retrieves the correct items. /// </summary> private void VerifyGenericEnumerator(ICollection<T> collection, T[] expectedItems) { IEnumerator<T> enumerator = collection.GetEnumerator(); int iterations = 0; int expectedCount = expectedItems.Length; //[] Verify non deterministic behavior of current every time it is called before a call to MoveNext() has been made for (int i = 0; i < 3; i++) { try { T tempCurrent = enumerator.Current; } catch (Exception) { } } // There is a sequential order to the collection, so we're testing for that. while ((iterations < expectedCount) && enumerator.MoveNext()) { T currentItem = enumerator.Current; T tempItem; //[] Verify we have not gotten more items then we expected Assert.True(iterations < expectedCount, "Err_9844awpa More items have been returned fromt the enumerator(" + iterations + " items) than are in the expectedElements(" + expectedCount + " items)"); //[] Verify Current returned the correct value Assert.Equal(currentItem, expectedItems[iterations]); //"Err_1432pauy Current returned unexpected value at index: " + iterations //[] Verify Current always returns the same value every time it is called for (int i = 0; i < 3; i++) { tempItem = enumerator.Current; Assert.Equal(currentItem, tempItem); //"Err_8776phaw Current is returning inconsistant results" } iterations++; } Assert.Equal(expectedCount, iterations); //"Err_658805eauz Number of items to iterate through" for (int i = 0; i < 3; i++) { Assert.False(enumerator.MoveNext()); //"Err_2929ahiea Expected MoveNext to return false after" + iterations + " iterations" } //[] Verify non deterministic behavior of current every time it is called after the enumerator is positioned after the last item for (int i = 0; i < 3; i++) { try { T tempCurrent = enumerator.Current; } catch (Exception) { } } enumerator.Dispose(); } /// <summary> /// Verifies that the non-generic enumerator retrieves the correct items. /// </summary> private void VerifyEnumerator(ICollection<T> collection, T[] expectedItems) { IEnumerator enumerator = collection.GetEnumerator(); int iterations = 0; int expectedCount = expectedItems.Length; //[] Verify non deterministic behavior of current every time it is called before a call to MoveNext() has been made for (int i = 0; i < 3; i++) { try { object tempCurrent = enumerator.Current; } catch (Exception) { } } // There is no sequential order to the collection, so we're testing that all the items // in the readonlydictionary exist in the array. bool[] itemsVisited = new bool[expectedCount]; bool itemFound; while ((iterations < expectedCount) && enumerator.MoveNext()) { object currentItem = enumerator.Current; object tempItem; //[] Verify we have not gotten more items then we expected Assert.True(iterations < expectedCount, "Err_9844awpa More items have been returned fromt the enumerator(" + iterations + " items) then are in the expectedElements(" + expectedCount + " items)"); //[] Verify Current returned the correct value itemFound = false; for (int i = 0; i < itemsVisited.Length; ++i) { if (itemsVisited[i]) continue; if ((expectedItems[i] == null && currentItem == null) || (expectedItems[i] != null && expectedItems[i].Equals(currentItem))) { itemsVisited[i] = true; itemFound = true; break; } } Assert.True(itemFound, "Err_1432pauy Current returned unexpected value=" + currentItem); //[] Verify Current always returns the same value every time it is called for (int i = 0; i < 3; i++) { tempItem = enumerator.Current; Assert.Equal(currentItem, tempItem); //"Err_8776phaw Current is returning inconsistant results Current." } iterations++; } for (int i = 0; i < expectedCount; ++i) { Assert.True(itemsVisited[i], "Err_052848ahiedoi Expected Current to return true for item: " + expectedItems[i] + "index: " + i); } Assert.Equal(expectedCount, iterations); //"Err_658805eauz Number of items to iterate through" for (int i = 0; i < 3; i++) { Assert.False(enumerator.MoveNext()); //"Err_2929ahiea Expected MoveNext to return false after" + iterations + " iterations" } //[] Verify non deterministic behavior of current every time it is called after the enumerator is positioned after the last item for (int i = 0; i < 3; i++) { try { object tempCurrent = enumerator.Current; } catch (Exception) { } } } /// <summary> /// Verifies that the contents of a linkedlistnode are correct. /// </summary> private static void VerifyLinkedListNode(LinkedListNode<T> node, T expectedValue, LinkedList<T> expectedList, LinkedListNode<T> expectedPrevious, LinkedListNode<T> expectedNext) { Assert.Equal(expectedValue, node.Value); //"Err_548ajoid Node Value" Assert.Equal(expectedList, node.List); //"Err_0821279 Node List" Assert.Equal(expectedPrevious, node.Previous); //"Err_8548ajhiod Previous Node" Assert.Equal(expectedNext, node.Next); //"Err_4688anmjod Next Node" } /// <summary> /// verifies that the contents of a linkedlist node are correct. /// </summary> private static void VerifyLinkedListNode(LinkedListNode<T> node, T expectedValue, LinkedList<T> expectedList, bool expectedPreviousNull, bool expectedNextNull) { Assert.Equal(expectedValue, node.Value); //"Err_548ajoid Expected Node Value" Assert.Equal(expectedList, node.List); //"Err_0821279 Expected Node List" if (expectedPreviousNull) Assert.Null(node.Previous); //"Expected node.Previous to be null." else Assert.NotNull(node.Previous); //"Expected node.Previous not to be null" if (expectedNextNull) Assert.Null(node.Next); //"Expected node.Next to be null." else Assert.NotNull(node.Next); //"Expected node.Next not to be null" } #endregion } }
using System; using System.Runtime.InteropServices; using System.Text; namespace Vanara.PInvoke { /// <summary>Items from the WindowsCodecs.dll</summary> public static partial class WindowsCodecs { /// <summary>Application defined callback function called when codec component progress is made.</summary> /// <param name="pvData"> /// <para>Type: <c>LPVOID</c></para> /// <para>Component data passed to the callback function.</para> /// </param> /// <param name="uFrameNum"> /// <para>Type: <c>ULONG</c></para> /// <para>The current frame number.</para> /// </param> /// <param name="operation"> /// <para>Type: <c>WICProgressOperation</c></para> /// <para>The current operation the component is in.</para> /// </param> /// <param name="dblProgress"> /// <para>Type: <c>double</c></para> /// <para>The progress value. The range is 0.0 to 1.0.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this callback function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para>An operation can be canceled by returning .</para> /// <para> /// To register your callback function, query the encoder or decoder for the IWICBitmapCodecProgressNotification interface and call RegisterProgressNotification. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/win32/api/wincodec/nc-wincodec-pfnprogressnotification PFNProgressNotification // Pfnprogressnotification; HRESULT Pfnprogressnotification( LPVOID pvData, ULONG uFrameNum, WICProgressOperation operation, double // dblProgress ) {...} [PInvokeData("wincodec.h", MSDNShortId = "10dd9fbe-abff-4fc9-a3a5-7c01ecc10a7f")] public delegate HRESULT PFNProgressNotification([In] IntPtr pvData, uint uFrameNum, WICProgressOperation operation, double dblProgress); /// <summary>Obtains a IWICBitmapSource in the desired pixel format from a given <c>IWICBitmapSource</c>.</summary> /// <param name="dstFormat"> /// <para>Type: <c>REFWICPixelFormatGUID</c></para> /// <para>The pixel format to convert to.</para> /// </param> /// <param name="pISrc"> /// <para>Type: <c>IWICBitmapSource*</c></para> /// <para>The source bitmap.</para> /// </param> /// <param name="ppIDst"> /// <para>Type: <c>IWICBitmapSource**</c></para> /// <para>A pointer to the <c>null</c>-initialized destination bitmap pointer.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// If the pISrc bitmap is already in the desired format, then pISrc is copied to the destination bitmap pointer and a reference is /// added. If it is not in the desired format however, <c>WICConvertBitmapSource</c> will instantiate a dstFormat format converter /// and initialize it with pISrc. /// </remarks> // https://docs.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-wicconvertbitmapsource HRESULT WICConvertBitmapSource( // REFWICPixelFormatGUID dstFormat, IWICBitmapSource *pISrc, IWICBitmapSource **ppIDst ); [DllImport(Lib.Windowscodecs, SetLastError = false, ExactSpelling = true)] [PInvokeData("wincodec.h", MSDNShortId = "ea735296-1bfd-4175-b8c9-cb5a61ab4203")] public static extern HRESULT WICConvertBitmapSource(in Guid dstFormat, [In] IWICBitmapSource pISrc, out IWICBitmapSource ppIDst); /// <summary>Returns a IWICBitmapSource that is backed by the pixels of a Windows Graphics Device Interface (GDI) section handle.</summary> /// <param name="width"> /// <para>Type: <c>UINT</c></para> /// <para>The width of the bitmap pixels.</para> /// </param> /// <param name="height"> /// <para>Type: <c>UINT</c></para> /// <para>The height of the bitmap pixels.</para> /// </param> /// <param name="pixelFormat"> /// <para>Type: <c>REFWICPixelFormatGUID</c></para> /// <para>The pixel format of the bitmap.</para> /// </param> /// <param name="hSection"> /// <para>Type: <c>HANDLE</c></para> /// <para>The section handle. This is a file mapping object handle returned by the CreateFileMapping function.</para> /// </param> /// <param name="stride"> /// <para>Type: <c>UINT</c></para> /// <para>The byte count of each scanline.</para> /// </param> /// <param name="offset"> /// <para>Type: <c>UINT</c></para> /// <para>The offset into the section.</para> /// </param> /// <param name="ppIBitmap"> /// <para>Type: <c>IWICBitmap**</c></para> /// <para>A pointer that receives the bitmap.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// The <c>WICCreateBitmapFromSection</c> function calls the WICCreateBitmapFromSectionEx function with the desiredAccessLevel /// parameter set to <c>WICSectionAccessLevelRead</c>. /// </remarks> // https://docs.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-wiccreatebitmapfromsection HRESULT // WICCreateBitmapFromSection( UINT width, UINT height, REFWICPixelFormatGUID pixelFormat, HANDLE hSection, UINT stride, UINT // offset, IWICBitmap **ppIBitmap ); [DllImport(Lib.Windowscodecs, SetLastError = false, ExactSpelling = true)] [PInvokeData("wincodec.h", MSDNShortId = "a14022a0-7af6-4c06-9afa-4709b81efc96")] public static extern HRESULT WICCreateBitmapFromSection(uint width, uint height, in Guid pixelFormat, HSECTION hSection, uint stride, uint offset, out IWICBitmap ppIBitmap); /// <summary>Returns a IWICBitmapSource that is backed by the pixels of a Windows Graphics Device Interface (GDI) section handle.</summary> /// <param name="width"> /// <para>Type: <c>UINT</c></para> /// <para>The width of the bitmap pixels.</para> /// </param> /// <param name="height"> /// <para>Type: <c>UINT</c></para> /// <para>The height of the bitmap pixels.</para> /// </param> /// <param name="pixelFormat"> /// <para>Type: <c>REFWICPixelFormatGUID</c></para> /// <para>The pixel format of the bitmap.</para> /// </param> /// <param name="hSection"> /// <para>Type: <c>HANDLE</c></para> /// <para>The section handle. This is a file mapping object handle returned by the CreateFileMapping function.</para> /// </param> /// <param name="stride"> /// <para>Type: <c>UINT</c></para> /// <para>The byte count of each scanline.</para> /// </param> /// <param name="offset"> /// <para>Type: <c>UINT</c></para> /// <para>The offset into the section.</para> /// </param> /// <param name="desiredAccessLevel"> /// <para>Type: <c>WICSectionAccessLevel</c></para> /// <para>The desired access level.</para> /// </param> /// <param name="ppIBitmap"> /// <para>Type: <c>IWICBitmap**</c></para> /// <para>A pointer that receives the bitmap.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> // https://docs.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-wiccreatebitmapfromsectionex HRESULT // WICCreateBitmapFromSectionEx( UINT width, UINT height, REFWICPixelFormatGUID pixelFormat, HANDLE hSection, UINT stride, UINT // offset, WICSectionAccessLevel desiredAccessLevel, IWICBitmap **ppIBitmap ); [DllImport(Lib.Windowscodecs, SetLastError = false, ExactSpelling = true)] [PInvokeData("wincodec.h", MSDNShortId = "0c9892a5-c136-41f6-8161-8077afe1a9da")] public static extern HRESULT WICCreateBitmapFromSectionEx(uint width, uint height, in Guid pixelFormat, HSECTION hSection, uint stride, uint offset, WICSectionAccessLevel desiredAccessLevel, out IWICBitmap ppIBitmap); /// <summary>Obtains the short name associated with a given GUID.</summary> /// <param name="guid"> /// <para>Type: <c>REFGUID</c></para> /// <para>The GUID to retrieve the short name for.</para> /// </param> /// <param name="cchName"> /// <para>Type: <c>UINT</c></para> /// <para>The size of the wzName buffer.</para> /// </param> /// <param name="wzName"> /// <para>Type: <c>WCHAR*</c></para> /// <para>A pointer that receives the short name associated with the GUID.</para> /// </param> /// <param name="pcchActual"> /// <para>Type: <c>UINT*</c></para> /// <para>The actual size needed to retrieve the entire short name associated with the GUID.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks>Windows Imaging Component (WIC) short name mappings can be found within the following registry key:</remarks> // https://docs.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-wicmapguidtoshortname HRESULT WICMapGuidToShortName( // REFGUID guid, UINT cchName, WCHAR *wzName, UINT *pcchActual ); [DllImport(Lib.Windowscodecs, SetLastError = false, ExactSpelling = true)] [PInvokeData("wincodec.h", MSDNShortId = "ae1e4680-2c20-4a3e-b931-206d26f4d09c")] public static extern HRESULT WICMapGuidToShortName(in Guid guid, uint cchName, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder wzName, out uint pcchActual); /// <summary>Obtains the name associated with a given schema.</summary> /// <param name="guidMetadataFormat"> /// <para>Type: <c>REFGUID</c></para> /// <para>The metadata format GUID.</para> /// </param> /// <param name="pwzSchema"> /// <para>Type: <c>LPWSTR</c></para> /// <para>The URI string of the schema for which the name is to be retrieved.</para> /// </param> /// <param name="cchName"> /// <para>Type: <c>UINT</c></para> /// <para>The size of the wzName buffer.</para> /// </param> /// <param name="wzName"> /// <para>Type: <c>WCHAR*</c></para> /// <para>A pointer to a buffer that receives the schema's name.</para> /// <para>To obtain the required buffer size, call <c>WICMapSchemaToName</c> with cchName set to 0 and wzName set to <c>NULL</c>.</para> /// </param> /// <param name="pcchActual"> /// <para>Type: <c>UINT</c></para> /// <para>The actual buffer size needed to retrieve the entire schema name.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para>You can extend the schema name mapping by adding to the following registry key:</para> /// <para><c>HKEY_CLASSES_ROOT</c><c>CLSID</c><c>{FAE3D380-FEA4-4623-8C75-C6B61110B681}</c><c>Schemas</c><c>BB5ACC38-F216-4CEC-A6C5-5F6E739763A9</c><c>...</c></para> /// <para>For more information, see How to Write a WIC-Enabled Codec.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-wicmapschematoname HRESULT WICMapSchemaToName( REFGUID // guidMetadataFormat, LPWSTR pwzSchema, UINT cchName, WCHAR *wzName, UINT *pcchActual ); [DllImport(Lib.Windowscodecs, SetLastError = false, ExactSpelling = true)] [PInvokeData("wincodec.h", MSDNShortId = "6e71b75a-a542-459c-9935-b05f3ce39217")] public static extern HRESULT WICMapSchemaToName(in Guid guidMetadataFormat, [MarshalAs(UnmanagedType.LPWStr)] string pwzSchema, uint cchName, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder wzName, out uint pcchActual); /// <summary>Obtains the GUID associated with the given short name.</summary> /// <param name="wzName"> /// <para>Type: <c>const WCHAR*</c></para> /// <para>A pointer to the short name.</para> /// </param> /// <param name="pguid"> /// <para>Type: <c>GUID*</c></para> /// <para>A pointer that receives the GUID associated with the given short name.</para> /// </param> /// <returns> /// <para>Type: <c>HRESULT</c></para> /// <para>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</para> /// </returns> /// <remarks> /// <para>You can extend the short name mapping by adding to the following registry key:</para> /// <para><c>HKEY_CLASSES_ROOT</c><c>CLSID</c><c>{FAE3D380-FEA4-4623-8C75-C6B61110B681}</c><c>Namespace</c><c>...</c></para> /// <para>For more information, see How to Write a WIC-Enabled Codec.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/win32/api/wincodec/nf-wincodec-wicmapshortnametoguid HRESULT WICMapShortNameToGuid( // PCWSTR wzName, GUID *pguid ); [DllImport(Lib.Windowscodecs, SetLastError = false, ExactSpelling = true)] [PInvokeData("wincodec.h", MSDNShortId = "ceefa802-7930-4b01-b1a2-6db530032e88")] public static extern HRESULT WICMapShortNameToGuid([MarshalAs(UnmanagedType.LPWStr)] string wzName, out Guid pguid); } }
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (the "License"). // You may not use this file except in compliance with the // License. A copy of the License is located at // // http://aws.amazon.com/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, 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.Globalization; using System.IO; using System.Linq; using System.Net; using Amazon.Runtime; using ThirdParty.Json.LitJson; namespace Amazon.Util { /// <summary> /// This class can be used to discover the public address ranges for AWS. The /// information is retrieved from the publicly accessible /// https://ip-ranges.amazonaws.com/ip-ranges.json file. /// </summary> /// <remarks> /// The information in this file is generated from our internal system-of-record and /// is authoritative. You can expect it to change several times per week and should /// poll accordingly. /// </remarks> public class AWSPublicIpAddressRanges { // The known-in-use service keys; the actual keys can be extended // over time. public const string AmazonServiceKey = "AMAZON"; public const string EC2ServiceKey = "EC2"; public const string CloudFrontServiceKey = "CLOUDFRONT"; public const string Route53ServiceKey = "ROUTE53"; public const string Route53HealthChecksServiceKey = "ROUTE53_HEALTHCHECKS"; /// <summary> /// Region identifier string for ROUTE53 and CLOUDFRONT ranges /// </summary> public const string GlobalRegionIdentifier = "GLOBAL"; /// <summary> /// Collection of service keys found in the data file. /// </summary> public IEnumerable<string> ServiceKeys { get { var keyHash = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var range in AllAddressRanges) { keyHash.Add(range.Service); } return keyHash; } } /// <summary> /// The publication date and time of the file that was downloaded and parsed. /// </summary> public DateTime CreateDate { get; private set; } /// <summary> /// Collection of all public IP ranges. /// </summary> public IEnumerable<AWSPublicIpAddressRange> AllAddressRanges { get; private set; } /// <summary> /// Filtered collection of public IP ranges for the given service key /// </summary> public IEnumerable<AWSPublicIpAddressRange> AddressRangesByServiceKey(string serviceKey) { if (!AllAddressRanges.Any()) throw new InvalidOperationException("No address range data has been loaded and parsed."); return AllAddressRanges.Where(ar => ar.Service.Equals(serviceKey, StringComparison.OrdinalIgnoreCase)).ToList(); } /// <summary> /// Filtered collection of public IP ranges for the given region (us-east-1 etc) or GLOBAL. /// </summary> public IEnumerable<AWSPublicIpAddressRange> AddressRangesByRegion(string regionIdentifier) { if (!AllAddressRanges.Any()) throw new InvalidOperationException("No address range data has been loaded and parsed."); return AllAddressRanges.Where(ar => ar.Region.Equals(regionIdentifier, StringComparison.OrdinalIgnoreCase)).ToList(); } /// <summary> /// Downloads the most recent copy of the endpoint address file and /// parses it to a collection of address range objects. /// </summary> public static AWSPublicIpAddressRanges Load() { const int maxDownloadRetries = 3; var retries = 0; while (retries < maxDownloadRetries) { try { // use async calls so same code works across mobile platforms var request = WebRequest.Create(IpAddressRangeEndpoint) as HttpWebRequest; var asynResult = request.BeginGetResponse(null, null); var response = request.EndGetResponse(asynResult) as HttpWebResponse; AWSPublicIpAddressRanges instance; using (response) { using (var reader = new StreamReader(response.GetResponseStream())) { instance = Parse(reader.ReadToEnd()); } } return instance; } catch (WebException e) { retries++; if (retries == maxDownloadRetries) throw new AmazonServiceException(string.Format(CultureInfo.InvariantCulture, "Error downloading public IP address ranges file from {0}.", IpAddressRangeEndpoint), e); } var delay = (int) (Math.Pow(4, retries)*100); delay = Math.Min(delay, 30*1000); Util.AWSSDKUtils.Sleep(delay); } return null; } private static AWSPublicIpAddressRanges Parse(string fileContent) { const string createDateKey = "createDate"; const string prefixesKey = "prefixes"; const string ipPrefixKey = "ip_prefix"; const string regionKey = "region"; const string serviceKey = "service"; const string createDateFormatString = "yyyy-MM-dd-HH-mm-ss"; try { var instance = new AWSPublicIpAddressRanges(); var json = JsonMapper.ToObject(new JsonReader(fileContent)); var createdAt = (string)json[createDateKey]; instance.CreateDate = DateTime.ParseExact(createdAt, createDateFormatString, null); var parsedRanges = new List<AWSPublicIpAddressRange>(); instance.AllAddressRanges = parsedRanges; var ranges = json[prefixesKey]; if (!ranges.IsArray) throw new InvalidDataException("Expected array content for prefixes key."); parsedRanges.AddRange(from JsonData range in ranges select new AWSPublicIpAddressRange { IpPrefix = (string)range[ipPrefixKey], Region = (string)range[regionKey], Service = (string)range[serviceKey] }); return instance; } catch (Exception e) { throw new InvalidDataException("IP address ranges content in unexpected/invalid format.", e); } } private AWSPublicIpAddressRanges() { } private static readonly Uri IpAddressRangeEndpoint = new Uri("https://ip-ranges.amazonaws.com/ip-ranges.json"); } /// <summary> /// Represents the IP address range for a single region and service key. /// </summary> public class AWSPublicIpAddressRange { /// <summary> /// The public IP address range, in CIDR notation. /// </summary> public string IpPrefix { get; internal set; } /// <summary> /// The AWS region or GLOBAL for edge locations. Note that the CLOUDFRONT and ROUTE53 /// ranges are GLOBAL. /// </summary> public string Region { get; internal set; } /// <summary> /// The subset of IP address ranges. Specify AMAZON to get all IP address ranges /// (for example, the ranges in the EC2 subset are also in the AMAZON subset). Note /// that some IP address ranges are only in the AMAZON subset. /// </summary> /// <remarks> /// Valid values for the service key include "AMAZON", "EC2", "ROUTE53", /// "ROUTE53_HEALTHCHECKS", and "CLOUDFRONT." If you need to know all of /// the ranges and don't care about the service, use the "AMAZON" entries. /// The other entries are subsets of this one. Also, some of the services, /// such as S3, are represented in "AMAZON" and do not have an entry that /// is specific to the service. We plan to add additional values over time; /// code accordingly! /// </remarks> public string Service { get; internal set; } } }
using System; using System.Configuration.Provider; using System.Collections.Specialized; using System.Web.Security; using System.Text.RegularExpressions; namespace Nucleo.Security { public abstract class FormsMembershipProvider : MembershipProvider { private string _applicationName; private bool _enablePasswordReset = true; private bool _enablePasswordRetrieval = false; private int _maxInvalidPasswordAttempts = 3; private int _minRequiredNonAlphanumericCharacters = 1; private int _minRequiredPasswordLength = 6; private int _passwordAttemptWindow = 0; private MembershipPasswordFormat _passwordFormat = MembershipPasswordFormat.Clear; private string _passwordStrengthRegularExpression = ".+"; private bool _requiresQuestionAndAnswer = false; private bool _requiresUniqueEmail = true; #region " Properties " public override string ApplicationName { get { return _applicationName; } set { _applicationName = value; } } protected internal abstract string CustomDescription { get; } public override bool EnablePasswordReset { get { return _enablePasswordReset; } } public override bool EnablePasswordRetrieval { get { return _enablePasswordRetrieval; } } public override int MaxInvalidPasswordAttempts { get { return _maxInvalidPasswordAttempts; } } public override int MinRequiredNonAlphanumericCharacters { get { return _minRequiredNonAlphanumericCharacters; } } public override int MinRequiredPasswordLength { get { return _minRequiredPasswordLength; } } public override int PasswordAttemptWindow { get { return _passwordAttemptWindow; } } public override MembershipPasswordFormat PasswordFormat { get { return _passwordFormat; } } public override string PasswordStrengthRegularExpression { get { return _passwordStrengthRegularExpression; } } public override bool RequiresQuestionAndAnswer { get { return _requiresQuestionAndAnswer; } } public override bool RequiresUniqueEmail { get { return _requiresUniqueEmail; } } #endregion #region " Methods " protected virtual bool GetBooleanValue(NameValueCollection config, string key, bool defaultValue) { if (string.IsNullOrEmpty(config[key])) return defaultValue; bool boolValue; if (!bool.TryParse(config[key], out boolValue)) throw new ProviderException("Invalid value for " + key); else return boolValue; } protected virtual int GetIntegerValue(NameValueCollection config, string key, int defaultValue) { if (string.IsNullOrEmpty(config[key])) return defaultValue; int intValue; if (!int.TryParse(config[key], out intValue)) throw new ProviderException("Invalid value for " + key); else return intValue; } protected void GetPagingInformation(int pageIndex, int pageSize, int total, out int startIndex, out int maxIndex) { startIndex = (pageIndex * pageSize); maxIndex = startIndex + pageSize; if (maxIndex >= total) maxIndex = total - 1; } public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (string.IsNullOrEmpty(name)) name = "SqlMembershipProvider"; if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", this.CustomDescription); } base.Initialize(name, config); this._enablePasswordRetrieval = GetBooleanValue(config, "enablePasswordRetrieval", false); this._enablePasswordReset = GetBooleanValue(config, "enablePasswordReset", true); this._requiresQuestionAndAnswer = GetBooleanValue(config, "requiresQuestionAndAnswer", true); this._requiresUniqueEmail = GetBooleanValue(config, "requiresUniqueEmail", true); this._maxInvalidPasswordAttempts = GetIntegerValue(config, "maxInvalidPasswordAttempts", 5); this._passwordAttemptWindow = GetIntegerValue(config, "passwordAttemptWindow", 10); this._minRequiredPasswordLength = GetIntegerValue(config, "minRequiredPasswordLength", 7); this._minRequiredNonAlphanumericCharacters = GetIntegerValue(config, "minRequiredNonalphanumericCharacters", 1); this._passwordStrengthRegularExpression = config["passwordStrengthRegularExpression"]; if (this._passwordStrengthRegularExpression != null) { this._passwordStrengthRegularExpression = this._passwordStrengthRegularExpression.Trim(); if (this._passwordStrengthRegularExpression.Length > 0) { try { new Regex(this._passwordStrengthRegularExpression); } catch (ArgumentException exception1) { throw new ProviderException(exception1.Message, exception1); } } } else this._passwordStrengthRegularExpression = string.Empty; if (this._minRequiredNonAlphanumericCharacters > this._minRequiredPasswordLength) throw new Exception("The non-alpha numeric characters length must be less than or equal to the required password length."); this._applicationName = config["applicationName"]; if (string.IsNullOrEmpty(this._applicationName)) this._applicationName = "/"; string passwordFormat = config["passwordFormat"]; if (passwordFormat == null) passwordFormat = "Hashed"; if (passwordFormat == "Clear") this._passwordFormat = MembershipPasswordFormat.Clear; else if (passwordFormat == "Encrypted") this._passwordFormat = MembershipPasswordFormat.Encrypted; else if (passwordFormat == "Hashed") this._passwordFormat = MembershipPasswordFormat.Hashed; else throw new ProviderException("The format provided is an unknown format."); if ((this.PasswordFormat == MembershipPasswordFormat.Hashed) && this.EnablePasswordRetrieval) throw new ProviderException("A hashed password cannot be retrieved"); config.Remove("enablePasswordRetrieval"); config.Remove("enablePasswordReset"); config.Remove("requiresQuestionAndAnswer"); config.Remove("applicationName"); config.Remove("requiresUniqueEmail"); config.Remove("maxInvalidPasswordAttempts"); config.Remove("passwordAttemptWindow"); config.Remove("commandTimeout"); config.Remove("passwordFormat"); config.Remove("name"); config.Remove("minRequiredPasswordLength"); config.Remove("minRequiredNonalphanumericCharacters"); config.Remove("passwordStrengthRegularExpression"); if (config.Count > 0) { string unknownKey = config.GetKey(0); if (!string.IsNullOrEmpty(unknownKey)) throw new ProviderException("An unknown attribute has been specified: " + unknownKey); } } //TODO:Finish password processing method protected MembershipCreateStatus ProcessPassword(string password) { if (this.MinRequiredPasswordLength > 0 && password.Length < this.MinRequiredPasswordLength) return MembershipCreateStatus.InvalidPassword; else if (this.MinRequiredNonAlphanumericCharacters > 0) { int nonAlphaCount = 0; foreach (char letter in password) { if (!Char.IsLetter(letter) && !Char.IsNumber(letter)) nonAlphaCount++; } if (this.MinRequiredNonAlphanumericCharacters > nonAlphaCount) return MembershipCreateStatus.InvalidPassword; } else if (!string.IsNullOrEmpty(this.PasswordStrengthRegularExpression)) { if (!Regex.IsMatch(password, this.PasswordStrengthRegularExpression)) return MembershipCreateStatus.InvalidPassword; } return MembershipCreateStatus.Success; } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using AsciiConsoleUi; using AsciiConsoleUi.CompositeComponents; using AsciiUml.Commands; using AsciiUml.Geo; using AsciiUml.UI; using LanguageExt; using static AsciiUml.Extensions; namespace AsciiUml { internal static class KeyHandler { private static HandlerState handlerState = HandlerState.Normal; private static List<ICommand> Noop => new List<ICommand>(); private static List<ICommand> NoopForceRepaint => new List<ICommand> {new TmpForceRepaint()}; private static Option<List<ICommand>> OptNoop => new Option<List<ICommand>>(); public static List<ICommand> HandleKeyPress(State state, ConsoleKeyInfo key, List<List<ICommand>> commandLog, UmlWindow umlWindow) { switch (handlerState) { case HandlerState.Normal: return ControlKeys(state, key, commandLog) .IfNone(() => ShiftKeys(state, key) .IfNone(() => HandleKeys(state, key, commandLog, umlWindow) .IfNone(() => Noop))); case HandlerState.Insert: (var done, var cmds) = new KeyHandlerInsertState().HandleKeyPress(state, key, commandLog, umlWindow); if (done) { handlerState = HandlerState.Normal; cmds = cmds.Concat(Lst(new ClearTopmenuText())).ToList(); } return cmds; default: throw new ArgumentOutOfRangeException(); } } private static Option<List<ICommand>> HandleKeys(State state, ConsoleKeyInfo key, List<List<ICommand>> commandLog, UmlWindow umlWindow) { var model = state.Model; var selected = state.SelectedIndexInModel; switch (key.Key) { case ConsoleKey.UpArrow: if (state.TheCurser.Pos.Y > 0) return MoveCursorAndSelectPaintable(Vector.DeltaNorth); break; case ConsoleKey.DownArrow: if (state.TheCurser.Pos.Y < State.MaxY - 2) return MoveCursorAndSelectPaintable(Vector.DeltaSouth); break; case ConsoleKey.LeftArrow: if (state.TheCurser.Pos.X > 0) return MoveCursorAndSelectPaintable(Vector.DeltaWest); break; case ConsoleKey.RightArrow: if (state.TheCurser.Pos.X < State.MaxX - 2) return MoveCursorAndSelectPaintable(Vector.DeltaEast); break; case ConsoleKey.Spacebar: return SelectDeselect(selected, state, umlWindow); case ConsoleKey.S: PrintIdsAndLetUserSelectObject(state, umlWindow); return OptNoop; case ConsoleKey.X: case ConsoleKey.Delete: return Lst(new DeleteSelectedElement()); case ConsoleKey.H: return HelpScreen(umlWindow); case ConsoleKey.I: handlerState = HandlerState.Insert; return Lst(new SetTopmenuText("INSERTMODE> d: database | t: text | n: note | u: user")); case ConsoleKey.B: CreateBox(state, umlWindow); break; case ConsoleKey.E: EditUnderCursor(state, umlWindow); break; case ConsoleKey.C: ConnectObjects(state, umlWindow); return OptNoop; case ConsoleKey.L: return SlopedLine(state); case ConsoleKey.R: return Rotate(selected, model); case ConsoleKey.Enter: CommandMode(state, commandLog, umlWindow); return OptNoop; case ConsoleKey.OemPeriod: return ChangeStyleUnderCursor(state, umlWindow, StyleChangeKind.Next); case ConsoleKey.OemComma: return ChangeStyleUnderCursor(state, umlWindow, StyleChangeKind.Previous); } return Noop; } private static List<ICommand> ChangeStyleUnderCursor(State state, UmlWindow umlWindow, StyleChangeKind change) { var id = state.Canvas.GetOccupants(state.TheCurser.Pos); if (!id.HasValue) return Noop; var elem = state.Model.Objects.Single(x => x.Id == id); if (elem is IStyleChangeable) return Lst(new ChangeStyle(elem.Id, change)); new Popup(umlWindow, "Only works on boxes"); return Noop; } private static void CreateBox(State state, UmlWindow umlWindow) { var input = new MultilineInputForm(umlWindow, "Create box", "Text:", "", state.TheCurser.Pos) { OnCancel = () => { }, OnSubmit = text => { umlWindow.HandleCommands(Lst(new CreateBox(state.TheCurser.Pos, text))); } }; input.Focus(); } private static void EditUnderCursor(State state, UmlWindow umlWindow) { var id = state.Canvas.GetOccupants(state.TheCurser.Pos); if (!id.HasValue) return; var elem = state.Model.Objects.Single(x => x.Id == id); if (elem is IHasTextProperty property) { var text = property.Text; var input = new MultilineInputForm(umlWindow, "Edit..", "Text:", text, state.TheCurser.Pos) { OnCancel = () => { }, OnSubmit = newtext => { umlWindow.HandleCommands(Lst(new SetText(id.Value, newtext))); } }; input.Focus(); } else { new Popup(umlWindow, "Only works on labels and boxes"); } } private static List<ICommand> SlopedLine(State state) { return Lst(new CreateSlopedLine(state.TheCurser.Pos)); } private static List<ICommand> SelectDeselect(int? selected, State state, UmlWindow umlWindow) { if (selected.HasValue) return Lst(new ClearSelection()); var obj = state.Canvas.GetOccupants(state.TheCurser.Pos).ToOption() .Match(x => Lst(new SelectObject(x, false)), () => { PrintIdsAndLetUserSelectObject(state, umlWindow); return Noop; }); return obj; } private static List<ICommand> HelpScreen(UmlWindow umlWindow) { new Popup(umlWindow, @"* * **** * **** * * * * * * **** ** * **** * * * * * * * **** **** * space ................ (un)select object at cursor or choose object s .................... select an object cursor keys........... move cursor or selected object shift + cursor ....... move object under cursor r .................... rotate selected object (only text label) ctrl + cursor ........ Resize selected object (only box) b .................... Create a Box e .................... Edit element at cursor (box/label/note) c .................... Create a connection line between boxes i .................... InsertMode d .................. Create a Database n .................. Create a note t .................. Create a text label u .................. Create a user l .................... Create a free-style line ., ................... Change the style (only box) x / Del............... Delete selected object enter ................ Enter command mode Esc .................. Abort input / InsertMode ctrl+c ............... Exit program"); return Noop; } private static void ConnectObjects(State state, UmlWindow umlWindow) { state.PaintSelectableIds = true; var cmds = NoopForceRepaint; var connect = new ConnectForm(umlWindow, state.TheCurser.Pos, state.Model.Objects.Select(x=>x.Id).ToArray()) { OnCancel = () => { umlWindow.HandleCommands(cmds); state.PaintSelectableIds = false; }, OnSubmit = (from, to) => { cmds.Add(new CreateLine(from, to, LineKind.Connected)); umlWindow.HandleCommands(cmds); state.PaintSelectableIds = false; } }; connect.Focus(); } private static void CommandMode(State state, List<List<ICommand>> commandLog, UmlWindow umlWindow) { var input = new SinglelineInputForm(umlWindow, "Enter command", "commands: database, save-file, set-save-filename:", "Enter a command", 25, state.TheCurser.Pos) { OnCancel = () => { }, OnSubmit = cmd => { switch (cmd) { case "set-save-filename": var filename = new SinglelineInputForm(umlWindow, "Set state", "Filename", "Enter a filename", 20, state.TheCurser.Pos) { OnSubmit = fname => state.Config.SaveFilename = fname }; filename.Focus(); break; case "save-file": var log = Program.Serialize(commandLog); var logname = state.Config.SaveFilename + ".log"; File.WriteAllText(logname, log); var model = Program.Serialize(state.Model); File.WriteAllText(state.Config.SaveFilename, model); new Popup(umlWindow, $"file saved to \'{state.Config.SaveFilename}\'"); break; case "database": umlWindow.HandleCommands(Lst(new CreateDatabase(state.TheCurser.Pos))); break; } } }; input.Focus(); } private static List<ICommand> Rotate(int? selected, Model model) { return selected.Match(x => { if (model.Objects[x] is Label) return Lst(new RotateSelectedElement(x)); Screen.PrintErrorAndWaitKey("Only labels can be rotated"); return NoopForceRepaint; }, () => { Screen.PrintErrorAndWaitKey("Nothing is selected"); return NoopForceRepaint; }); } private static Option<List<ICommand>> ControlKeys(State state, ConsoleKeyInfo key, List<List<ICommand>> commandLog) { if ((key.Modifiers & ConsoleModifiers.Control) == 0) return Option<List<ICommand>>.None; switch (key.Key) { case ConsoleKey.UpArrow: case ConsoleKey.DownArrow: case ConsoleKey.LeftArrow: case ConsoleKey.RightArrow: return ControlCursor(state, key); case ConsoleKey.W: Program.Serialize(commandLog); return NoopForceRepaint; default: return Option<List<ICommand>>.None; } } private static Option<List<ICommand>> ControlCursor(State state, ConsoleKeyInfo key) { return SelectTemporarily(state, x => { return x.GetSelected().Match(el => { if (el is Box) switch (key.Key) { case ConsoleKey.UpArrow: return Lst(new ResizeSelectedBox(Vector.DeltaNorth)); case ConsoleKey.DownArrow: return Lst(new ResizeSelectedBox(Vector.DeltaSouth)); case ConsoleKey.LeftArrow: return Lst(new ResizeSelectedBox(Vector.DeltaWest)); case ConsoleKey.RightArrow: return Lst(new ResizeSelectedBox(Vector.DeltaEast)); } if (el is SlopedLine2) switch (key.Key) { case ConsoleKey.UpArrow: return Lst(new DragLinePixel(state.TheCurser.Pos, Vector.DeltaNorth), new MoveCursor(Vector.DeltaNorth)); case ConsoleKey.DownArrow: return Lst(new DragLinePixel(state.TheCurser.Pos, Vector.DeltaSouth), new MoveCursor(Vector.DeltaSouth)); case ConsoleKey.LeftArrow: return Lst(new DragLinePixel(state.TheCurser.Pos, Vector.DeltaWest), new MoveCursor(Vector.DeltaWest)); case ConsoleKey.RightArrow: return Lst(new DragLinePixel(state.TheCurser.Pos, Vector.DeltaEast), new MoveCursor(Vector.DeltaEast)); } return Noop; }, () => Noop).ToList(); }); } private static Option<List<ICommand>> ShiftKeys(State state, ConsoleKeyInfo key) { if ((key.Modifiers & ConsoleModifiers.Shift) == 0) return Option<List<ICommand>>.None; var commands = SelectTemporarily(state, x => { switch (key.Key) { case ConsoleKey.UpArrow: return MoveCursorAndSelectPaintable(Vector.DeltaNorth); case ConsoleKey.DownArrow: return MoveCursorAndSelectPaintable(Vector.DeltaSouth); case ConsoleKey.LeftArrow: return MoveCursorAndSelectPaintable(Vector.DeltaWest); case ConsoleKey.RightArrow: return MoveCursorAndSelectPaintable(Vector.DeltaEast); } return Noop; }); return commands; } private static List<ICommand> MoveCursorAndSelectPaintable(Coord direction) { return Lst(new MoveCursor(direction), new MoveSelectedPaintable(direction)); } private static void PrintIdsAndLetUserSelectObject(State state, UmlWindow umlWindow) { state.PaintSelectableIds = true; var cmds = NoopForceRepaint; var selectedform = new SelectObjectForm(umlWindow, state.Model.Objects.Select(x => x.Id).ToArray(), state.TheCurser.Pos) { OnCancel = () => { umlWindow.HandleCommands(cmds); state.PaintSelectableIds = false; }, OnSubmit = selected => { if (state.Model.Objects.SingleOrDefault(b => b.Id == selected) is ISelectable) cmds.Add(new SelectObject(selected, true)); umlWindow.HandleCommands(cmds); state.PaintSelectableIds = false; } }; selectedform.Focus(); } public static Option<List<ICommand>> SelectTemporarily(State state, Func<State, List<ICommand>> code) { if (state.SelectedId.HasValue) return code(state); var occupants = state.Canvas.GetOccupants(state.TheCurser.Pos); if (!occupants.HasValue) return Noop; state.SelectedId = occupants; var commands = code(state); var result = commands.Count == 0 ? Noop : Lst(new SelectObject(occupants.Value, false)) .Append(commands) .Append(Lst(new ClearSelection())) .ToList(); state.SelectedId = null; return result; } private enum HandlerState { Normal, Insert } } internal class KeyHandlerInsertState { private static Option<List<ICommand>> OptNoop => new Option<List<ICommand>>(); private static List<ICommand> Noop => new List<ICommand>(); public (bool, List<ICommand>) HandleKeyPress(State state, ConsoleKeyInfo key, List<List<ICommand>> commandLog, UmlWindow umlWindow) { switch (key.Key) { case ConsoleKey.C: return (true, Noop); case ConsoleKey.D: return (true, Lst(new CreateDatabase(state.TheCurser.Pos))); case ConsoleKey.N: CreateNote(state, umlWindow); return (true, Noop); case ConsoleKey.T: CreateText(state, umlWindow); return (true, Noop); case ConsoleKey.U: CreateUmlUser(state, umlWindow); return (true, Noop); case ConsoleKey.Escape: return (true, Noop); } return (false, Noop); } private static void CreateText(State state, UmlWindow umlWindow) { var input = new MultilineInputForm(umlWindow, "Create a label", "Text:", "", state.TheCurser.Pos) { OnCancel = () => { }, OnSubmit = text => { umlWindow.HandleCommands(Lst(new CreateLabel(state.TheCurser.Pos, text))); } }; input.Focus(); } private static void CreateNote(State state, UmlWindow umlWindow) { var input = new MultilineInputForm(umlWindow, "Create a note", "Text:", "", state.TheCurser.Pos) { OnCancel = () => { }, OnSubmit = text => { umlWindow.HandleCommands(Lst(new CreateNote(state.TheCurser.Pos, text))); } }; input.Focus(); } private static void CreateUmlUser(State state, UmlWindow umlWindow) { var input = new MultilineInputForm(umlWindow, "Text for user (optional)", "Text:", "", state.TheCurser.Pos) { OnCancel = () => { }, OnSubmit = text => { umlWindow.HandleCommands(Lst(new CreateUmlUser(state.TheCurser.Pos, text))); } }; input.Focus(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Benchmarks { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Apache.Ignite.Benchmarks.Result; /// <summary> /// Benchmark base class. /// </summary> internal abstract class BenchmarkBase { /** Result writer type: console. */ private const string ResultWriterConsole = "console"; /** Result writer type: file. */ private const string ResultWriterFile = "file"; /** Default duration. */ private const int DefaultDuration = 60; /** Default maximum errors count. */ private const int DefaultMaxErrors = 100; /** Default percentile result buckets count. */ private const int DEfaultResultBucketCount = 10000; /** Default percentile result bucket interval. */ private const int DefaultResultBucketInterval = 100; /** Default batch size. */ private const int DefaultBatchSize = 1; /** Default result wrier. */ private const string DefaultResultWriter = ResultWriterConsole; /** Start flag. */ private volatile bool _start; /** Stop flag. */ private volatile bool _stop; /** Warmup flag. */ private volatile bool _warmup = true; /** Ready threads. */ private int _readyThreads; /** Finished threads. */ private volatile int _finishedThreads; /** Descriptors. */ private volatile ICollection<BenchmarkOperationDescriptor> _descs; /** Benchmark tasks. */ private volatile ICollection<BenchmarkTask> _tasks; /** Percentile results. */ private volatile IDictionary<string, long[]> _percentiles; /** Currently completed operations. */ private long _curOps; /** Error count. */ private long _errorCount; /** Watches to count total execution time. */ private readonly Stopwatch _totalWatch = new Stopwatch(); /** Warmup barrier. */ private Barrier _barrier; /** Benchmark result writer. */ private IBenchmarkResultWriter _writer; /// <summary> /// Default constructor. /// </summary> protected BenchmarkBase() { Duration = DefaultDuration; MaxErrors = DefaultMaxErrors; ResultBucketCount = DEfaultResultBucketCount; ResultBucketInterval = DefaultResultBucketInterval; BatchSize = DefaultBatchSize; ResultWriter = DefaultResultWriter; } /// <summary> /// Run the benchmark. /// </summary> public void Run() { PrintDebug("Started benchmark: " + this); ValidateArguments(); if (ResultWriter.Equals(ResultWriterConsole, StringComparison.OrdinalIgnoreCase)) _writer = new BenchmarkConsoleResultWriter(); else _writer = new BenchmarkFileResultWriter(); OnStarted(); PrintDebug("Benchmark setup finished."); try { _descs = new List<BenchmarkOperationDescriptor>(); GetDescriptors(_descs); if (_descs.Count == 0) throw new Exception("No tasks provided for benchmark."); // Initialize writer. var opNames = new List<string>(_descs.Select(desc => desc.Name)); PrintDebug(() => { var sb = new StringBuilder("Operations: "); foreach (var opName in opNames) sb.Append(opName).Append(' '); return sb.ToString(); }); _writer.Initialize(this, opNames); PrintDebug("Initialized result writer."); // Start worker threads. _tasks = new List<BenchmarkTask>(Threads); PrintDebug("Starting worker threads: " + Threads); for (var i = 0; i < Threads; i++) { var task = new BenchmarkTask(this, _descs); _tasks.Add(task); new Thread(task.Run).Start(); } PrintDebug("Waiting worker threads to start: " + Threads); // Await for all threads to start in spin loop. while (Thread.VolatileRead(ref _readyThreads) < Threads) Thread.Sleep(10); PrintDebug("Worker threads started: " + Threads); // Start throughput writer thread. var writerThread = new Thread(new ThroughputTask(this).Run) {IsBackground = true}; writerThread.Start(); PrintDebug("Started throughput writer thread."); // Start warmup thread if needed. if (Warmup > 0) { var thread = new Thread(new WarmupTask(this, Warmup).Run) {IsBackground = true}; thread.Start(); PrintDebug("Started warmup timeout thread: " + Warmup); } else _warmup = false; _barrier = new Barrier(Threads, b => { Console.WriteLine("Warmup finished."); _totalWatch.Start(); }); // Start timeout thread if needed. if (Duration > 0) { if (Operations > 0) PrintDebug("Duration argument is ignored because operations number is set: " + Operations); else { var thread = new Thread(new TimeoutTask(this, Warmup + Duration).Run) {IsBackground = true}; thread.Start(); PrintDebug("Started duration timeout thread: " + Duration); } } // Let workers start execution. _start = true; // Await workers completion. PrintDebug("Awaiting worker threads completion."); Monitor.Enter(this); try { while (_finishedThreads < Threads) Monitor.Wait(this); } finally { Monitor.Exit(this); } PrintDebug("Worker threads completed."); } finally { OnFinished(); _totalWatch.Stop(); PrintDebug("Tear down invoked."); if (PrintThroughputInfo()) { var avgThroughput = _totalWatch.ElapsedMilliseconds == 0 ? 0 : _curOps*1000/_totalWatch.ElapsedMilliseconds; var avgLatency = _curOps == 0 ? 0 : (double) _totalWatch.ElapsedMilliseconds*Threads/_curOps; Console.WriteLine("Finishing benchmark [name=" + GetType().Name + ", time=" + _totalWatch.ElapsedMilliseconds + "ms, ops=" + _curOps + ", threads=" + Threads + ", avgThroughput=" + avgThroughput + ", avgLatency=" + string.Format("{0:0.000}ms", avgLatency) + ']'); } else { Console.WriteLine("Finishing benchmark [name=" + GetType().Name + ", time=" + _totalWatch.ElapsedMilliseconds + "ms, ops=" + Operations + ", threads=" + Threads + ']'); } } _percentiles = new Dictionary<string, long[]>(_descs.Count); foreach (var desc in _descs) _percentiles[desc.Name] = new long[ResultBucketCount]; foreach (var task in _tasks) task.CollectPercentiles(_percentiles); foreach (var percentile in _percentiles) _writer.WritePercentiles(percentile.Key, ResultBucketInterval, percentile.Value); _writer.Commit(); PrintDebug("Results committed to output writer."); } /// <summary> /// Consumes passed argument. /// </summary> /// <param name="name">Argument name.</param> /// <param name="val">Value.</param> /// <returns>True if argument was consumed.</returns> public void Configure(string name, string val) { var prop = BenchmarkUtils.GetProperty(this, name); if (prop != null) BenchmarkUtils.SetProperty(this, prop, val); } /// <summary> /// Start callback. /// </summary> protected virtual void OnStarted() { // No-op. } /// <summary> /// Warmup finished callback. Executed by each worker thread once. /// </summary> protected virtual void OnWarmupFinished() { // No-op. } /// <summary> /// Batch execution started callback. /// </summary> /// <param name="state">State.</param> protected virtual void OnBatchStarted(BenchmarkState state) { // No-op. } /// <summary> /// Batch execution finished callback. /// </summary> /// <param name="state">State.</param> /// <param name="duration">Duration.</param> /// <returns>True if this result must be counted.</returns> protected virtual bool OnBatchFinished(BenchmarkState state, long duration) { return true; } /// <summary> /// Benchmarh finished callback. /// </summary> protected virtual void OnFinished() { // No-op. } /// <returns>Flag indicating whether benchmark should print throughput information.</returns> protected virtual bool PrintThroughputInfo() { return true; } /// <summary> /// Internal arguments validation routine. /// </summary> /// <returns>True if base class must validate common arguments, false otherwise.</returns> protected virtual bool ValidateArgumentsEx() { return true; } /// <summary> /// Print debug to console. /// </summary> /// <param name="msg">Message</param> protected void PrintDebug(string msg) { if (Debug) Console.WriteLine("[DEBUG] " + Thread.CurrentThread.ManagedThreadId + ": " + msg); } /// <summary> /// Print debug to console. /// </summary> /// <param name="msgFunc">Message delegate.</param> protected void PrintDebug(Func<string> msgFunc) { if (Debug) PrintDebug(msgFunc.Invoke()); } /// <summary> /// Add operation descriptors. /// </summary> /// <param name="descs">Collection where operation descriptors must be added.</param> protected abstract void GetDescriptors(ICollection<BenchmarkOperationDescriptor> descs); /// <summary> /// Invoked when single thread is ready to actual execution. /// </summary> private void OnThreadReady() { Interlocked.Increment(ref _readyThreads); } /// <summary> /// Invoked when single thread finished execution. /// </summary> private void OnThreadFinished() { Monitor.Enter(this); try { // ReSharper disable once NonAtomicCompoundOperator _finishedThreads++; Monitor.PulseAll(this); } finally { Monitor.Exit(this); } PrintDebug("Worker thread finished."); } /// <summary> /// Validate arguments. /// </summary> private void ValidateArguments() { if (ValidateArgumentsEx()) { if (Threads <= 0) throw new Exception("Threads must be positive: " + Threads); if (Warmup < 0) throw new Exception("Warmup cannot be negative: " + Warmup); if (Duration < 0) throw new Exception("Duration cannot be negative: " + Duration); if (BatchSize <= 0) throw new Exception("BatchSize must be positive: " + BatchSize); if (MaxErrors < 0) throw new Exception("MaxErrors cannot be negative: " + MaxErrors); if (ResultWriter == null || !ResultWriter.Equals(ResultWriterConsole, StringComparison.OrdinalIgnoreCase) && !ResultWriter.Equals(ResultWriterFile, StringComparison.OrdinalIgnoreCase)) throw new Exception("Invalid ResultWriter: " + ResultWriter); if (ResultWriter.Equals(ResultWriterFile, StringComparison.OrdinalIgnoreCase) && ResultFolder == null) throw new Exception("ResultFolder must be set for file result writer."); if (ResultBucketCount <= 0) throw new Exception("ResultBucketCount must be positive: " + ResultBucketCount); if (ResultBucketInterval <= 0) throw new Exception("ResultBucketInterval must be positive: " + ResultBucketInterval); } } /// <summary> /// Get current throughput across all currenlty running threads. /// </summary> /// <returns>Current throughput.</returns> private IDictionary<string, Tuple<long, long>> GetCurrentThroughput() { var total = new Dictionary<string, Tuple<long, long>>(_descs.Count); foreach (var desc in _descs) total[desc.Name] = new Tuple<long, long>(0, 0); foreach (var task in _tasks) task.CollectThroughput(total); return total; } /** <inheritDoc /> */ public override string ToString() { var sb = new StringBuilder(GetType().Name).Append('['); var first = true; var props = BenchmarkUtils.GetProperties(this); foreach (var prop in props) { if (first) first = false; else sb.Append(", "); sb.Append(prop.Name).Append('=').Append(prop.GetValue(this, null)); } sb.Append(']'); return sb.ToString(); } /* COMMON PUBLIC PROPERTIES. */ /// <summary> /// Amount of worker threads. /// </summary> public int Threads { get; set; } /// <summary> /// Warmup duration in secnods. /// </summary> public int Warmup { get; set; } /// <summary> /// Duration in seconds. /// </summary> public int Duration { get; set; } /// <summary> /// Maximum amount of operations to perform. /// </summary> public int Operations { get; set; } /// <summary> /// Single measurement batch size. /// </summary> public int BatchSize { get; set; } /// <summary> /// Maximum amount of errors before benchmark exits. /// </summary> public int MaxErrors { get; set; } /// <summary> /// Debug flag. /// </summary> public bool Debug { get; set; } /// <summary> /// Result writer type. /// </summary> public string ResultWriter { get; set; } /// <summary> /// Result output folder. /// </summary> public string ResultFolder { get; set; } /// <summary> /// Percentile result buckets count. /// </summary> public int ResultBucketCount { get; set; } /// <summary> /// Percnetile result bucket interval in microseconds. /// </summary> public long ResultBucketInterval { get; set; } /* INNER CLASSES. */ /// <summary> /// Benchmark worker task. /// </summary> private class BenchmarkTask { /** Benchmark. */ private readonly BenchmarkBase _benchmark; /** Descriptors. */ private readonly BenchmarkOperationDescriptor[] _descs; /** Results. */ private readonly IDictionary<string, Result> _results; /** Stop watch. */ private readonly Stopwatch _watch = new Stopwatch(); /** Benchmark state. */ private readonly BenchmarkState _state; /// <summary> /// Constructor. /// </summary> /// <param name="benchmark">Benchmark.</param> /// <param name="descList">Descriptor list.</param> public BenchmarkTask(BenchmarkBase benchmark, ICollection<BenchmarkOperationDescriptor> descList) { _benchmark = benchmark; _state = new BenchmarkState(); _results = new Dictionary<string, Result>(descList.Count); var totalWeight = 0; var ticksPerSlot = benchmark.ResultBucketInterval*Stopwatch.Frequency/1000000; if (ticksPerSlot == 0) throw new Exception("Too low bucket interval: " + benchmark.ResultBucketInterval); foreach (var desc in descList) { _results[desc.Name] = new Result(benchmark.ResultBucketCount, ticksPerSlot); totalWeight += desc.Weight; } _descs = new BenchmarkOperationDescriptor[totalWeight]; var idx = 0; foreach (var desc in descList) { for (var i = 0; i < desc.Weight; i++) _descs[idx++] = desc; } } /// <summary> /// Task routine. /// </summary> public void Run() { try { _benchmark.OnThreadReady(); _benchmark.PrintDebug("Worker thread ready."); while (!_benchmark._start) Thread.Sleep(10); _benchmark.PrintDebug("Worker thread started benchmark execution."); var warmupIteration = true; long maxDur = 0; long maxOps = _benchmark.Operations; while (!_benchmark._stop) { if (warmupIteration && !_benchmark._warmup) { warmupIteration = false; _benchmark.OnWarmupFinished(); _state.StopWarmup(); _benchmark._barrier.SignalAndWait(); } if (!warmupIteration) { if (maxOps > 0 && Interlocked.Read(ref _benchmark._curOps) > maxOps) break; } var desc = _descs.Length == 1 ? _descs[0] : _descs[BenchmarkUtils.GetRandomInt(_descs.Length)]; var res = true; _benchmark.OnBatchStarted(_state); _watch.Start(); try { for (var i = 0; i < _benchmark.BatchSize; i++) { desc.Operation(_state); _state.IncrementCounter(); } if (!warmupIteration) Interlocked.Add(ref _benchmark._curOps, _benchmark.BatchSize); } catch (Exception e) { Console.WriteLine("Exception: " + e); res = false; if (_benchmark.MaxErrors > 0 && Interlocked.Increment(ref _benchmark._errorCount) > _benchmark.MaxErrors) { lock (_benchmark) { Console.WriteLine("Benchmark is stopped due to too much errors: " + _benchmark.MaxErrors); Environment.Exit(-1); } } } finally { _watch.Stop(); var curDur = _watch.ElapsedTicks; if (res) res = _benchmark.OnBatchFinished(_state, curDur); _state.Reset(); if (curDur > maxDur) { maxDur = curDur; _benchmark.PrintDebug("The longest execution [warmup=" + warmupIteration + ", dur(nsec)=" + maxDur*1000000000/Stopwatch.Frequency + ']'); } _watch.Reset(); if (!warmupIteration && res) _results[desc.Name].Add(curDur); } } } finally { _benchmark.PrintDebug("Worker thread stopped."); _benchmark.OnThreadFinished(); } } /// <summary> /// Collect throughput for the current task. /// </summary> /// <param name="total">Total result.</param> public void CollectThroughput(IDictionary<string, Tuple<long, long>> total) { foreach (var result in _results) { var old = total[result.Key]; total[result.Key] = new Tuple<long, long>(old.Item1 + result.Value.Duration, old.Item2 + result.Value.OpCount); } } /// <summary> /// Collect percnetiles for the current task. /// </summary> /// <param name="total"></param> public void CollectPercentiles(IDictionary<string, long[]> total) { foreach (var result in _results) { var arr = total[result.Key]; for (var i = 0; i < arr.Length; i++) arr[i] += result.Value.Slots[i]; } } } /// <summary> /// Timeout task to stop execution. /// </summary> private class TimeoutTask { /** Benchmark. */ private readonly BenchmarkBase _benchmark; /** Duration. */ private readonly long _dur; /// <summary> /// Constructor. /// </summary> /// <param name="benchmark">Benchmark.</param> /// <param name="dur">Duration.</param> public TimeoutTask(BenchmarkBase benchmark, long dur) { _benchmark = benchmark; _dur = dur; } /// <summary> /// Task routine. /// </summary> public void Run() { try { Thread.Sleep(TimeSpan.FromSeconds(_dur)); } finally { _benchmark._stop = true; } } } /// <summary> /// Warmup task to clear warmup flag. /// </summary> private class WarmupTask { /** Benchmark. */ private readonly BenchmarkBase _benchmark; /** Duration. */ private readonly long _dur; /// <summary> /// Constructor. /// </summary> /// <param name="benchmark">Benchmark.</param> /// <param name="dur">Duration.</param> public WarmupTask(BenchmarkBase benchmark, long dur) { _benchmark = benchmark; _dur = dur; } /// <summary> /// Task routine. /// </summary> public void Run() { try { Thread.Sleep(TimeSpan.FromSeconds(_dur)); } finally { _benchmark._warmup = false; } } } /// <summary> /// Throughput write task. /// </summary> private class ThroughputTask { /** Benchmark. */ private readonly BenchmarkBase _benchmark; /** Last recorded result. */ private IDictionary<string, Tuple<long, long>> _lastResults; /// <summary> /// Constructor. /// </summary> /// <param name="benchmark">Benchmark.</param> public ThroughputTask(BenchmarkBase benchmark) { _benchmark = benchmark; } public void Run() { while (!_benchmark._stop) { Thread.Sleep(1000); if (_benchmark._start && !_benchmark._warmup) { var results = _benchmark.GetCurrentThroughput(); if (_benchmark._finishedThreads > 0) return; // Threads are stopping, do not collect any more. foreach (var pair in results) { Tuple<long, long> old; if (_lastResults != null && _lastResults.TryGetValue(pair.Key, out old)) _benchmark._writer.WriteThroughput(pair.Key, pair.Value.Item1 - old.Item1, pair.Value.Item2 - old.Item2); else _benchmark._writer.WriteThroughput(pair.Key, pair.Value.Item1, pair.Value.Item2); } _lastResults = results; } } } } /// <summary> /// Benchmark result. Specific for each operation. /// </summary> private class Result { /** Slots. */ public readonly long[] Slots; /** Slot duration in ticks. */ private readonly long _slotDuration; /** Total operations count. */ public long OpCount; /** Total duration. */ public long Duration; /// <summary> /// Constructor. /// </summary> /// <param name="slotCnt">Slot count.</param> /// <param name="slotDuration">Slot duration in ticks.</param> public Result(long slotCnt, long slotDuration) { Slots = new long[slotCnt]; _slotDuration = slotDuration; } /// <summary> /// Add result. /// </summary> /// <param name="curDur">Current duration in ticks.</param> public void Add(long curDur) { var idx = (int) (curDur/_slotDuration); if (idx >= Slots.Length) idx = Slots.Length - 1; Slots[idx] += 1; OpCount++; Duration += curDur; } } } }
// *********************************************************************** // Copyright (c) 2008-2014 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal.Builders { /// <summary> /// NUnitTestCaseBuilder is a utility class used by attributes /// that build test cases. /// </summary> public class NUnitTestCaseBuilder { private readonly Randomizer _randomizer = Randomizer.CreateRandomizer(); private readonly TestNameGenerator _nameGenerator; /// <summary> /// Constructs an <see cref="NUnitTestCaseBuilder"/> /// </summary> public NUnitTestCaseBuilder() { _nameGenerator = new TestNameGenerator(); } /// <summary> /// Builds a single NUnitTestMethod, either as a child of the fixture /// or as one of a set of test cases under a ParameterizedTestMethodSuite. /// </summary> /// <param name="method">The MethodInfo from which to construct the TestMethod</param> /// <param name="parentSuite">The suite or fixture to which the new test will be added</param> /// <param name="parms">The ParameterSet to be used, or null</param> public TestMethod BuildTestMethod(IMethodInfo method, Test parentSuite, TestCaseParameters parms) { var testMethod = new TestMethod(method, parentSuite) { Seed = _randomizer.Next() }; CheckTestMethodAttributes(testMethod); CheckTestMethodSignature(testMethod, parms); if (parms == null || parms.Arguments == null) testMethod.ApplyAttributesToTest(method.MethodInfo); // NOTE: After the call to CheckTestMethodSignature, the Method // property of testMethod may no longer be the same as the // original MethodInfo, so we don't use it here. string prefix = testMethod.Method.TypeInfo.FullName; // Needed to give proper full name to test in a parameterized fixture. // Without this, the arguments to the fixture are not included. if (parentSuite != null) prefix = parentSuite.FullName; if (parms != null) { parms.ApplyToTest(testMethod); if (parms.TestName != null) { // The test is simply for efficiency testMethod.Name = parms.TestName.Contains("{") ? new TestNameGenerator(parms.TestName).GetDisplayName(testMethod, parms.OriginalArguments) : parms.TestName; } else if (parms.ArgDisplayNames != null) { testMethod.Name = testMethod.Name + '(' + string.Join(", ", parms.ArgDisplayNames) + ')'; } else { testMethod.Name = _nameGenerator.GetDisplayName(testMethod, parms.OriginalArguments); } } else { testMethod.Name = _nameGenerator.GetDisplayName(testMethod, null); } testMethod.FullName = prefix + "." + testMethod.Name; return testMethod; } #region Helper Methods /// <summary> /// Checks to see if we have valid combinations of attributes. /// </summary> /// <param name="testMethod">The TestMethod to be checked. If it /// is found to be non-runnable, it will be modified.</param> /// <returns>True if the method signature is valid, false if not</returns> private static bool CheckTestMethodAttributes(TestMethod testMethod) { if (testMethod.Method.MethodInfo.GetAttributes<IRepeatTest>(true).Length > 1) return MarkAsNotRunnable(testMethod, "Multiple attributes that repeat a test may cause issues."); return true; } /// <summary> /// Helper method that checks the signature of a TestMethod and /// any supplied parameters to determine if the test is valid. /// /// Currently, NUnitTestMethods are required to be public, /// non-abstract methods, either static or instance, /// returning void. They may take arguments but the values must /// be provided or the TestMethod is not considered runnable. /// /// Methods not meeting these criteria will be marked as /// non-runnable and the method will return false in that case. /// </summary> /// <param name="testMethod">The TestMethod to be checked. If it /// is found to be non-runnable, it will be modified.</param> /// <param name="parms">Parameters to be used for this test, or null</param> /// <returns>True if the method signature is valid, false if not</returns> /// <remarks> /// The return value is no longer used internally, but is retained /// for testing purposes. /// </remarks> private static bool CheckTestMethodSignature(TestMethod testMethod, TestCaseParameters parms) { if (testMethod.Method.IsAbstract) return MarkAsNotRunnable(testMethod, "Method is abstract"); if (!testMethod.Method.IsPublic) return MarkAsNotRunnable(testMethod, "Method is not public"); IParameterInfo[] parameters; parameters = testMethod.Method.GetParameters(); int minArgsNeeded = 0; foreach (var parameter in parameters) { // IsOptional is supported since .NET 1.1 if (!parameter.IsOptional) minArgsNeeded++; } int maxArgsNeeded = parameters.Length; object[] arglist = null; int argsProvided = 0; if (parms != null) { testMethod.parms = parms; testMethod.RunState = parms.RunState; arglist = parms.Arguments; if (arglist != null) argsProvided = arglist.Length; if (testMethod.RunState != RunState.Runnable) return false; } ITypeInfo returnType = testMethod.Method.ReturnType; #if ASYNC if (AsyncToSyncAdapter.IsAsyncOperation(testMethod.Method.MethodInfo)) { if (returnType.IsType(typeof(void))) return MarkAsNotRunnable(testMethod, "Async test method must have non-void return type"); var returnsGenericTask = returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(System.Threading.Tasks.Task<>); if (returnsGenericTask && (parms == null || !parms.HasExpectedResult)) return MarkAsNotRunnable(testMethod, "Async test method must have non-generic Task return type when no result is expected"); if (!returnsGenericTask && parms != null && parms.HasExpectedResult) return MarkAsNotRunnable(testMethod, "Async test method must have Task<T> return type when a result is expected"); } else #endif if (returnType.IsType(typeof(void))) { if (parms != null && parms.HasExpectedResult) return MarkAsNotRunnable(testMethod, "Method returning void cannot have an expected result"); } else if (parms == null || !parms.HasExpectedResult) return MarkAsNotRunnable(testMethod, "Method has non-void return value, but no result is expected"); if (argsProvided > 0 && maxArgsNeeded == 0) return MarkAsNotRunnable(testMethod, "Arguments provided for method with no parameters"); if (argsProvided == 0 && minArgsNeeded > 0) return MarkAsNotRunnable(testMethod, "No arguments were provided"); if (argsProvided < minArgsNeeded) return MarkAsNotRunnable(testMethod, string.Format("Not enough arguments provided, provide at least {0} arguments.", minArgsNeeded)); if (argsProvided > maxArgsNeeded) return MarkAsNotRunnable(testMethod, string.Format("Too many arguments provided, provide at most {0} arguments.", maxArgsNeeded)); if (testMethod.Method.IsGenericMethodDefinition && arglist != null) { Type[] typeArguments; if (!new GenericMethodHelper(testMethod.Method.MethodInfo).TryGetTypeArguments(arglist, out typeArguments)) return MarkAsNotRunnable(testMethod, "Unable to determine type arguments for method"); testMethod.Method = testMethod.Method.MakeGenericMethod(typeArguments); parameters = testMethod.Method.GetParameters(); } if (parms != null && parms.TestName != null && parms.TestName.Trim() == "") return MarkAsNotRunnable(testMethod, "Test name cannot be all white-space or empty."); if (arglist != null && parameters != null) TypeHelper.ConvertArgumentList(arglist, parameters); return true; } private static bool MarkAsNotRunnable(TestMethod testMethod, string reason) { testMethod.MakeInvalid(reason); return false; } #endregion } }
// Copyright CommonsForNET. // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; namespace Commons.Utils { public class ChromiumBase64Codec { private static char CHARPAD = '='; private static uint BADCHAR = 0x01FFFFFF; private static readonly char[] e0 = { 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'D', 'D', 'D', 'D', 'E', 'E', 'E', 'E', 'F', 'F', 'F', 'F', 'G', 'G', 'G', 'G', 'H', 'H', 'H', 'H', 'I', 'I', 'I', 'I', 'J', 'J', 'J', 'J', 'K', 'K', 'K', 'K', 'L', 'L', 'L', 'L', 'M', 'M', 'M', 'M', 'N', 'N', 'N', 'N', 'O', 'O', 'O', 'O', 'P', 'P', 'P', 'P', 'Q', 'Q', 'Q', 'Q', 'R', 'R', 'R', 'R', 'S', 'S', 'S', 'S', 'T', 'T', 'T', 'T', 'U', 'U', 'U', 'U', 'V', 'V', 'V', 'V', 'W', 'W', 'W', 'W', 'X', 'X', 'X', 'X', 'Y', 'Y', 'Y', 'Y', 'Z', 'Z', 'Z', 'Z', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'd', 'd', 'd', 'd', 'e', 'e', 'e', 'e', 'f', 'f', 'f', 'f', 'g', 'g', 'g', 'g', 'h', 'h', 'h', 'h', 'i', 'i', 'i', 'i', 'j', 'j', 'j', 'j', 'k', 'k', 'k', 'k', 'l', 'l', 'l', 'l', 'm', 'm', 'm', 'm', 'n', 'n', 'n', 'n', 'o', 'o', 'o', 'o', 'p', 'p', 'p', 'p', 'q', 'q', 'q', 'q', 'r', 'r', 'r', 'r', 's', 's', 's', 's', 't', 't', 't', 't', 'u', 'u', 'u', 'u', 'v', 'v', 'v', 'v', 'w', 'w', 'w', 'w', 'x', 'x', 'x', 'x', 'y', 'y', 'y', 'y', 'z', 'z', 'z', 'z', '0', '0', '0', '0', '1', '1', '1', '1', '2', '2', '2', '2', '3', '3', '3', '3', '4', '4', '4', '4', '5', '5', '5', '5', '6', '6', '6', '6', '7', '7', '7', '7', '8', '8', '8', '8', '9', '9', '9', '9', '+', '+', '+', '+', '/', '/', '/', '/' }; private static readonly char[] e1 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; private static readonly char[] e2 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; private static readonly uint[] d0 = { 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x000000f8, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x000000fc, 0x000000d0, 0x000000d4, 0x000000d8, 0x000000dc, 0x000000e0, 0x000000e4, 0x000000e8, 0x000000ec, 0x000000f0, 0x000000f4, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x00000000, 0x00000004, 0x00000008, 0x0000000c, 0x00000010, 0x00000014, 0x00000018, 0x0000001c, 0x00000020, 0x00000024, 0x00000028, 0x0000002c, 0x00000030, 0x00000034, 0x00000038, 0x0000003c, 0x00000040, 0x00000044, 0x00000048, 0x0000004c, 0x00000050, 0x00000054, 0x00000058, 0x0000005c, 0x00000060, 0x00000064, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x00000068, 0x0000006c, 0x00000070, 0x00000074, 0x00000078, 0x0000007c, 0x00000080, 0x00000084, 0x00000088, 0x0000008c, 0x00000090, 0x00000094, 0x00000098, 0x0000009c, 0x000000a0, 0x000000a4, 0x000000a8, 0x000000ac, 0x000000b0, 0x000000b4, 0x000000b8, 0x000000bc, 0x000000c0, 0x000000c4, 0x000000c8, 0x000000cc, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff }; private static readonly uint[] d1 = { 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x0000e003, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x0000f003, 0x00004003, 0x00005003, 0x00006003, 0x00007003, 0x00008003, 0x00009003, 0x0000a003, 0x0000b003, 0x0000c003, 0x0000d003, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x00000000, 0x00001000, 0x00002000, 0x00003000, 0x00004000, 0x00005000, 0x00006000, 0x00007000, 0x00008000, 0x00009000, 0x0000a000, 0x0000b000, 0x0000c000, 0x0000d000, 0x0000e000, 0x0000f000, 0x00000001, 0x00001001, 0x00002001, 0x00003001, 0x00004001, 0x00005001, 0x00006001, 0x00007001, 0x00008001, 0x00009001, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x0000a001, 0x0000b001, 0x0000c001, 0x0000d001, 0x0000e001, 0x0000f001, 0x00000002, 0x00001002, 0x00002002, 0x00003002, 0x00004002, 0x00005002, 0x00006002, 0x00007002, 0x00008002, 0x00009002, 0x0000a002, 0x0000b002, 0x0000c002, 0x0000d002, 0x0000e002, 0x0000f002, 0x00000003, 0x00001003, 0x00002003, 0x00003003, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff }; private static uint[] d2 = { 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x00800f00, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x00c00f00, 0x00000d00, 0x00400d00, 0x00800d00, 0x00c00d00, 0x00000e00, 0x00400e00, 0x00800e00, 0x00c00e00, 0x00000f00, 0x00400f00, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x00000000, 0x00400000, 0x00800000, 0x00c00000, 0x00000100, 0x00400100, 0x00800100, 0x00c00100, 0x00000200, 0x00400200, 0x00800200, 0x00c00200, 0x00000300, 0x00400300, 0x00800300, 0x00c00300, 0x00000400, 0x00400400, 0x00800400, 0x00c00400, 0x00000500, 0x00400500, 0x00800500, 0x00c00500, 0x00000600, 0x00400600, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x00800600, 0x00c00600, 0x00000700, 0x00400700, 0x00800700, 0x00c00700, 0x00000800, 0x00400800, 0x00800800, 0x00c00800, 0x00000900, 0x00400900, 0x00800900, 0x00c00900, 0x00000a00, 0x00400a00, 0x00800a00, 0x00c00a00, 0x00000b00, 0x00400b00, 0x00800b00, 0x00c00b00, 0x00000c00, 0x00400c00, 0x00800c00, 0x00c00c00, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff }; private static readonly uint[] d3 = { 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x003e0000, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x003f0000, 0x00340000, 0x00350000, 0x00360000, 0x00370000, 0x00380000, 0x00390000, 0x003a0000, 0x003b0000, 0x003c0000, 0x003d0000, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x00000000, 0x00010000, 0x00020000, 0x00030000, 0x00040000, 0x00050000, 0x00060000, 0x00070000, 0x00080000, 0x00090000, 0x000a0000, 0x000b0000, 0x000c0000, 0x000d0000, 0x000e0000, 0x000f0000, 0x00100000, 0x00110000, 0x00120000, 0x00130000, 0x00140000, 0x00150000, 0x00160000, 0x00170000, 0x00180000, 0x00190000, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x001a0000, 0x001b0000, 0x001c0000, 0x001d0000, 0x001e0000, 0x001f0000, 0x00200000, 0x00210000, 0x00220000, 0x00230000, 0x00240000, 0x00250000, 0x00260000, 0x00270000, 0x00280000, 0x00290000, 0x002a0000, 0x002b0000, 0x002c0000, 0x002d0000, 0x002e0000, 0x002f0000, 0x00300000, 0x00310000, 0x00320000, 0x00330000, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff }; public static string Encode(byte[] bytes) { if (bytes == null) { return null; } byte t1, t2, t3; var len = bytes.Length; var i = 0; var num = len / 3 * 4; if (len % 3 != 0) { num += 4; } var str = new char[num]; var index = 0; if (len > 2) { for (; i < len - 2; i+=3) { t1 = bytes[i]; t2 = bytes[i + 1]; t3 = bytes[i + 2]; str[index++] = e0[t1]; str[index++] = e1[((t1 & 0x03) << 4) | ((t2 >> 4) & 0x0F)]; str[index++] = e2[((t2 & 0x0F) << 2) | ((t3 >> 6) & 0x03)]; str[index++] = e2[t3]; } } switch (len - i) { case 1: t1 = bytes[i]; str[index++] = e0[t1]; str[index++] = e1[(t1 & 0x03) << 4]; str[index++] = CHARPAD; str[index++] = CHARPAD; break; case 2: t1 = bytes[i]; t2 = bytes[i + 1]; str[index++] = e0[t1]; str[index++] = e1[((t1 & 0x03) << 4) | ((t2>>4) & 0x0F)]; str[index++] = e2[(t2 & 0x0F) << 2]; str[index++] = CHARPAD; break; default: break; } return new string(str); } public static byte[] Decode(string str) { if (string.IsNullOrEmpty(str)) { return null; } var len = str.Length; if (len == 0) { return new byte[0]; } /* * if padding is used, then the message must be at least * 4 chars and be a multiple of 4 */ if (len < 4 || (len % 4 != 0)) { throw new FormatException("The Base64 string format is incorrect."); } /* there can be at most 2 pad chars at the end */ if (str[len - 1] == CHARPAD) { len--; if (str[len - 1] == CHARPAD) { len--; } } int i; var leftover = len % 4; var chunks = (leftover == 0) ? len / 4 - 1 : len / 4; int size = 0; switch (leftover) { case 0: size = len/4*3; break; case 1: break; case 2: size = len/4*3 + 1; break; case 3:; size = len/4*3 + 2; break; default: break; } var byteArray = new byte[size]; uint x = 0; var y = 0; var pos = 0; for (i = 0; i < chunks; ++i, y += 4) { x = d0[str[y]] | d1[str[y + 1]] | d2[str[y + 2]] | d3[str[y + 3]]; if (x >= BADCHAR) { throw new FormatException("The base 64 string format is incorrect"); } byteArray[pos++] = (byte) (x & 0xFF); byteArray[pos++] = (byte) ((x >> 8) & 0xFF); byteArray[pos++] = (byte) (x >> 16); } switch (leftover) { case 0: x = d0[str[y]] | d1[str[y + 1]] | d2[str[y + 2]] | d3[str[y + 3]]; if (x >= BADCHAR) { throw new FormatException("The base 64 string format is incorrect"); } byteArray[pos++] = (byte) (x & 0xFF); byteArray[pos++] = (byte) ((x >> 8) & 0xFF); byteArray[pos++] = (byte) (x >> 16); break; case 1: /* with padding this is an impossible case */ break; case 2: // * case 2, 1 output byte */ x = d0[str[y]] | d1[str[y + 1]]; byteArray[pos++] = (byte) (x & 0xFF); break; default: /* case 3, 2 output bytes */ x = d0[str[y]] | d1[str[y + 1]] | d2[str[y + 2]]; /* 0x3c */ byteArray[pos++] = (byte) (x & 0xFF); byteArray[pos++] = (byte) ((x >> 8) & 0xFF); break; } if (x >= BADCHAR) throw new FormatException(); return byteArray; } } }
namespace java.net { [global::MonoJavaBridge.JavaClass()] public partial class DatagramSocket : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected DatagramSocket(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public virtual void close() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.DatagramSocket.staticClass, "close", "()V", ref global::java.net.DatagramSocket._m0); } private static global::MonoJavaBridge.MethodId _m1; public virtual void send(java.net.DatagramPacket arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.DatagramSocket.staticClass, "send", "(Ljava/net/DatagramPacket;)V", ref global::java.net.DatagramSocket._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int Port { get { return getPort(); } } private static global::MonoJavaBridge.MethodId _m2; public virtual int getPort() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.net.DatagramSocket.staticClass, "getPort", "()I", ref global::java.net.DatagramSocket._m2); } public new global::java.nio.channels.DatagramChannel Channel { get { return getChannel(); } } private static global::MonoJavaBridge.MethodId _m3; public virtual global::java.nio.channels.DatagramChannel getChannel() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.net.DatagramSocket.staticClass, "getChannel", "()Ljava/nio/channels/DatagramChannel;", ref global::java.net.DatagramSocket._m3) as java.nio.channels.DatagramChannel; } private static global::MonoJavaBridge.MethodId _m4; public virtual void connect(java.net.SocketAddress arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.DatagramSocket.staticClass, "connect", "(Ljava/net/SocketAddress;)V", ref global::java.net.DatagramSocket._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m5; public virtual void connect(java.net.InetAddress arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.DatagramSocket.staticClass, "connect", "(Ljava/net/InetAddress;I)V", ref global::java.net.DatagramSocket._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m6; public virtual bool isClosed() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.net.DatagramSocket.staticClass, "isClosed", "()Z", ref global::java.net.DatagramSocket._m6); } public new bool Broadcast { get { return getBroadcast(); } set { setBroadcast(value); } } private static global::MonoJavaBridge.MethodId _m7; public virtual bool getBroadcast() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.net.DatagramSocket.staticClass, "getBroadcast", "()Z", ref global::java.net.DatagramSocket._m7); } private static global::MonoJavaBridge.MethodId _m8; public virtual void bind(java.net.SocketAddress arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.DatagramSocket.staticClass, "bind", "(Ljava/net/SocketAddress;)V", ref global::java.net.DatagramSocket._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m9; public virtual void disconnect() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.DatagramSocket.staticClass, "disconnect", "()V", ref global::java.net.DatagramSocket._m9); } private static global::MonoJavaBridge.MethodId _m10; public virtual bool isConnected() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.net.DatagramSocket.staticClass, "isConnected", "()Z", ref global::java.net.DatagramSocket._m10); } public new global::java.net.SocketAddress LocalSocketAddress { get { return getLocalSocketAddress(); } } private static global::MonoJavaBridge.MethodId _m11; public virtual global::java.net.SocketAddress getLocalSocketAddress() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.net.DatagramSocket.staticClass, "getLocalSocketAddress", "()Ljava/net/SocketAddress;", ref global::java.net.DatagramSocket._m11) as java.net.SocketAddress; } private static global::MonoJavaBridge.MethodId _m12; public virtual void setReceiveBufferSize(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.DatagramSocket.staticClass, "setReceiveBufferSize", "(I)V", ref global::java.net.DatagramSocket._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int ReceiveBufferSize { get { return getReceiveBufferSize(); } set { setReceiveBufferSize(value); } } private static global::MonoJavaBridge.MethodId _m13; public virtual int getReceiveBufferSize() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.net.DatagramSocket.staticClass, "getReceiveBufferSize", "()I", ref global::java.net.DatagramSocket._m13); } private static global::MonoJavaBridge.MethodId _m14; public virtual void setSoTimeout(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.DatagramSocket.staticClass, "setSoTimeout", "(I)V", ref global::java.net.DatagramSocket._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int SoTimeout { get { return getSoTimeout(); } set { setSoTimeout(value); } } private static global::MonoJavaBridge.MethodId _m15; public virtual int getSoTimeout() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.net.DatagramSocket.staticClass, "getSoTimeout", "()I", ref global::java.net.DatagramSocket._m15); } private static global::MonoJavaBridge.MethodId _m16; public virtual void setSendBufferSize(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.DatagramSocket.staticClass, "setSendBufferSize", "(I)V", ref global::java.net.DatagramSocket._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int SendBufferSize { get { return getSendBufferSize(); } set { setSendBufferSize(value); } } private static global::MonoJavaBridge.MethodId _m17; public virtual int getSendBufferSize() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.net.DatagramSocket.staticClass, "getSendBufferSize", "()I", ref global::java.net.DatagramSocket._m17); } public new global::java.net.SocketAddress RemoteSocketAddress { get { return getRemoteSocketAddress(); } } private static global::MonoJavaBridge.MethodId _m18; public virtual global::java.net.SocketAddress getRemoteSocketAddress() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.net.DatagramSocket.staticClass, "getRemoteSocketAddress", "()Ljava/net/SocketAddress;", ref global::java.net.DatagramSocket._m18) as java.net.SocketAddress; } private static global::MonoJavaBridge.MethodId _m19; public virtual bool isBound() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.net.DatagramSocket.staticClass, "isBound", "()Z", ref global::java.net.DatagramSocket._m19); } public new global::java.net.InetAddress InetAddress { get { return getInetAddress(); } } private static global::MonoJavaBridge.MethodId _m20; public virtual global::java.net.InetAddress getInetAddress() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.net.DatagramSocket.staticClass, "getInetAddress", "()Ljava/net/InetAddress;", ref global::java.net.DatagramSocket._m20) as java.net.InetAddress; } public new global::java.net.InetAddress LocalAddress { get { return getLocalAddress(); } } private static global::MonoJavaBridge.MethodId _m21; public virtual global::java.net.InetAddress getLocalAddress() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.net.DatagramSocket.staticClass, "getLocalAddress", "()Ljava/net/InetAddress;", ref global::java.net.DatagramSocket._m21) as java.net.InetAddress; } public new int LocalPort { get { return getLocalPort(); } } private static global::MonoJavaBridge.MethodId _m22; public virtual int getLocalPort() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.net.DatagramSocket.staticClass, "getLocalPort", "()I", ref global::java.net.DatagramSocket._m22); } private static global::MonoJavaBridge.MethodId _m23; public virtual void setTrafficClass(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.DatagramSocket.staticClass, "setTrafficClass", "(I)V", ref global::java.net.DatagramSocket._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int TrafficClass { get { return getTrafficClass(); } set { setTrafficClass(value); } } private static global::MonoJavaBridge.MethodId _m24; public virtual int getTrafficClass() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.net.DatagramSocket.staticClass, "getTrafficClass", "()I", ref global::java.net.DatagramSocket._m24); } private static global::MonoJavaBridge.MethodId _m25; public virtual void setReuseAddress(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.DatagramSocket.staticClass, "setReuseAddress", "(Z)V", ref global::java.net.DatagramSocket._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new bool ReuseAddress { get { return getReuseAddress(); } set { setReuseAddress(value); } } private static global::MonoJavaBridge.MethodId _m26; public virtual bool getReuseAddress() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.net.DatagramSocket.staticClass, "getReuseAddress", "()Z", ref global::java.net.DatagramSocket._m26); } private static global::MonoJavaBridge.MethodId _m27; public virtual void receive(java.net.DatagramPacket arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.DatagramSocket.staticClass, "receive", "(Ljava/net/DatagramPacket;)V", ref global::java.net.DatagramSocket._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m28; public virtual void setBroadcast(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.DatagramSocket.staticClass, "setBroadcast", "(Z)V", ref global::java.net.DatagramSocket._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public static global::java.net.DatagramSocketImplFactory DatagramSocketImplFactory { set { setDatagramSocketImplFactory(value); } } private static global::MonoJavaBridge.MethodId _m29; public static void setDatagramSocketImplFactory(java.net.DatagramSocketImplFactory arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.DatagramSocket._m29.native == global::System.IntPtr.Zero) global::java.net.DatagramSocket._m29 = @__env.GetStaticMethodIDNoThrow(global::java.net.DatagramSocket.staticClass, "setDatagramSocketImplFactory", "(Ljava/net/DatagramSocketImplFactory;)V"); @__env.CallStaticVoidMethod(java.net.DatagramSocket.staticClass, global::java.net.DatagramSocket._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m30; public DatagramSocket(java.net.SocketAddress arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.DatagramSocket._m30.native == global::System.IntPtr.Zero) global::java.net.DatagramSocket._m30 = @__env.GetMethodIDNoThrow(global::java.net.DatagramSocket.staticClass, "<init>", "(Ljava/net/SocketAddress;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.net.DatagramSocket.staticClass, global::java.net.DatagramSocket._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m31; public DatagramSocket() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.DatagramSocket._m31.native == global::System.IntPtr.Zero) global::java.net.DatagramSocket._m31 = @__env.GetMethodIDNoThrow(global::java.net.DatagramSocket.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.net.DatagramSocket.staticClass, global::java.net.DatagramSocket._m31); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m32; protected DatagramSocket(java.net.DatagramSocketImpl arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.DatagramSocket._m32.native == global::System.IntPtr.Zero) global::java.net.DatagramSocket._m32 = @__env.GetMethodIDNoThrow(global::java.net.DatagramSocket.staticClass, "<init>", "(Ljava/net/DatagramSocketImpl;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.net.DatagramSocket.staticClass, global::java.net.DatagramSocket._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m33; public DatagramSocket(int arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.DatagramSocket._m33.native == global::System.IntPtr.Zero) global::java.net.DatagramSocket._m33 = @__env.GetMethodIDNoThrow(global::java.net.DatagramSocket.staticClass, "<init>", "(I)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.net.DatagramSocket.staticClass, global::java.net.DatagramSocket._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m34; public DatagramSocket(int arg0, java.net.InetAddress arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.DatagramSocket._m34.native == global::System.IntPtr.Zero) global::java.net.DatagramSocket._m34 = @__env.GetMethodIDNoThrow(global::java.net.DatagramSocket.staticClass, "<init>", "(ILjava/net/InetAddress;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.net.DatagramSocket.staticClass, global::java.net.DatagramSocket._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } static DatagramSocket() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.net.DatagramSocket.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/net/DatagramSocket")); } } }
/* * Vericred API * * Vericred's API allows you to search for Health Plans that a specific doctor accepts. ## Getting Started Visit our [Developer Portal](https://developers.vericred.com) to create an account. Once you have created an account, you can create one Application for Production and another for our Sandbox (select the appropriate Plan when you create the Application). ## SDKs Our API follows standard REST conventions, so you can use any HTTP client to integrate with us. You will likely find it easier to use one of our [autogenerated SDKs](https://github.com/vericred/?query=vericred-), which we make available for several common programming languages. ## Authentication To authenticate, pass the API Key you created in the Developer Portal as a `Vericred-Api-Key` header. `curl -H 'Vericred-Api-Key: YOUR_KEY' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"` ## Versioning Vericred's API default to the latest version. However, if you need a specific version, you can request it with an `Accept-Version` header. The current version is `v3`. Previous versions are `v1` and `v2`. `curl -H 'Vericred-Api-Key: YOUR_KEY' -H 'Accept-Version: v2' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"` ## Pagination Endpoints that accept `page` and `per_page` parameters are paginated. They expose four additional fields that contain data about your position in the response, namely `Total`, `Per-Page`, `Link`, and `Page` as described in [RFC-5988](https://tools.ietf.org/html/rfc5988). For example, to display 5 results per page and view the second page of a `GET` to `/networks`, your final request would be `GET /networks?....page=2&per_page=5`. ## Sideloading When we return multiple levels of an object graph (e.g. `Provider`s and their `State`s we sideload the associated data. In this example, we would provide an Array of `State`s and a `state_id` for each provider. This is done primarily to reduce the payload size since many of the `Provider`s will share a `State` ``` { providers: [{ id: 1, state_id: 1}, { id: 2, state_id: 1 }], states: [{ id: 1, code: 'NY' }] } ``` If you need the second level of the object graph, you can just match the corresponding id. ## Selecting specific data All endpoints allow you to specify which fields you would like to return. This allows you to limit the response to contain only the data you need. For example, let's take a request that returns the following JSON by default ``` { provider: { id: 1, name: 'John', phone: '1234567890', field_we_dont_care_about: 'value_we_dont_care_about' }, states: [{ id: 1, name: 'New York', code: 'NY', field_we_dont_care_about: 'value_we_dont_care_about' }] } ``` To limit our results to only return the fields we care about, we specify the `select` query string parameter for the corresponding fields in the JSON document. In this case, we want to select `name` and `phone` from the `provider` key, so we would add the parameters `select=provider.name,provider.phone`. We also want the `name` and `code` from the `states` key, so we would add the parameters `select=states.name,staes.code`. The id field of each document is always returned whether or not it is requested. Our final request would be `GET /providers/12345?select=provider.name,provider.phone,states.name,states.code` The response would be ``` { provider: { id: 1, name: 'John', phone: '1234567890' }, states: [{ id: 1, name: 'New York', code: 'NY' }] } ``` ## Benefits summary format Benefit cost-share strings are formatted to capture: * Network tiers * Compound or conditional cost-share * Limits on the cost-share * Benefit-specific maximum out-of-pocket costs **Example #1** As an example, we would represent [this Summary of Benefits &amp; Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/33602TX0780032.pdf) as: * **Hospital stay facility fees**: - Network Provider: `$400 copay/admit plus 20% coinsurance` - Out-of-Network Provider: `$1,500 copay/admit plus 50% coinsurance` - Vericred's format for this benefit: `In-Network: $400 before deductible then 20% after deductible / Out-of-Network: $1,500 before deductible then 50% after deductible` * **Rehabilitation services:** - Network Provider: `20% coinsurance` - Out-of-Network Provider: `50% coinsurance` - Limitations & Exceptions: `35 visit maximum per benefit period combined with Chiropractic care.` - Vericred's format for this benefit: `In-Network: 20% after deductible / Out-of-Network: 50% after deductible | limit: 35 visit(s) per Benefit Period` **Example #2** In [this other Summary of Benefits &amp; Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/40733CA0110568.pdf), the **specialty_drugs** cost-share has a maximum out-of-pocket for in-network pharmacies. * **Specialty drugs:** - Network Provider: `40% coinsurance up to a $500 maximum for up to a 30 day supply` - Out-of-Network Provider `Not covered` - Vericred's format for this benefit: `In-Network: 40% after deductible, up to $500 per script / Out-of-Network: 100%` **BNF** Here's a description of the benefits summary string, represented as a context-free grammar: ``` <cost-share> ::= <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> <tier-limit> "/" <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> "|" <benefit-limit> <tier> ::= "In-Network:" | "In-Network-Tier-2:" | "Out-of-Network:" <opt-num-prefix> ::= "first" <num> <unit> | "" <unit> ::= "day(s)" | "visit(s)" | "exam(s)" | "item(s)" <value> ::= <ddct_moop> | <copay> | <coinsurance> | <compound> | "unknown" | "Not Applicable" <compound> ::= <copay> <deductible> "then" <coinsurance> <deductible> | <copay> <deductible> "then" <copay> <deductible> | <coinsurance> <deductible> "then" <coinsurance> <deductible> <copay> ::= "$" <num> <coinsurace> ::= <num> "%" <ddct_moop> ::= <copay> | "Included in Medical" | "Unlimited" <opt-per-unit> ::= "per day" | "per visit" | "per stay" | "" <deductible> ::= "before deductible" | "after deductible" | "" <tier-limit> ::= ", " <limit> | "" <benefit-limit> ::= <limit> | "" ``` * * OpenAPI spec version: 1.0.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Reflection; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace IO.Vericred.Client { /// <summary> /// Represents a set of configuration settings /// </summary> public class Configuration { /// <summary> /// Initializes a new instance of the Configuration class with different settings /// </summary> /// <param name="apiClient">Api client</param> /// <param name="defaultHeader">Dictionary of default HTTP header</param> /// <param name="username">Username</param> /// <param name="password">Password</param> /// <param name="accessToken">accessToken</param> /// <param name="apiKey">Dictionary of API key</param> /// <param name="apiKeyPrefix">Dictionary of API key prefix</param> /// <param name="tempFolderPath">Temp folder path</param> /// <param name="dateTimeFormat">DateTime format string</param> /// <param name="timeout">HTTP connection timeout (in milliseconds)</param> /// <param name="userAgent">HTTP user agent</param> public Configuration(ApiClient apiClient = null, Dictionary<String, String> defaultHeader = null, string username = null, string password = null, string accessToken = null, Dictionary<String, String> apiKey = null, Dictionary<String, String> apiKeyPrefix = null, string tempFolderPath = null, string dateTimeFormat = null, int timeout = 100000, string userAgent = "Swagger-Codegen/0.0.6/csharp" ) { setApiClientUsingDefault(apiClient); Username = username; Password = password; AccessToken = accessToken; UserAgent = userAgent; if (defaultHeader != null) DefaultHeader = defaultHeader; if (apiKey != null) ApiKey = apiKey; if (apiKeyPrefix != null) ApiKeyPrefix = apiKeyPrefix; TempFolderPath = tempFolderPath; DateTimeFormat = dateTimeFormat; Timeout = timeout; } /// <summary> /// Initializes a new instance of the Configuration class. /// </summary> /// <param name="apiClient">Api client.</param> public Configuration(ApiClient apiClient) { setApiClientUsingDefault(apiClient); } /// <summary> /// Version of the package. /// </summary> /// <value>Version of the package.</value> public const string Version = "0.0.6"; /// <summary> /// Gets or sets the default Configuration. /// </summary> /// <value>Configuration.</value> public static Configuration Default = new Configuration(); /// <summary> /// Default creation of exceptions for a given method name and response object /// </summary> public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) => { int status = (int) response.StatusCode; if (status >= 400) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.Content), response.Content); if (status == 0) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.ErrorMessage), response.ErrorMessage); return null; }; /// <summary> /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. /// </summary> /// <value>Timeout.</value> public int Timeout { get { return ApiClient.RestClient.Timeout; } set { if (ApiClient != null) ApiClient.RestClient.Timeout = value; } } /// <summary> /// Gets or sets the default API client for making HTTP calls. /// </summary> /// <value>The API client.</value> public ApiClient ApiClient; /// <summary> /// Set the ApiClient using Default or ApiClient instance. /// </summary> /// <param name="apiClient">An instance of ApiClient.</param> /// <returns></returns> public void setApiClientUsingDefault (ApiClient apiClient = null) { if (apiClient == null) { if (Default != null && Default.ApiClient == null) Default.ApiClient = new ApiClient(); ApiClient = Default != null ? Default.ApiClient : new ApiClient(); } else { if (Default != null && Default.ApiClient == null) Default.ApiClient = apiClient; ApiClient = apiClient; } } private Dictionary<String, String> _defaultHeaderMap = new Dictionary<String, String>(); /// <summary> /// Gets or sets the default header. /// </summary> public Dictionary<String, String> DefaultHeader { get { return _defaultHeaderMap; } set { _defaultHeaderMap = value; } } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> public void AddDefaultHeader(string key, string value) { _defaultHeaderMap[key] = value; } /// <summary> /// Add Api Key Header. /// </summary> /// <param name="key">Api Key name.</param> /// <param name="value">Api Key value.</param> /// <returns></returns> public void AddApiKey(string key, string value) { ApiKey[key] = value; } /// <summary> /// Sets the API key prefix. /// </summary> /// <param name="key">Api Key name.</param> /// <param name="value">Api Key value.</param> public void AddApiKeyPrefix(string key, string value) { ApiKeyPrefix[key] = value; } /// <summary> /// Gets or sets the HTTP user agent. /// </summary> /// <value>Http user agent.</value> public String UserAgent { get; set; } /// <summary> /// Gets or sets the username (HTTP basic authentication). /// </summary> /// <value>The username.</value> public String Username { get; set; } /// <summary> /// Gets or sets the password (HTTP basic authentication). /// </summary> /// <value>The password.</value> public String Password { get; set; } /// <summary> /// Gets or sets the access token for OAuth2 authentication. /// </summary> /// <value>The access token.</value> public String AccessToken { get; set; } /// <summary> /// Gets or sets the API key based on the authentication name. /// </summary> /// <value>The API key.</value> public Dictionary<String, String> ApiKey = new Dictionary<String, String>(); /// <summary> /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. /// </summary> /// <value>The prefix of the API key.</value> public Dictionary<String, String> ApiKeyPrefix = new Dictionary<String, String>(); /// <summary> /// Get the API key with prefix. /// </summary> /// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param> /// <returns>API key with prefix.</returns> public string GetApiKeyWithPrefix (string apiKeyIdentifier) { var apiKeyValue = ""; ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue); var apiKeyPrefix = ""; if (ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) return apiKeyPrefix + " " + apiKeyValue; else return apiKeyValue; } private string _tempFolderPath = Path.GetTempPath(); /// <summary> /// Gets or sets the temporary folder path to store the files downloaded from the server. /// </summary> /// <value>Folder path.</value> public String TempFolderPath { get { return _tempFolderPath; } set { if (String.IsNullOrEmpty(value)) { _tempFolderPath = value; return; } // create the directory if it does not exist if (!Directory.Exists(value)) Directory.CreateDirectory(value); // check if the path contains directory separator at the end if (value[value.Length - 1] == Path.DirectorySeparatorChar) _tempFolderPath = value; else _tempFolderPath = value + Path.DirectorySeparatorChar; } } private const string ISO8601_DATETIME_FORMAT = "o"; private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; /// <summary> /// Gets or sets the the date time format used when serializing in the ApiClient /// By default, it's set to ISO 8601 - "o", for others see: /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx /// No validation is done to ensure that the string you're providing is valid /// </summary> /// <value>The DateTimeFormat string</value> public String DateTimeFormat { get { return _dateTimeFormat; } set { if (string.IsNullOrEmpty(value)) { // Never allow a blank or null string, go back to the default _dateTimeFormat = ISO8601_DATETIME_FORMAT; return; } // Caution, no validation when you choose date time format other than ISO 8601 // Take a look at the above links _dateTimeFormat = value; } } /// <summary> /// Returns a string with essential information for debugging. /// </summary> public static String ToDebugReport() { String report = "C# SDK (IO.Vericred) Debug Report:\n"; report += " OS: " + Environment.OSVersion + "\n"; report += " .NET Framework Version: " + Assembly .GetExecutingAssembly() .GetReferencedAssemblies() .Where(x => x.Name == "System.Core").First().Version.ToString() + "\n"; report += " Version of the API: 1.0.0\n"; report += " SDK Package Version: 0.0.6\n"; return report; } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Xml; using System.IO; using System.Drawing; using System.Drawing.Imaging; using System.Collections; using System.Collections.Specialized; using System.Threading; using System.Net; namespace fyiReporting.RDL { ///<summary> /// Represents an image. Source of image can from database, external or embedded. ///</summary> [Serializable] internal class Image : ReportItem { ImageSourceEnum _ImageSource; // Identifies the source of the image: Expression _Value; // See Source. Expected datatype is string or // binary, depending on Source. If the Value is // null, no image is displayed. Expression _MIMEType; // (string) An expression, the value of which is the // MIMEType for the image. // Valid values are: image/bmp, image/jpeg, // image/gif, image/png, image/x-png // Required if Source = Database. Ignored otherwise. ImageSizingEnum _Sizing; // Defines the behavior if the image does not fit within the specified size. bool _ConstantImage; // true if Image is a constant at runtime internal Image(ReportDefn r, ReportLink p, XmlNode xNode):base(r,p,xNode) { _ImageSource=ImageSourceEnum.Unknown; _Value=null; _MIMEType=null; _Sizing=ImageSizingEnum.AutoSize; _ConstantImage = false; // Loop thru all the child nodes foreach(XmlNode xNodeLoop in xNode.ChildNodes) { if (xNodeLoop.NodeType != XmlNodeType.Element) continue; switch (xNodeLoop.Name) { case "Source": _ImageSource = fyiReporting.RDL.ImageSource.GetStyle(xNodeLoop.InnerText); break; case "Value": _Value = new Expression(r, this, xNodeLoop, ExpressionType.Variant); break; case "MIMEType": _MIMEType = new Expression(r, this, xNodeLoop, ExpressionType.String); break; case "Sizing": _Sizing = ImageSizing.GetStyle(xNodeLoop.InnerText, OwnerReport.rl); break; default: if (ReportItemElement(xNodeLoop)) // try at ReportItem level break; // don't know this element - log it OwnerReport.rl.LogError(4, "Unknown Image element " + xNodeLoop.Name + " ignored."); break; } } if (_ImageSource==ImageSourceEnum.Unknown) OwnerReport.rl.LogError(8, "Image requires a Source element."); if (_Value == null) OwnerReport.rl.LogError(8, "Image requires the Value element."); } // Handle parsing of function in final pass override internal void FinalPass() { base.FinalPass(); _Value.FinalPass(); if (_MIMEType != null) _MIMEType.FinalPass(); _ConstantImage = this.IsConstant(); return; } // Returns true if the image and style remain constant at runtime bool IsConstant() { if (_Value.IsConstant()) { if (_MIMEType == null || _MIMEType.IsConstant()) { // if (this.Style == null || this.Style.ConstantStyle) // return true; return true; // ok if style changes } } return false; } override internal void Run(IPresent ip, Row row) { base.Run(ip, row); string mtype=null; Stream strm=null; try { strm = GetImageStream(ip.Report(), row, out mtype); ip.Image(this, row, mtype, strm); } catch { // image failed to load; continue processing } finally { if (strm != null) strm.Close(); } return; } override internal void RunPage(Pages pgs, Row row) { Report r = pgs.Report; bool bHidden = IsHidden(r, row); WorkClass wc = GetWC(r); string mtype=null; Stream strm=null; System.Drawing.Image im=null; SetPagePositionBegin(pgs); if (bHidden) { PageImage pi = new PageImage(ImageFormat.Jpeg, null, 0, 0); this.SetPagePositionAndStyle(r, pi, row); SetPagePositionEnd(pgs, pi.Y + pi.H); return; } if (wc.PgImage != null) { // have we already generated this one // reuse most of the work; only position will likely change PageImage pi = new PageImage(wc.PgImage.ImgFormat, wc.PgImage.ImageData, wc.PgImage.SamplesW, wc.PgImage.SamplesH); pi.Name = wc.PgImage.Name; // this is name it will be shared under pi.Sizing = this._Sizing; this.SetPagePositionAndStyle(r, pi, row); pgs.CurrentPage.AddObject(pi); SetPagePositionEnd(pgs, pi.Y + pi.H); return; } try { strm = GetImageStream(r, row, out mtype); if (strm == null) { r.rl.LogError(4, string.Format("Unable to load image {0}.", this.Name.Nm)); return; } im = System.Drawing.Image.FromStream(strm); int height = im.Height; int width = im.Width; MemoryStream ostrm = new MemoryStream(); // 140208AJM Better JPEG Encoding ImageFormat imf; // if (mtype.ToLower() == "image/jpeg") //TODO: how do we get png to work // imf = ImageFormat.Jpeg; // else imf = ImageFormat.Jpeg; System.Drawing.Imaging.ImageCodecInfo[] info; info = ImageCodecInfo.GetImageEncoders(); EncoderParameters encoderParameters; encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, ImageQualityManager.EmbeddedImageQuality); System.Drawing.Imaging.ImageCodecInfo codec = null; for (int i = 0; i < info.Length; i++) { if (info[i].FormatDescription == "JPEG") { codec = info[i]; break; } } im.Save(ostrm, codec, encoderParameters); // im.Save(ostrm, imf, encoderParameters); //END 140208AJM byte[] ba = ostrm.ToArray(); ostrm.Close(); PageImage pi = new PageImage(imf, ba, width, height); pi.Sizing = this._Sizing; this.SetPagePositionAndStyle(r, pi, row); pgs.CurrentPage.AddObject(pi); if (_ConstantImage) { wc.PgImage = pi; // create unique name; PDF generation uses this to optimize the saving of the image only once pi.Name = "pi" + Interlocked.Increment(ref Parser.Counter).ToString(); // create unique name } SetPagePositionEnd(pgs, pi.Y + pi.H); } catch (Exception e) { // image failed to load, continue processing r.rl.LogError(4, "Image load failed. " + e.Message); } finally { if (strm != null) strm.Close(); if (im != null) im.Dispose(); } return; } Stream GetImageStream(Report rpt, Row row, out string mtype) { mtype=null; Stream strm=null; try { switch (this.ImageSource) { case ImageSourceEnum.Database: if (_MIMEType == null) return null; mtype = _MIMEType.EvaluateString(rpt, row); object o = _Value.Evaluate(rpt, row); strm = new MemoryStream((byte[]) o); break; case ImageSourceEnum.Embedded: string name = _Value.EvaluateString(rpt, row); EmbeddedImage ei = (EmbeddedImage) OwnerReport.LUEmbeddedImages[name]; mtype = ei.MIMEType; byte[] ba = Convert.FromBase64String(ei.ImageData); strm = new MemoryStream(ba); break; case ImageSourceEnum.External: string fname = _Value.EvaluateString(rpt, row); mtype = GetMimeType(fname); if (fname.StartsWith("http:") || fname.StartsWith("file:") || fname.StartsWith("https:")) { WebRequest wreq = WebRequest.Create(fname); WebResponse wres = wreq.GetResponse(); strm = wres.GetResponseStream(); } else strm = new FileStream(fname, System.IO.FileMode.Open, FileAccess.Read); break; default: return null; } } catch (Exception e) { if (strm != null) { strm.Close(); strm = null; } rpt.rl.LogError(4, string.Format("Unable to load image. {0}", e.Message)); } return strm; } internal ImageSourceEnum ImageSource { get { return _ImageSource; } set { _ImageSource = value; } } internal Expression Value { get { return _Value; } set { _Value = value; } } internal Expression MIMEType { get { return _MIMEType; } set { _MIMEType = value; } } internal ImageSizingEnum Sizing { get { return _Sizing; } set { _Sizing = value; } } internal bool ConstantImage { get { return _ConstantImage; } } static internal string GetMimeType(string file) { String fileExt; int startPos = file.LastIndexOf(".") + 1; fileExt = file.Substring(startPos).ToLower(); switch (fileExt) { case "bmp": return "image/bmp"; case "jpeg": case "jpe": case "jpg": case "jfif": return "image/jpeg"; case "gif": return "image/gif"; case "png": return "image/png"; case "tif": case "tiff": return "image/tiff"; default: return null; } } private WorkClass GetWC(Report rpt) { WorkClass wc = rpt.Cache.Get(this, "wc") as WorkClass; if (wc == null) { wc = new WorkClass(); rpt.Cache.Add(this, "wc", wc); } return wc; } private void RemoveImageWC(Report rpt) { rpt.Cache.Remove(this, "wc"); } class WorkClass { internal PageImage PgImage; // When ConstantImage is true this will save the PageImage for reuse internal WorkClass() { PgImage=null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.IO.Tests { public class File_Exists : FileSystemTest { #region Utilities public virtual bool Exists(string path) { return File.Exists(path); } #endregion #region UniversalTests [Fact] public void NullAsPath_ReturnsFalse() { Assert.False(Exists(null)); } [Fact] public void EmptyAsPath_ReturnsFalse() { Assert.False(Exists(string.Empty)); } [Theory, MemberData(nameof(ValidPathComponentNames))] public void NonExistentValidPath_ReturnsFalse(string path) { Assert.False(Exists(path), path); } [Theory, MemberData(nameof(ValidPathComponentNames))] public void ValidPathExists_ReturnsTrue(string component) { string path = Path.Combine(TestDirectory, component); FileInfo testFile = new FileInfo(path); testFile.Create().Dispose(); Assert.True(Exists(path)); } [Theory, MemberData(nameof(PathsWithInvalidCharacters))] public void PathWithInvalidCharactersAsPath_ReturnsFalse(string invalidPath) { // Checks that errors aren't thrown when calling Exists() on paths with impossible to create characters Assert.False(Exists(invalidPath)); Assert.False(Exists("..")); Assert.False(Exists(".")); } [Fact] public void PathAlreadyExistsAsFile() { string path = GetTestFilePath(); File.Create(path).Dispose(); Assert.True(Exists(IOServices.RemoveTrailingSlash(path))); Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path)))); Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path)))); } [Fact] public void PathEndsInTrailingSlash() { string path = GetTestFilePath() + Path.DirectorySeparatorChar; Assert.False(Exists(path)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void PathEndsInAltTrailingSlash_Windows() { string path = GetTestFilePath() + Path.DirectorySeparatorChar; Assert.False(Exists(path)); } [Fact] public void PathEndsInTrailingSlash_AndExists() { string path = GetTestFilePath(); File.Create(path).Dispose(); Assert.False(Exists(path + Path.DirectorySeparatorChar)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void PathEndsInAltTrailingSlash_AndExists_Windows() { string path = GetTestFilePath(); File.Create(path).Dispose(); Assert.False(Exists(path + Path.DirectorySeparatorChar)); } [Fact] public void PathAlreadyExistsAsDirectory() { string path = GetTestFilePath(); DirectoryInfo testDir = Directory.CreateDirectory(path); Assert.False(Exists(IOServices.RemoveTrailingSlash(path))); Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path)))); Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path)))); } [Fact] public void DirectoryLongerThanMaxDirectoryAsPath_DoesntThrow() { Assert.All((IOInputs.GetPathsLongerThanMaxDirectory(GetTestFilePath())), (path) => { Assert.False(Exists(path)); }); } [Fact] public void DirectoryLongerThanMaxPathAsPath_DoesntThrow() { Assert.All((IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath())), (path) => { Assert.False(Exists(path), path); }); } [ConditionalFact(nameof(CanCreateSymbolicLinks))] public void SymLinksMayExistIndependentlyOfTarget() { var path = GetTestFilePath(); var linkPath = GetTestFilePath(); File.Create(path).Dispose(); Assert.True(MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: false)); // Both the symlink and the target exist Assert.True(File.Exists(path), "path should exist"); Assert.True(File.Exists(linkPath), "linkPath should exist"); // Delete the target. The symlink should still exist File.Delete(path); Assert.False(File.Exists(path), "path should now not exist"); Assert.True(File.Exists(linkPath), "linkPath should still exist"); // Now delete the symlink. File.Delete(linkPath); Assert.False(File.Exists(linkPath), "linkPath should no longer exist"); } #endregion #region PlatformSpecific [Theory, MemberData(nameof(WhiteSpace))] [PlatformSpecific(TestPlatforms.Windows)] // Unix equivalent tested already in CreateDirectory public void WindowsNonSignificantWhiteSpaceAsPath_ReturnsFalse(string component) { // Checks that errors aren't thrown when calling Exists() on impossible paths Assert.False(Exists(component)); } [Fact] [PlatformSpecific(CaseInsensitivePlatforms)] public void DoesCaseInsensitiveInvariantComparions() { FileInfo testFile = new FileInfo(GetTestFilePath()); testFile.Create().Dispose(); Assert.True(Exists(testFile.FullName)); Assert.True(Exists(testFile.FullName.ToUpperInvariant())); Assert.True(Exists(testFile.FullName.ToLowerInvariant())); } [Fact] [PlatformSpecific(CaseSensitivePlatforms)] public void DoesCaseSensitiveComparions() { FileInfo testFile = new FileInfo(GetTestFilePath()); testFile.Create().Dispose(); Assert.True(Exists(testFile.FullName)); Assert.False(Exists(testFile.FullName.ToUpperInvariant())); Assert.False(Exists(testFile.FullName.ToLowerInvariant())); } [Theory, MemberData(nameof(ControlWhiteSpace))] [PlatformSpecific(TestPlatforms.Windows)] // In Windows, trailing whitespace in a path is trimmed [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)] // e.g. NetFX only public void TrailingWhiteSpace_Trimmed(string component) { // On desktop, we trim a number of whitespace characters FileInfo testFile = new FileInfo(GetTestFilePath()); testFile.Create().Dispose(); // Exists calls GetFullPath() which trims trailing white space Assert.True(Exists(testFile.FullName + component)); } [Theory, MemberData(nameof(NonControlWhiteSpace))] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] // Not NetFX public void TrailingWhiteSpace_NotTrimmed(string component) { // In CoreFX we don't trim anything other than space (' ') string path = GetTestFilePath() + component; FileInfo testFile = new FileInfo(path); testFile.Create().Dispose(); Assert.True(Exists(path)); } [Theory, MemberData(nameof(SimpleWhiteSpace))] //*Just* spaces [PlatformSpecific(TestPlatforms.Windows)] // In Windows, trailing whitespace in a path is trimmed public void TrailingSpace_Trimmed(string component) { FileInfo testFile = new FileInfo(GetTestFilePath()); testFile.Create().Dispose(); // Windows will trim trailing spaces Assert.True(Exists(testFile.FullName + component)); } [Theory, MemberData(nameof(PathsWithColons))] [PlatformSpecific(TestPlatforms.Windows)] // alternate data stream public void PathWithAlternateDataStreams_ReturnsFalse(string component) { Assert.False(Exists(component)); } [Theory, MemberData(nameof(PathsWithReservedDeviceNames))] [OuterLoop] [PlatformSpecific(TestPlatforms.Windows)] // device names public void PathWithReservedDeviceNameAsPath_ReturnsFalse(string component) { Assert.False(Exists(component)); } [Theory, MemberData(nameof(UncPathsWithoutShareName))] public void UncPathWithoutShareNameAsPath_ReturnsFalse(string component) { Assert.False(Exists(component)); } [Theory, MemberData(nameof(PathsWithComponentLongerThanMaxComponent))] [PlatformSpecific(TestPlatforms.Windows)] // max directory length not fixed on Unix public void DirectoryWithComponentLongerThanMaxComponentAsPath_ReturnsFalse(string component) { Assert.False(Exists(component)); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Uses P/Invokes public void FalseForNonRegularFile() { string fileName = GetTestFilePath(); Assert.Equal(0, mkfifo(fileName, 0)); Assert.True(File.Exists(fileName)); } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.ObjectModel; using System.Diagnostics; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Microsoft.VisualStudio.Debugger.Metadata; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { /// <summary> /// Type member expansion. /// </summary> /// <remarks> /// Includes accesses to static members with instance receivers and /// accesses to instance members with dynamic receivers. /// </remarks> internal sealed class MemberExpansion : Expansion { internal static Expansion CreateExpansion( DkmInspectionContext inspectionContext, TypeAndCustomInfo declaredTypeAndInfo, DkmClrValue value, ExpansionFlags flags, Predicate<MemberInfo> predicate, Formatter formatter) { var runtimeType = value.Type.GetLmrType(); // Primitives, enums and null values with a declared type that is an interface have no visible members. Debug.Assert(!runtimeType.IsInterface || value.IsNull); if (formatter.IsPredefinedType(runtimeType) || runtimeType.IsEnum || runtimeType.IsInterface) { return null; } var dynamicFlagsMap = DynamicFlagsMap.Create(declaredTypeAndInfo); var expansions = ArrayBuilder<Expansion>.GetInstance(); // From the members, collect the fields and properties, // separated into static and instance members. var staticMembers = ArrayBuilder<MemberAndDeclarationInfo>.GetInstance(); var instanceMembers = ArrayBuilder<MemberAndDeclarationInfo>.GetInstance(); var appDomain = value.Type.AppDomain; // Expand members. (Ideally, this should be done lazily.) var allMembers = ArrayBuilder<MemberAndDeclarationInfo>.GetInstance(); var includeInherited = (flags & ExpansionFlags.IncludeBaseMembers) == ExpansionFlags.IncludeBaseMembers; var hideNonPublic = (inspectionContext.EvaluationFlags & DkmEvaluationFlags.HideNonPublicMembers) == DkmEvaluationFlags.HideNonPublicMembers; runtimeType.AppendTypeMembers(allMembers, predicate, declaredTypeAndInfo.Type, appDomain, includeInherited, hideNonPublic); foreach (var member in allMembers) { var name = member.Name; if (name.IsCompilerGenerated()) { continue; } if (member.IsStatic) { staticMembers.Add(member); } else if (!value.IsNull) { instanceMembers.Add(member); } } allMembers.Free(); // Public and non-public instance members. Expansion publicInstanceExpansion; Expansion nonPublicInstanceExpansion; GetPublicAndNonPublicMembers( instanceMembers, dynamicFlagsMap, out publicInstanceExpansion, out nonPublicInstanceExpansion); // Public and non-public static members. Expansion publicStaticExpansion; Expansion nonPublicStaticExpansion; GetPublicAndNonPublicMembers( staticMembers, dynamicFlagsMap, out publicStaticExpansion, out nonPublicStaticExpansion); if (publicInstanceExpansion != null) { expansions.Add(publicInstanceExpansion); } if ((publicStaticExpansion != null) || (nonPublicStaticExpansion != null)) { var staticExpansions = ArrayBuilder<Expansion>.GetInstance(); if (publicStaticExpansion != null) { staticExpansions.Add(publicStaticExpansion); } if (nonPublicStaticExpansion != null) { staticExpansions.Add(nonPublicStaticExpansion); } Debug.Assert(staticExpansions.Count > 0); var staticMembersExpansion = new StaticMembersExpansion( runtimeType, AggregateExpansion.CreateExpansion(staticExpansions)); staticExpansions.Free(); expansions.Add(staticMembersExpansion); } if (value.NativeComPointer != 0) { expansions.Add(NativeViewExpansion.Instance); } if (nonPublicInstanceExpansion != null) { expansions.Add(nonPublicInstanceExpansion); } // Include Results View if necessary. if ((flags & ExpansionFlags.IncludeResultsView) != 0) { var resultsViewExpansion = ResultsViewExpansion.CreateExpansion(inspectionContext, value, formatter); if (resultsViewExpansion != null) { expansions.Add(resultsViewExpansion); } } var result = AggregateExpansion.CreateExpansion(expansions); expansions.Free(); return result; } private static void GetPublicAndNonPublicMembers( ArrayBuilder<MemberAndDeclarationInfo> allMembers, DynamicFlagsMap dynamicFlagsMap, out Expansion publicExpansion, out Expansion nonPublicExpansion) { var publicExpansions = ArrayBuilder<Expansion>.GetInstance(); var publicMembers = ArrayBuilder<MemberAndDeclarationInfo>.GetInstance(); var nonPublicMembers = ArrayBuilder<MemberAndDeclarationInfo>.GetInstance(); foreach (var member in allMembers) { if (member.BrowsableState.HasValue) { switch (member.BrowsableState.Value) { case DkmClrDebuggerBrowsableAttributeState.RootHidden: if (publicMembers.Count > 0) { publicExpansions.Add(new MemberExpansion(publicMembers.ToArray(), dynamicFlagsMap)); publicMembers.Clear(); } publicExpansions.Add(new RootHiddenExpansion(member, dynamicFlagsMap)); continue; case DkmClrDebuggerBrowsableAttributeState.Never: continue; } } if (member.HideNonPublic && !member.IsPublic) { nonPublicMembers.Add(member); } else { publicMembers.Add(member); } } if (publicMembers.Count > 0) { publicExpansions.Add(new MemberExpansion(publicMembers.ToArray(), dynamicFlagsMap)); } publicMembers.Free(); publicExpansion = AggregateExpansion.CreateExpansion(publicExpansions); publicExpansions.Free(); nonPublicExpansion = (nonPublicMembers.Count > 0) ? new NonPublicMembersExpansion( members: new MemberExpansion(nonPublicMembers.ToArray(), dynamicFlagsMap)) : null; nonPublicMembers.Free(); } private readonly MemberAndDeclarationInfo[] _members; private readonly DynamicFlagsMap _dynamicFlagsMap; private MemberExpansion(MemberAndDeclarationInfo[] members, DynamicFlagsMap dynamicFlagsMap) { Debug.Assert(members != null); Debug.Assert(members.Length > 0); Debug.Assert(dynamicFlagsMap != null); _members = members; _dynamicFlagsMap = dynamicFlagsMap; } internal override void GetRows( ResultProvider resultProvider, ArrayBuilder<EvalResultDataItem> rows, DkmInspectionContext inspectionContext, EvalResultDataItem parent, DkmClrValue value, int startIndex, int count, bool visitAll, ref int index) { int startIndex2; int count2; GetIntersection(startIndex, count, index, _members.Length, out startIndex2, out count2); int offset = startIndex2 - index; for (int i = 0; i < count2; i++) { rows.Add(GetMemberRow(resultProvider, inspectionContext, value, _members[i + offset], parent, _dynamicFlagsMap)); } index += _members.Length; } private static EvalResultDataItem GetMemberRow( ResultProvider resultProvider, DkmInspectionContext inspectionContext, DkmClrValue value, MemberAndDeclarationInfo member, EvalResultDataItem parent, DynamicFlagsMap dynamicFlagsMap) { var memberValue = GetMemberValue(value, member, inspectionContext); return CreateMemberDataItem( resultProvider, inspectionContext, member, memberValue, parent, dynamicFlagsMap, ExpansionFlags.All); } private static DkmClrValue GetMemberValue(DkmClrValue container, MemberAndDeclarationInfo member, DkmInspectionContext inspectionContext) { // Note: GetMemberValue() may return special value // when func-eval of properties is disabled. return container.GetMemberValue(member.Name, (int)member.MemberType, member.DeclaringType.FullName, inspectionContext); } private sealed class RootHiddenExpansion : Expansion { private readonly MemberAndDeclarationInfo _member; private readonly DynamicFlagsMap _dynamicFlagsMap; internal RootHiddenExpansion(MemberAndDeclarationInfo member, DynamicFlagsMap dynamicFlagsMap) { _member = member; _dynamicFlagsMap = dynamicFlagsMap; } internal override void GetRows( ResultProvider resultProvider, ArrayBuilder<EvalResultDataItem> rows, DkmInspectionContext inspectionContext, EvalResultDataItem parent, DkmClrValue value, int startIndex, int count, bool visitAll, ref int index) { var memberValue = GetMemberValue(value, _member, inspectionContext); if (memberValue.IsError()) { if (InRange(startIndex, count, index)) { var row = new EvalResultDataItem(Resources.ErrorName, errorMessage: (string)memberValue.HostObjectValue); rows.Add(row); } index++; } else { parent = CreateMemberDataItem( resultProvider, inspectionContext, _member, memberValue, parent, _dynamicFlagsMap, ExpansionFlags.IncludeBaseMembers | ExpansionFlags.IncludeResultsView); var expansion = parent.Expansion; if (expansion != null) { expansion.GetRows(resultProvider, rows, inspectionContext, parent, parent.Value, startIndex, count, visitAll, ref index); } } } } /// <summary> /// An explicit user request to bypass "Just My Code" and display /// the inaccessible members of an instance of an imported type. /// </summary> private sealed class NonPublicMembersExpansion : Expansion { private readonly Expansion _members; internal NonPublicMembersExpansion(Expansion members) { _members = members; } internal override void GetRows( ResultProvider resultProvider, ArrayBuilder<EvalResultDataItem> rows, DkmInspectionContext inspectionContext, EvalResultDataItem parent, DkmClrValue value, int startIndex, int count, bool visitAll, ref int index) { if (InRange(startIndex, count, index)) { rows.Add(GetRow( resultProvider, inspectionContext, value, _members, parent)); } index++; } private static readonly ReadOnlyCollection<string> s_hiddenFormatSpecifiers = new ReadOnlyCollection<string>(new[] { "hidden" }); private static EvalResultDataItem GetRow( ResultProvider resultProvider, DkmInspectionContext inspectionContext, DkmClrValue value, Expansion expansion, EvalResultDataItem parent) { return new EvalResultDataItem( ExpansionKind.NonPublicMembers, name: Resources.NonPublicMembers, typeDeclaringMemberAndInfo: default(TypeAndCustomInfo), declaredTypeAndInfo: default(TypeAndCustomInfo), parent: null, value: value, displayValue: null, expansion: expansion, childShouldParenthesize: parent.ChildShouldParenthesize, fullName: parent.FullNameWithoutFormatSpecifiers, childFullNamePrefixOpt: parent.ChildFullNamePrefix, formatSpecifiers: s_hiddenFormatSpecifiers, category: DkmEvaluationResultCategory.Data, flags: DkmEvaluationResultFlags.ReadOnly, editableValue: null, inspectionContext: inspectionContext); } } /// <summary> /// A transition from an instance of a type to the type itself (for inspecting static members). /// </summary> private sealed class StaticMembersExpansion : Expansion { private readonly Type _runtimeType; private readonly Expansion _members; internal StaticMembersExpansion(Type runtimeType, Expansion members) { _runtimeType = runtimeType; _members = members; } internal override void GetRows( ResultProvider resultProvider, ArrayBuilder<EvalResultDataItem> rows, DkmInspectionContext inspectionContext, EvalResultDataItem parent, DkmClrValue value, int startIndex, int count, bool visitAll, ref int index) { if (InRange(startIndex, count, index)) { rows.Add(GetRow( resultProvider, inspectionContext, new TypeAndCustomInfo(_runtimeType), value, _members)); } index++; } private static EvalResultDataItem GetRow( ResultProvider resultProvider, DkmInspectionContext inspectionContext, TypeAndCustomInfo declaredTypeAndInfo, DkmClrValue value, Expansion expansion) { var formatter = resultProvider.Formatter; var fullName = formatter.GetTypeName(declaredTypeAndInfo, escapeKeywordIdentifiers: true); return new EvalResultDataItem( ExpansionKind.StaticMembers, name: formatter.StaticMembersString, typeDeclaringMemberAndInfo: default(TypeAndCustomInfo), declaredTypeAndInfo: declaredTypeAndInfo, parent: null, value: value, displayValue: null, expansion: expansion, childShouldParenthesize: false, fullName: fullName, childFullNamePrefixOpt: fullName, formatSpecifiers: Formatter.NoFormatSpecifiers, category: DkmEvaluationResultCategory.Class, flags: DkmEvaluationResultFlags.ReadOnly, editableValue: null, inspectionContext: inspectionContext); } } private static EvalResultDataItem CreateMemberDataItem( ResultProvider resultProvider, DkmInspectionContext inspectionContext, MemberAndDeclarationInfo member, DkmClrValue memberValue, EvalResultDataItem parent, DynamicFlagsMap dynamicFlagsMap, ExpansionFlags flags) { var declaredType = member.Type; var declaredTypeInfo = dynamicFlagsMap.SubstituteDynamicFlags(member.OriginalDefinitionType, DynamicFlagsCustomTypeInfo.Create(member.TypeInfo)).GetCustomTypeInfo(); string memberName; // Considering, we're not handling the case of a member inherited from a generic base type. var typeDeclaringMember = member.GetExplicitlyImplementedInterface(out memberName) ?? member.DeclaringType; var typeDeclaringMemberInfo = typeDeclaringMember.IsInterface ? dynamicFlagsMap.SubstituteDynamicFlags(typeDeclaringMember.GetInterfaceListEntry(member.DeclaringType), originalDynamicFlags: default(DynamicFlagsCustomTypeInfo)).GetCustomTypeInfo() : null; var formatter = resultProvider.Formatter; memberName = formatter.GetIdentifierEscapingPotentialKeywords(memberName); var fullName = MakeFullName( formatter, memberName, new TypeAndCustomInfo(typeDeclaringMember, typeDeclaringMemberInfo), // Note: Won't include DynamicAttribute. member.RequiresExplicitCast, member.IsStatic, parent); return resultProvider.CreateDataItem( inspectionContext, memberName, typeDeclaringMemberAndInfo: (member.IncludeTypeInMemberName || typeDeclaringMember.IsInterface) ? new TypeAndCustomInfo(typeDeclaringMember, typeDeclaringMemberInfo) : default(TypeAndCustomInfo), // Note: Won't include DynamicAttribute. declaredTypeAndInfo: new TypeAndCustomInfo(declaredType, declaredTypeInfo), value: memberValue, parent: parent, expansionFlags: flags, childShouldParenthesize: false, fullName: fullName, formatSpecifiers: Formatter.NoFormatSpecifiers, category: DkmEvaluationResultCategory.Other, flags: memberValue.EvalFlags, evalFlags: DkmEvaluationFlags.None); } private static string MakeFullName( Formatter formatter, string name, TypeAndCustomInfo typeDeclaringMemberAndInfo, bool memberAccessRequiresExplicitCast, bool memberIsStatic, EvalResultDataItem parent) { // If the parent is an exception thrown during evaluation, // there is no valid fullname expression for the child. if (parent.Value.EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown)) { return null; } var parentFullName = parent.ChildFullNamePrefix; if (parentFullName == null) { return null; } if (parent.ChildShouldParenthesize) { parentFullName = $"({parentFullName})"; } if (!typeDeclaringMemberAndInfo.Type.IsInterface) { string qualifier; if (memberIsStatic) { qualifier = formatter.GetTypeName(typeDeclaringMemberAndInfo, escapeKeywordIdentifiers: false); } else if (memberAccessRequiresExplicitCast) { var typeName = formatter.GetTypeName(typeDeclaringMemberAndInfo, escapeKeywordIdentifiers: true); qualifier = formatter.GetCastExpression( parentFullName, typeName, parenthesizeEntireExpression: true); } else { qualifier = parentFullName; } return $"{qualifier}.{name}"; } else { // NOTE: This should never interact with debugger proxy types: // 1) Interfaces cannot have debugger proxy types. // 2) Debugger proxy types cannot be interfaces. if (typeDeclaringMemberAndInfo.Type.Equals(parent.DeclaredTypeAndInfo.Type)) { var memberAccessTemplate = parent.ChildShouldParenthesize ? "({0}).{1}" : "{0}.{1}"; return string.Format(memberAccessTemplate, parent.ChildFullNamePrefix, name); } else { var interfaceName = formatter.GetTypeName(typeDeclaringMemberAndInfo, escapeKeywordIdentifiers: true); var memberAccessTemplate = parent.ChildShouldParenthesize ? "(({0})({1})).{2}" : "(({0}){1}).{2}"; return string.Format(memberAccessTemplate, interfaceName, parent.ChildFullNamePrefix, name); } } } } }
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 p.pro.Server.Areas.HelpPage.Models; namespace p.pro.Server.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); } } } }
using DocumentFormat.OpenXml.Packaging; using Signum.Engine.Basics; using Signum.Engine.DynamicQuery; using Signum.Engine.Maps; using Signum.Engine.Operations; using Signum.Entities; using Signum.Entities.DynamicQuery; using Signum.Entities.Word; using Signum.Utilities; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Signum.Engine.UserAssets; using Signum.Engine.Templating; using Signum.Entities.Files; using Signum.Utilities.DataStructures; using DocumentFormat.OpenXml; using W = DocumentFormat.OpenXml.Wordprocessing; using System.Data; using Signum.Entities.Reflection; using Signum.Entities.Templating; using Signum.Engine.Authorization; using Signum.Engine; using Signum.Entities.Basics; using Signum.Engine.Files; namespace Signum.Engine.Word { public interface IWordDataTableProvider { string? Validate(string suffix, WordTemplateEntity template); DataTable GetDataTable(string suffix, WordTemplateLogic.WordContext context); } public static class WordTemplateLogic { public static bool AvoidSynchronize = false; public static ResetLazy<Dictionary<Lite<WordTemplateEntity>, WordTemplateEntity>> WordTemplatesLazy = null!; public static ResetLazy<Dictionary<object, List<WordTemplateEntity>>> TemplatesByQueryName = null!; public static ResetLazy<Dictionary<Type, List<WordTemplateEntity>>> TemplatesByEntityType = null!; public static Dictionary<WordTransformerSymbol, Action<WordContext, OpenXmlPackage>> Transformers = new Dictionary<WordTransformerSymbol, Action<WordContext, OpenXmlPackage>>(); public static Dictionary<WordConverterSymbol, Func<WordContext, byte[], byte[]>> Converters = new Dictionary<WordConverterSymbol, Func<WordContext, byte[], byte[]>>(); public static Dictionary<string, IWordDataTableProvider> ToDataTableProviders = new Dictionary<string, IWordDataTableProvider>(); [AutoExpressionField] public static IQueryable<WordTemplateEntity> WordTemplates(this WordModelEntity e) => As.Expression(() => Database.Query<WordTemplateEntity>().Where(a => a.Model == e)); public static void Start(SchemaBuilder sb) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { sb.Include<WordTemplateEntity>() .WithQuery(() => e => new { Entity = e, e.Id, e.Name, e.Query, e.Culture, e.Template!.Entity.FileName }); new Graph<WordTemplateEntity>.Execute(WordTemplateOperation.Save) { CanBeNew = true, CanBeModified = true, Execute = (wt, _) => { if (!wt.IsNew) { var oldFile = wt.InDB(t => t.Template); if (oldFile != null && !wt.Template.Is(oldFile)) Transaction.PreRealCommit += dic => oldFile.Delete(); } }, }.Register(); new Graph<WordTemplateEntity>.Delete(WordTemplateOperation.Delete) { Delete = (e, _) => e.Delete(), }.Register(); sb.Schema.EntityEvents<WordTemplateEntity>().Retrieved += WordTemplateLogic_Retrieved; PermissionAuthLogic.RegisterPermissions(WordTemplatePermission.GenerateReport); WordModelLogic.Start(sb); SymbolLogic<WordTransformerSymbol>.Start(sb, () => Transformers.Keys.ToHashSet()); SymbolLogic<WordConverterSymbol>.Start(sb, () => Converters.Keys.ToHashSet()); sb.Include<WordTransformerSymbol>() .WithQuery(() => f => new { Entity = f, f.Key }); sb.Include<WordConverterSymbol>() .WithQuery(() => f => new { Entity = f, f.Key }); sb.Schema.Table<WordModelEntity>().PreDeleteSqlSync += e => Administrator.UnsafeDeletePreCommand(Database.Query<WordTemplateEntity>() .Where(a => a.Model.Is(e))); ToDataTableProviders.Add("Model", new ModelDataTableProvider()); ToDataTableProviders.Add("UserQuery", new UserQueryDataTableProvider()); ToDataTableProviders.Add("UserChart", new UserChartDataTableProvider()); QueryLogic.Expressions.Register((WordModelEntity e) => e.WordTemplates(), () => typeof(WordTemplateEntity).NiceName()); new Graph<WordTemplateEntity>.Execute(WordTemplateOperation.CreateWordReport) { CanExecute = et => { if (et.Model != null && WordModelLogic.RequiresExtraParameters(et.Model)) return WordTemplateMessage._01RequiresExtraParameters.NiceToString(typeof(WordModelEntity).NiceName(), et.Model); return null; }, Execute = (et, args) => { throw new InvalidOperationException("UI-only operation"); } }.Register(); WordTemplatesLazy = sb.GlobalLazy(() => Database.Query<WordTemplateEntity>() .ToDictionary(et => et.ToLite()), new InvalidateWith(typeof(WordTemplateEntity))); TemplatesByQueryName = sb.GlobalLazy(() => { return WordTemplatesLazy.Value.Values.SelectCatch(w => KeyValuePair.Create(w.Query.ToQueryName(), w)).GroupToDictionary(); }, new InvalidateWith(typeof(WordTemplateEntity))); TemplatesByEntityType = sb.GlobalLazy(() => { return (from pair in WordTemplatesLazy.Value.Values.SelectCatch(wr => new { wr, imp = QueryLogic.Queries.GetEntityImplementations(wr.Query.ToQueryName()) }) where !pair.imp.IsByAll from t in pair.imp.Types select KeyValuePair.Create(t, pair.wr)) .GroupToDictionary(); }, new InvalidateWith(typeof(WordTemplateEntity))); Schema.Current.Synchronizing += Schema_Synchronize_Tokens; Validator.PropertyValidator((WordTemplateEntity e) => e.Template).StaticPropertyValidation += ValidateTemplate; } } private static void WordTemplateLogic_Retrieved(WordTemplateEntity template, PostRetrievingContext ctx) { object? queryName = template.Query.ToQueryNameCatch(); if (queryName == null) return; QueryDescription description = QueryLogic.Queries.QueryDescription(queryName); template.ParseData(description); } public static Dictionary<Type, WordTemplateVisibleOn> VisibleOnDictionary = new Dictionary<Type, WordTemplateVisibleOn>() { { typeof(MultiEntityModel), WordTemplateVisibleOn.Single | WordTemplateVisibleOn.Multiple}, { typeof(QueryModel), WordTemplateVisibleOn.Single | WordTemplateVisibleOn.Multiple| WordTemplateVisibleOn.Query}, }; public static bool IsVisible(WordTemplateEntity wt, WordTemplateVisibleOn visibleOn) { if (wt.Model == null) return visibleOn == WordTemplateVisibleOn.Single; if (WordModelLogic.HasDefaultTemplateConstructor(wt.Model)) return false; var entityType = WordModelLogic.GetEntityType(wt.Model.ToType()); if (entityType.IsEntity()) return visibleOn == WordTemplateVisibleOn.Single; var should = VisibleOnDictionary.TryGet(entityType, WordTemplateVisibleOn.Single); return ((should & visibleOn) != 0); } public static List<Lite<WordTemplateEntity>> GetApplicableWordTemplates(object queryName, Entity? entity, WordTemplateVisibleOn visibleOn) { var isAllowed = Schema.Current.GetInMemoryFilter<WordTemplateEntity>(userInterface: false); return TemplatesByQueryName.Value.TryGetC(queryName).EmptyIfNull() .Where(a => isAllowed(a) && IsVisible(a, visibleOn)) .Where(a => a.IsApplicable(entity)) .Select(a => a.ToLite()) .ToList(); } public static void RegisterTransformer(WordTransformerSymbol transformerSymbol, Action<WordContext, OpenXmlPackage> transformer) { if (transformerSymbol == null) throw AutoInitAttribute.ArgumentNullException(typeof(WordTransformerSymbol), nameof(transformerSymbol)); Transformers.Add(transformerSymbol, transformer); } public class WordContext { public WordTemplateEntity Template; public Entity? Entity; public IWordModel? Model; public WordContext(WordTemplateEntity template, Entity? entity, IWordModel? model) { Template = template; Entity = entity; Model = model; } public ModifiableEntity ModifiableEntity => (Entity ?? Model?.UntypedEntity)!; } public static void RegisterConverter(WordConverterSymbol converterSymbol, Func<WordContext, byte[], byte[]> converter) { if (converterSymbol == null) throw new ArgumentNullException(nameof(converterSymbol)); Converters.Add(converterSymbol, converter); } static string? ValidateTemplate(WordTemplateEntity template, PropertyInfo pi) { if (template.Template == null) return null; using (template.DisableAuthorization ? ExecutionMode.Global() : null) { QueryDescription qd = QueryLogic.Queries.QueryDescription(template.Query.ToQueryName()); string? error = null; template.ProcessOpenXmlPackage(document => { Dump(document, "0.Original.txt"); var parser = new WordTemplateParser(document, qd, template.Model?.ToType(), template); parser.ParseDocument(); Dump(document, "1.Match.txt"); parser.CreateNodes(); Dump(document, "2.BaseNode.txt"); parser.AssertClean(); error = parser.Errors.IsEmpty() ? null : parser.Errors.ToString(e => e.Message, "\r\n"); }); return error; } } public class FileNameBox { public string? FileName { get; set; } } public static FileContent CreateReportFileContent(this Lite<WordTemplateEntity> liteTemplate, ModifiableEntity? modifiableEntity = null, IWordModel? model = null, bool avoidConversion = false) { var box = new FileNameBox { FileName = null }; var bytes = liteTemplate.GetFromCache().CreateReport(modifiableEntity, model, avoidConversion, box); return new FileContent(box.FileName!, bytes); } public static byte[] CreateReport(this Lite<WordTemplateEntity> liteTemplate, ModifiableEntity? modifiableEntity = null, IWordModel? model = null, bool avoidConversion = false, FileNameBox? fileNameBox = null) { return liteTemplate.GetFromCache().CreateReport(modifiableEntity, model, avoidConversion, fileNameBox); } public static WordTemplateEntity GetFromCache(this Lite<WordTemplateEntity> liteTemplate) { WordTemplateEntity template = WordTemplatesLazy.Value.GetOrThrow(liteTemplate, "Word report template {0} not in cache".FormatWith(liteTemplate)); return template; } public static FileContent CreateReportFileContent(this WordTemplateEntity template, ModifiableEntity? modifiableEntity = null, IWordModel? model = null, bool avoidConversion = false) { var box = new FileNameBox { FileName = null }; var bytes = template.CreateReport(modifiableEntity, model, avoidConversion, box); return new FileContent(box.FileName!, bytes); } public static string? DumpFileFolder = null; public static byte[] CreateReport(this WordTemplateEntity template, ModifiableEntity? modifiableEntity = null, IWordModel? model = null, bool avoidConversion = false, FileNameBox? fileNameBox = null) { using (HeavyProfiler.Log("CreateReport", () => $"{template.Name} {modifiableEntity?.ToString()} {model?.UntypedEntity.ToString()}")) { try { WordTemplatePermission.GenerateReport.AssertAuthorized(); Entity? entity = null; if (template.Model != null) { if (model == null) model = WordModelLogic.CreateDefaultWordModel(template.Model, modifiableEntity); else if (template.Model.ToType() != model.GetType()) throw new ArgumentException("model should be a {0} instead of {1}".FormatWith(template.Model.FullClassName, model.GetType().FullName)); } else { entity = modifiableEntity as Entity ?? throw new InvalidOperationException("Model should be an Entity"); } using (template.DisableAuthorization ? ExecutionMode.Global() : null) using (CultureInfoUtils.ChangeBothCultures(template.Culture.ToCultureInfo())) { QueryDescription qd = QueryLogic.Queries.QueryDescription(template.Query.ToQueryName()); using (var p = HeavyProfiler.Log("ProcessOpenXmlPackage")) { var array = template.ProcessOpenXmlPackage(document => { Dump(document, "0.Original.txt"); var parser = new WordTemplateParser(document, qd, template.Model?.ToType(), template); p.Switch("ParseDocument"); parser.ParseDocument(); Dump(document, "1.Match.txt"); p.Switch("CreateNodes"); parser.CreateNodes(); Dump(document, "2.BaseNode.txt"); p.Switch("AssertClean"); parser.AssertClean(); if (parser.Errors.Any()) throw new InvalidOperationException("Error in template {0}:\r\n".FormatWith(template) + parser.Errors.ToString(e => e.Message, "\r\n")); var parsedFileName = fileNameBox != null ? TextTemplateParser.Parse(template.FileName, qd, template.Model?.ToType()) : null; var renderer = new WordTemplateRenderer(document, qd, template.Culture.ToCultureInfo(), template, model, entity, parsedFileName); p.Switch("MakeQuery"); renderer.ExecuteQuery(); p.Switch("RenderNodes"); renderer.RenderNodes(); Dump(document, "3.Replaced.txt"); p.Switch("AssertClean"); renderer.AssertClean(); p.Switch("FixDocument"); FixDocument(document); Dump(document, "4.Fixed.txt"); if (fileNameBox != null) { p.Switch("RenderFileName"); fileNameBox.FileName = renderer.RenderFileName(); } if (template.WordTransformer != null) { p.Switch("WordTransformer"); Transformers.GetOrThrow(template.WordTransformer)(new WordContext(template, entity, model), document); } }); if (!avoidConversion && template.WordConverter != null) { p.Switch("WordConverter"); array = Converters.GetOrThrow(template.WordConverter)(new WordContext(template, entity, model), array); } return array; } } } catch (Exception e) { e.Data["WordTemplate"] = template.ToLite(); e.Data["ModifiableEntity"] = modifiableEntity; e.Data["Model"] = model; throw; } } } private static void FixDocument(OpenXmlPackage document) { foreach (var root in document.AllRootElements()) { foreach (var cell in root.Descendants<W.TableCell>().ToList()) { if (!cell.ChildElements.Any(c => !(c is W.TableCellProperties))) cell.AppendChild(new W.Paragraph()); } } } private static void Dump(OpenXmlPackage document, string fileName) { if (DumpFileFolder == null) return; if (!Directory.Exists(DumpFileFolder)) Directory.CreateDirectory(DumpFileFolder); foreach (var part in AllParts(document).Where(p => p.RootElement != null)) { string fullFileName = Path.Combine(DumpFileFolder, part.Uri.ToString().Replace("/", "_") + "." + fileName); File.WriteAllText(fullFileName, part.RootElement.NiceToString()); } } static SqlPreCommand? Schema_Synchronize_Tokens(Replacements replacements) { if (AvoidSynchronize) return null; StringDistance sd = new StringDistance(); var emailTemplates = Database.Query<WordTemplateEntity>().ToList(); SqlPreCommand? cmd = emailTemplates.Select(uq => SynchronizeWordTemplate(replacements, uq, sd)).Combine(Spacing.Double); return cmd; } internal static SqlPreCommand? SynchronizeWordTemplate(Replacements replacements, WordTemplateEntity template, StringDistance sd) { Console.Write("."); try { if (template.Template == null || !replacements.Interactive) return null; var queryName = QueryLogic.ToQueryName(template.Query.Key); QueryDescription qd = QueryLogic.Queries.QueryDescription(queryName); using (DelayedConsole.Delay(() => SafeConsole.WriteLineColor(ConsoleColor.White, "WordTemplate: " + template.Name))) using (DelayedConsole.Delay(() => Console.WriteLine(" Query: " + template.Query.Key))) { var file = template.Template.RetrieveAndRemember(); var oldHash = file.Hash; try { SynchronizationContext sc = new SynchronizationContext(replacements, sd, qd, template.Model?.ToType()); var bytes = template.ProcessOpenXmlPackage(document => { Dump(document, "0.Original.txt"); var parser = new WordTemplateParser(document, qd, template.Model?.ToType(), template); parser.ParseDocument(); Dump(document, "1.Match.txt"); parser.CreateNodes(); Dump(document, "2.BaseNode.txt"); parser.AssertClean(); foreach (var root in document.AllRootElements()) { foreach (var node in root.Descendants<BaseNode>().ToList()) { node.Synchronize(sc); } } if (sc.HasChanges) { Dump(document, "3.Synchronized.txt"); var variables = new ScopedDictionary<string, ValueProviderBase>(null); foreach (var root in document.AllRootElements()) { foreach (var node in root.Descendants<BaseNode>().ToList()) { node.RenderTemplate(variables); } } Dump(document, "4.Rendered.txt"); } }); if (!sc.HasChanges) return null; file.AllowChange = true; file.BinaryFile = bytes; using (replacements.WithReplacedDatabaseName()) return Schema.Current.Table<FileEntity>().UpdateSqlSync(file, f => f.Hash == oldHash, comment: "WordTemplate: " + template.Name); } catch (TemplateSyncException ex) { if (ex.Result == FixTokenResult.SkipEntity) return null; if (ex.Result == FixTokenResult.DeleteEntity) return SqlPreCommandConcat.Combine(Spacing.Simple, Schema.Current.Table<WordTemplateEntity>().DeleteSqlSync(template, wt => wt.Name == template.Name), Schema.Current.Table<FileEntity>().DeleteSqlSync(file, f => f.Hash == file.Hash)); if (ex.Result == FixTokenResult.ReGenerateEntity) return Regenerate(template, replacements); throw new InvalidOperationException("Unexcpected {0}".FormatWith(ex.Result)); } } } catch (Exception e) { return new SqlPreCommandSimple("-- Exception in {0}: \r\n{1}".FormatWith(template.BaseToString(), e.Message.Indent(2, '-'))); } } public static byte[] ProcessOpenXmlPackage(this WordTemplateEntity template, Action<OpenXmlPackage> processPackage) { var file = template.Template!.RetrieveAndRemember(); using (var memory = new MemoryStream()) { memory.WriteAllBytes(file.BinaryFile); var ext = Path.GetExtension(file.FileName).ToLower(); var document = ext == ".docx" ? (OpenXmlPackage)WordprocessingDocument.Open(memory, true) : ext == ".pptx" ? (OpenXmlPackage)PresentationDocument.Open(memory, true) : ext == ".xlsx" ? (OpenXmlPackage)SpreadsheetDocument.Open(memory, true) : throw new InvalidOperationException("Extension '{0}' not supported".FormatWith(ext)); using (document) { processPackage(document); } return memory.ToArray(); } } public static bool Regenerate(WordTemplateEntity template) { var result = Regenerate(template, null); if (result == null) return false; result.ExecuteLeaves(); return true; } private static SqlPreCommand? Regenerate(WordTemplateEntity template, Replacements? replacements) { var newTemplate = template.Model == null ? null : WordModelLogic.CreateDefaultTemplate(template.Model); if (newTemplate == null) return null; var file = template.Template!.RetrieveAndRemember(); using (file.AllowChanges()) { file.BinaryFile = newTemplate.Template!.Entity.BinaryFile; file.FileName = newTemplate.Template!.Entity.FileName; return Schema.Current.Table<FileEntity>().UpdateSqlSync(file, f => f.Hash == file.Hash, comment: "WordTemplate Regenerated: " + template.Name); } } public static IEnumerable<OpenXmlPartRootElement> AllRootElements(this OpenXmlPartContainer document) { return AllParts(document).Select(p => p.RootElement).NotNull(); } public static IEnumerable<OpenXmlPart> AllParts(this OpenXmlPartContainer container) { var roots = container.Parts.Select(a => a.OpenXmlPart); var result = DirectedGraph<OpenXmlPart>.Generate(roots, c => c.Parts.Select(a => a.OpenXmlPart)); return result; } public static void GenerateDefaultTemplates() { var wordModels = Database.Query<WordModelEntity>().Where(se => !se.WordTemplates().Any()).ToList(); List<string> exceptions = new List<string>(); foreach (var se in wordModels) { try { var defaultTemplate = WordModelLogic.CreateDefaultTemplate(se); if (defaultTemplate != null) defaultTemplate.Save(); } catch (Exception ex) { exceptions.Add("{0} in {1}:\r\n{2}".FormatWith(ex.GetType().Name, se.FullClassName, ex.Message.Indent(4))); } } if (exceptions.Any()) throw new Exception(exceptions.ToString("\r\n\r\n")); } public static void OverrideWordTemplatesConsole() { var wordTemplates = Database.Query<WordTemplateEntity>().Where(a=>a.Model != null).GroupToDictionary(a => a.Model!); var wordModels = Database.Query<WordModelEntity>().ToList(); List<string> exceptions = new List<string>(); bool? rememberedAnswer = null; foreach (var se in wordModels) { try { var defaultTemplate = WordModelLogic.CreateDefaultTemplate(se); if (defaultTemplate != null && defaultTemplate.Template != null) { var already = wordTemplates.TryGetC(se); if (already == null) { defaultTemplate.Save(); SafeConsole.WriteLineColor(ConsoleColor.Green, $"Created {se.FullClassName}"); } else { var toModify = already.Only() ?? already.ChooseConsole(); if (toModify != null) { if (toModify.Template == null) { toModify.Template = defaultTemplate.Template; toModify.Save(); SafeConsole.WriteLineColor(ConsoleColor.Yellow, $"Initialized {se.FullClassName}"); } else if (MemoryExtensions.SequenceEqual<byte>(toModify.Template.RetrieveAndForget().BinaryFile, defaultTemplate.Template.Entity.BinaryFile)) { SafeConsole.WriteLineColor(ConsoleColor.DarkGray, $"Identical {se.FullClassName}"); } else { if (SafeConsole.Ask(ref rememberedAnswer, $"Override {se.FullClassName}?")) { toModify.Template = defaultTemplate.Template; toModify.Save(); SafeConsole.WriteLineColor(ConsoleColor.Yellow, $"Overriden {se.FullClassName}"); } } } } } } catch (Exception ex) { SafeConsole.WriteLineColor(ConsoleColor.Red, se.FullClassName); SafeConsole.WriteLineColor(ConsoleColor.Red, "{0} in {1}:\r\n{2}".FormatWith(ex.GetType().Name, se.FullClassName, ex.Message.Indent(4))); } } } } }
using Lucene.Net.Diagnostics; using System; namespace Lucene.Net.Search { /* * 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 ArrayUtil = Lucene.Net.Util.ArrayUtil; using ByteBlockPool = Lucene.Net.Util.ByteBlockPool; using BytesRef = Lucene.Net.Util.BytesRef; using BytesRefHash = Lucene.Net.Util.BytesRefHash; using IndexReader = Lucene.Net.Index.IndexReader; using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator; using Term = Lucene.Net.Index.Term; using TermContext = Lucene.Net.Index.TermContext; using TermsEnum = Lucene.Net.Index.TermsEnum; using TermState = Lucene.Net.Index.TermState; /// <summary> /// A rewrite method that tries to pick the best /// constant-score rewrite method based on term and /// document counts from the query. If both the number of /// terms and documents is small enough, then /// <see cref="MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE"/> is used. /// Otherwise, <see cref="MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE"/> is /// used. /// </summary> // LUCENENET specific: made this class public. In Lucene there was a derived class // with the same name that was nested within MultiTermQuery, but in .NET it is // more intuitive if our classes are not nested. public class ConstantScoreAutoRewrite : TermCollectingRewrite<BooleanQuery> { /// <summary> /// Defaults derived from rough tests with a 20.0 million /// doc Wikipedia index. With more than 350 terms in the /// query, the filter method is fastest: /// </summary> public static int DEFAULT_TERM_COUNT_CUTOFF = 350; /// <summary> /// If the query will hit more than 1 in 1000 of the docs /// in the index (0.1%), the filter method is fastest: /// </summary> public static double DEFAULT_DOC_COUNT_PERCENT = 0.1; private int termCountCutoff = DEFAULT_TERM_COUNT_CUTOFF; private double docCountPercent = DEFAULT_DOC_COUNT_PERCENT; /// <summary> /// If the number of terms in this query is equal to or /// larger than this setting then /// <see cref="MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE"/> is used. /// </summary> public virtual int TermCountCutoff { get => termCountCutoff; set => termCountCutoff = value; } /// <summary> /// If the number of documents to be visited in the /// postings exceeds this specified percentage of the /// <see cref="Index.IndexReader.MaxDoc"/> for the index, then /// <see cref="MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE"/> is used. /// Value may be 0.0 to 100.0. /// </summary> public virtual double DocCountPercent { get => docCountPercent; set => docCountPercent = value; } protected override BooleanQuery GetTopLevelQuery() { return new BooleanQuery(true); } protected override void AddClause(BooleanQuery topLevel, Term term, int docFreq, float boost, TermContext states) //ignored { topLevel.Add(new TermQuery(term, states), Occur.SHOULD); } public override Query Rewrite(IndexReader reader, MultiTermQuery query) { // Get the enum and start visiting terms. If we // exhaust the enum before hitting either of the // cutoffs, we use ConstantBooleanQueryRewrite; else, // ConstantFilterRewrite: int docCountCutoff = (int)((docCountPercent / 100.0) * reader.MaxDoc); int termCountLimit = Math.Min(BooleanQuery.MaxClauseCount, termCountCutoff); CutOffTermCollector col = new CutOffTermCollector(docCountCutoff, termCountLimit); CollectTerms(reader, query, col); int size = col.pendingTerms.Count; if (col.hasCutOff) { return MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE.Rewrite(reader, query); } else { BooleanQuery bq = GetTopLevelQuery(); if (size > 0) { BytesRefHash pendingTerms = col.pendingTerms; int[] sort = pendingTerms.Sort(col.termsEnum.Comparer); for (int i = 0; i < size; i++) { int pos = sort[i]; // docFreq is not used for constant score here, we pass 1 // to explicitely set a fake value, so it's not calculated AddClause(bq, new Term(query.m_field, pendingTerms.Get(pos, new BytesRef())), 1, 1.0f, col.array.termState[pos]); } } // Strip scores Query result = new ConstantScoreQuery(bq); result.Boost = query.Boost; return result; } } internal sealed class CutOffTermCollector : TermCollector { internal CutOffTermCollector(int docCountCutoff, int termCountLimit) { pendingTerms = new BytesRefHash(new ByteBlockPool(new ByteBlockPool.DirectAllocator()), 16, array); this.docCountCutoff = docCountCutoff; this.termCountLimit = termCountLimit; } public override void SetNextEnum(TermsEnum termsEnum) { this.termsEnum = termsEnum; } public override bool Collect(BytesRef bytes) { int pos = pendingTerms.Add(bytes); docVisitCount += termsEnum.DocFreq; if (pendingTerms.Count >= termCountLimit || docVisitCount >= docCountCutoff) { hasCutOff = true; return false; } TermState termState = termsEnum.GetTermState(); if (Debugging.AssertsEnabled) Debugging.Assert(termState != null); if (pos < 0) { pos = (-pos) - 1; array.termState[pos].Register(termState, m_readerContext.Ord, termsEnum.DocFreq, termsEnum.TotalTermFreq); } else { array.termState[pos] = new TermContext(m_topReaderContext, termState, m_readerContext.Ord, termsEnum.DocFreq, termsEnum.TotalTermFreq); } return true; } internal int docVisitCount = 0; internal bool hasCutOff = false; internal TermsEnum termsEnum; internal readonly int docCountCutoff, termCountLimit; internal readonly TermStateByteStart array = new TermStateByteStart(16); internal BytesRefHash pendingTerms; } public override int GetHashCode() { const int prime = 1279; return (int)(prime * termCountCutoff + J2N.BitConversion.DoubleToInt64Bits(docCountPercent)); } public override bool Equals(object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.GetType() != obj.GetType()) { return false; } ConstantScoreAutoRewrite other = (ConstantScoreAutoRewrite)obj; if (other.termCountCutoff != termCountCutoff) { return false; } if (J2N.BitConversion.DoubleToInt64Bits(other.docCountPercent) != J2N.BitConversion.DoubleToInt64Bits(docCountPercent)) { return false; } return true; } /// <summary> /// Special implementation of <see cref="BytesRefHash.BytesStartArray"/> that keeps parallel arrays for <see cref="TermContext"/> </summary> internal sealed class TermStateByteStart : BytesRefHash.DirectBytesStartArray { internal TermContext[] termState; public TermStateByteStart(int initSize) : base(initSize) { } public override int[] Init() { int[] ord = base.Init(); termState = new TermContext[ArrayUtil.Oversize(ord.Length, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; if (Debugging.AssertsEnabled) Debugging.Assert(termState.Length >= ord.Length); return ord; } public override int[] Grow() { int[] ord = base.Grow(); if (termState.Length < ord.Length) { TermContext[] tmpTermState = new TermContext[ArrayUtil.Oversize(ord.Length, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; Array.Copy(termState, 0, tmpTermState, 0, termState.Length); termState = tmpTermState; } if (Debugging.AssertsEnabled) Debugging.Assert(termState.Length >= ord.Length); return ord; } public override int[] Clear() { termState = null; return base.Clear(); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; #if !MSBUILD12 using Microsoft.Build.Construction; #endif using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MSBuild { /// <summary> /// A workspace that can be populated by opening MSBuild solution and project files. /// </summary> public sealed class MSBuildWorkspace : Workspace { // used to serialize access to public methods private readonly NonReentrantLock _serializationLock = new NonReentrantLock(); // used to protect access to mutable state private readonly NonReentrantLock _dataGuard = new NonReentrantLock(); private readonly Dictionary<string, string> _extensionToLanguageMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, ProjectId> _projectPathToProjectIdMap = new Dictionary<string, ProjectId>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, IProjectFileLoader> _projectPathToLoaderMap = new Dictionary<string, IProjectFileLoader>(StringComparer.OrdinalIgnoreCase); private string _solutionFilePath; private ImmutableDictionary<string, string> _properties; private MSBuildWorkspace( HostServices hostServices, ImmutableDictionary<string, string> properties) : base(hostServices, "MSBuildWorkspace") { // always make a copy of these build properties (no mutation please!) _properties = properties ?? ImmutableDictionary<string, string>.Empty; this.SetSolutionProperties(solutionFilePath: null); this.LoadMetadataForReferencedProjects = false; this.SkipUnrecognizedProjects = true; } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> public static MSBuildWorkspace Create() { return Create(ImmutableDictionary<string, string>.Empty); } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> /// <param name="properties">An optional set of MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument.</param> public static MSBuildWorkspace Create(IDictionary<string, string> properties) { return Create(properties, DesktopMefHostServices.DefaultServices); } /// <summary> /// Create a new instance of a workspace that can be populated by opening solution and project files. /// </summary> /// <param name="properties">The MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument.</param> /// <param name="hostServices">The <see cref="HostServices"/> used to configure this workspace.</param> public static MSBuildWorkspace Create(IDictionary<string, string> properties, HostServices hostServices) { if (properties == null) { throw new ArgumentNullException(nameof(properties)); } if (hostServices == null) { throw new ArgumentNullException(nameof(hostServices)); } return new MSBuildWorkspace(hostServices, properties.ToImmutableDictionary()); } /// <summary> /// The MSBuild properties used when interpreting project files. /// These are the same properties that are passed to msbuild via the /property:&lt;n&gt;=&lt;v&gt; command line argument. /// </summary> public ImmutableDictionary<string, string> Properties { get { return _properties; } } /// <summary> /// Determines if metadata from existing output assemblies is loaded instead of opening referenced projects. /// If the referenced project is already opened, the metadata will not be loaded. /// If the metadata assembly cannot be found the referenced project will be opened instead. /// </summary> public bool LoadMetadataForReferencedProjects { get; set; } /// <summary> /// Determines if unrecognized projects are skipped when solutions or projects are opened. /// /// An project is unrecognized if it either has /// a) an invalid file path, /// b) a non-existent project file, /// c) has an unrecognized file extension or /// d) a file extension associated with an unsupported language. /// /// If unrecognized projects cannot be skipped a corresponding exception is thrown. /// </summary> public bool SkipUnrecognizedProjects { get; set; } /// <summary> /// Associates a project file extension with a language name. /// </summary> public void AssociateFileExtensionWithLanguage(string projectFileExtension, string language) { if (language == null) { throw new ArgumentNullException(nameof(language)); } if (projectFileExtension == null) { throw new ArgumentNullException(nameof(projectFileExtension)); } using (_dataGuard.DisposableWait()) { _extensionToLanguageMap[projectFileExtension] = language; } } /// <summary> /// Close the open solution, and reset the workspace to a new empty solution. /// </summary> public void CloseSolution() { using (_serializationLock.DisposableWait()) { this.ClearSolution(); } } protected override void ClearSolutionData() { base.ClearSolutionData(); using (_dataGuard.DisposableWait()) { this.SetSolutionProperties(solutionFilePath: null); // clear project related data _projectPathToProjectIdMap.Clear(); _projectPathToLoaderMap.Clear(); } } private const string SolutionDirProperty = "SolutionDir"; private void SetSolutionProperties(string solutionFilePath) { _solutionFilePath = solutionFilePath; if (!string.IsNullOrEmpty(solutionFilePath)) { // When MSBuild is building an individual project, it doesn't define $(SolutionDir). // However when building an .sln file, or when working inside Visual Studio, // $(SolutionDir) is defined to be the directory where the .sln file is located. // Some projects out there rely on $(SolutionDir) being set (although the best practice is to // use MSBuildProjectDirectory which is always defined). if (!string.IsNullOrEmpty(solutionFilePath)) { string solutionDirectory = Path.GetDirectoryName(solutionFilePath); if (!solutionDirectory.EndsWith(@"\", StringComparison.Ordinal)) { solutionDirectory += @"\"; } if (Directory.Exists(solutionDirectory)) { _properties = _properties.SetItem(SolutionDirProperty, solutionDirectory); } } } } private ProjectId GetProjectId(string fullProjectPath) { using (_dataGuard.DisposableWait()) { ProjectId id; _projectPathToProjectIdMap.TryGetValue(fullProjectPath, out id); return id; } } private ProjectId GetOrCreateProjectId(string fullProjectPath) { using (_dataGuard.DisposableWait()) { ProjectId id; if (!_projectPathToProjectIdMap.TryGetValue(fullProjectPath, out id)) { id = ProjectId.CreateNewId(debugName: fullProjectPath); _projectPathToProjectIdMap.Add(fullProjectPath, id); } return id; } } private bool TryGetLoaderFromProjectPath(string projectFilePath, ReportMode mode, out IProjectFileLoader loader) { using (_dataGuard.DisposableWait()) { // check to see if we already know the loader if (!_projectPathToLoaderMap.TryGetValue(projectFilePath, out loader)) { // otherwise try to figure it out from extension var extension = Path.GetExtension(projectFilePath); if (extension.Length > 0 && extension[0] == '.') { extension = extension.Substring(1); } string language; if (_extensionToLanguageMap.TryGetValue(extension, out language)) { if (this.Services.SupportedLanguages.Contains(language)) { loader = this.Services.GetLanguageServices(language).GetService<IProjectFileLoader>(); } else { this.ReportFailure(mode, string.Format(WorkspacesResources.CannotOpenProjectUnsupportedLanguage, projectFilePath, language)); return false; } } else { loader = ProjectFileLoader.GetLoaderForProjectFileExtension(this, extension); if (loader == null) { this.ReportFailure(mode, string.Format(WorkspacesResources.CannotOpenProjectUnrecognizedFileExtension, projectFilePath, Path.GetExtension(projectFilePath))); return false; } } if (loader != null) { _projectPathToLoaderMap[projectFilePath] = loader; } } return loader != null; } } private bool TryGetAbsoluteProjectPath(string path, string baseDirectory, ReportMode mode, out string absolutePath) { try { absolutePath = this.GetAbsolutePath(path, baseDirectory); } catch (Exception) { ReportFailure(mode, string.Format(WorkspacesResources.InvalidProjectFilePath, path)); absolutePath = null; return false; } if (!File.Exists(absolutePath)) { ReportFailure( mode, string.Format(WorkspacesResources.ProjectFileNotFound, absolutePath), msg => new FileNotFoundException(msg)); return false; } return true; } private string GetAbsoluteSolutionPath(string path, string baseDirectory) { string absolutePath; try { absolutePath = GetAbsolutePath(path, baseDirectory); } catch (Exception) { throw new InvalidOperationException(string.Format(WorkspacesResources.InvalidSolutionFilePath, path)); } if (!File.Exists(absolutePath)) { throw new FileNotFoundException(string.Format(WorkspacesResources.SolutionFileNotFound, absolutePath)); } return absolutePath; } private enum ReportMode { Throw, Log, Ignore } private void ReportFailure(ReportMode mode, string message, Func<string, Exception> createException = null) { switch (mode) { case ReportMode.Throw: if (createException != null) { throw createException(message); } else { throw new InvalidOperationException(message); } case ReportMode.Log: this.OnWorkspaceFailed(new WorkspaceDiagnostic(WorkspaceDiagnosticKind.Failure, message)); break; case ReportMode.Ignore: default: break; } } private string GetAbsolutePath(string path, string baseDirectoryPath) { return Path.GetFullPath(FileUtilities.ResolveRelativePath(path, baseDirectoryPath) ?? path); } #region Open Solution & Project /// <summary> /// Open a solution file and all referenced projects. /// </summary> public async Task<Solution> OpenSolutionAsync(string solutionFilePath, CancellationToken cancellationToken = default(CancellationToken)) { if (solutionFilePath == null) { throw new ArgumentNullException(nameof(solutionFilePath)); } this.ClearSolution(); var absoluteSolutionPath = this.GetAbsoluteSolutionPath(solutionFilePath, Directory.GetCurrentDirectory()); using (_dataGuard.DisposableWait(cancellationToken)) { this.SetSolutionProperties(absoluteSolutionPath); } VersionStamp version = default(VersionStamp); #if !MSBUILD12 Microsoft.Build.Construction.SolutionFile solutionFile = Microsoft.Build.Construction.SolutionFile.Parse(absoluteSolutionPath); var reportMode = this.SkipUnrecognizedProjects ? ReportMode.Log : ReportMode.Throw; var invalidProjects = new List<ProjectInSolution>(); // seed loaders from known project types using (_dataGuard.DisposableWait(cancellationToken)) { foreach (var project in solutionFile.ProjectsInOrder) { if (project.ProjectType == SolutionProjectType.SolutionFolder) { continue; } var projectAbsolutePath = TryGetAbsolutePath(project.AbsolutePath, reportMode); if (projectAbsolutePath != null) { var extension = Path.GetExtension(projectAbsolutePath); if (extension.Length > 0 && extension[0] == '.') { extension = extension.Substring(1); } var loader = ProjectFileLoader.GetLoaderForProjectFileExtension(this, extension); if (loader != null) { _projectPathToLoaderMap[projectAbsolutePath] = loader; } } else { invalidProjects.Add(project); } } } // a list to accumulate all the loaded projects var loadedProjects = new List<ProjectInfo>(); // load all the projects foreach (var project in solutionFile.ProjectsInOrder) { cancellationToken.ThrowIfCancellationRequested(); if (project.ProjectType != SolutionProjectType.SolutionFolder && !invalidProjects.Contains(project)) { var projectAbsolutePath = TryGetAbsolutePath(project.AbsolutePath, reportMode); if (projectAbsolutePath != null) { IProjectFileLoader loader; if (TryGetLoaderFromProjectPath(projectAbsolutePath, reportMode, out loader)) { // projects get added to 'loadedProjects' as side-effect // never perfer metadata when loading solution, all projects get loaded if they can. var tmp = await GetOrLoadProjectAsync(projectAbsolutePath, loader, preferMetadata: false, loadedProjects: loadedProjects, cancellationToken: cancellationToken).ConfigureAwait(false); } } } } #else SolutionFile solutionFile = null; using (var reader = new StreamReader(absoluteSolutionPath)) { version = VersionStamp.Create(File.GetLastWriteTimeUtc(absoluteSolutionPath)); var text = await reader.ReadToEndAsync().ConfigureAwait(false); solutionFile = SolutionFile.Parse(new StringReader(text)); } var solutionFolder = Path.GetDirectoryName(absoluteSolutionPath); // seed loaders from known project types using (_dataGuard.DisposableWait()) { foreach (var projectBlock in solutionFile.ProjectBlocks) { string absoluteProjectPath; if (TryGetAbsoluteProjectPath(projectBlock.ProjectPath, solutionFolder, ReportMode.Ignore, out absoluteProjectPath)) { var loader = ProjectFileLoader.GetLoaderForProjectTypeGuid(this, projectBlock.ProjectTypeGuid); if (loader != null) { _projectPathToLoaderMap[absoluteProjectPath] = loader; } } } } // a list to accumulate all the loaded projects var loadedProjects = new List<ProjectInfo>(); var reportMode = this.SkipUnrecognizedProjects ? ReportMode.Log : ReportMode.Throw; // load all the projects foreach (var projectBlock in solutionFile.ProjectBlocks) { cancellationToken.ThrowIfCancellationRequested(); string absoluteProjectPath; if (TryGetAbsoluteProjectPath(projectBlock.ProjectPath, solutionFolder, reportMode, out absoluteProjectPath)) { IProjectFileLoader loader; if (TryGetLoaderFromProjectPath(absoluteProjectPath, reportMode, out loader)) { // projects get added to 'loadedProjects' as side-effect // never perfer metadata when loading solution, all projects get loaded if they can. var tmp = await GetOrLoadProjectAsync(absoluteProjectPath, loader, preferMetadata: false, loadedProjects: loadedProjects, cancellationToken: cancellationToken).ConfigureAwait(false); } } } #endif // construct workspace from loaded project infos this.OnSolutionAdded(SolutionInfo.Create(SolutionId.CreateNewId(debugName: absoluteSolutionPath), version, absoluteSolutionPath, loadedProjects)); this.UpdateReferencesAfterAdd(); return this.CurrentSolution; } /// <summary> /// Open a project file and all referenced projects. /// </summary> public async Task<Project> OpenProjectAsync(string projectFilePath, CancellationToken cancellationToken = default(CancellationToken)) { if (projectFilePath == null) { throw new ArgumentNullException(nameof(projectFilePath)); } string fullPath; if (this.TryGetAbsoluteProjectPath(projectFilePath, Directory.GetCurrentDirectory(), ReportMode.Throw, out fullPath)) { IProjectFileLoader loader; if (this.TryGetLoaderFromProjectPath(projectFilePath, ReportMode.Throw, out loader)) { var loadedProjects = new List<ProjectInfo>(); var projectId = await GetOrLoadProjectAsync(fullPath, loader, this.LoadMetadataForReferencedProjects, loadedProjects, cancellationToken).ConfigureAwait(false); // add projects to solution foreach (var project in loadedProjects) { this.OnProjectAdded(project); } this.UpdateReferencesAfterAdd(); return this.CurrentSolution.GetProject(projectId); } } // unreachable return null; } private string TryGetAbsolutePath(string path, ReportMode mode) { try { path = Path.GetFullPath(path); } catch (Exception) { ReportFailure(mode, string.Format(WorkspacesResources.InvalidProjectFilePath, path)); return null; } if (!File.Exists(path)) { ReportFailure( mode, string.Format(WorkspacesResources.ProjectFileNotFound, path), msg => new FileNotFoundException(msg)); return null; } return path; } private void UpdateReferencesAfterAdd() { using (_serializationLock.DisposableWait()) { var oldSolution = this.CurrentSolution; var newSolution = this.UpdateReferencesAfterAdd(oldSolution); if (newSolution != oldSolution) { newSolution = this.SetCurrentSolution(newSolution); var ignore = this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.SolutionChanged, oldSolution, newSolution); } } } // Updates all projects to properly reference other existing projects via project references instead of using references to built metadata. private Solution UpdateReferencesAfterAdd(Solution solution) { // Build map from output assembly path to ProjectId // Use explicit loop instead of ToDictionary so we don't throw if multiple projects have same output assembly path. var outputAssemblyToProjectIdMap = new Dictionary<string, ProjectId>(); foreach (var p in solution.Projects) { if (!string.IsNullOrEmpty(p.OutputFilePath)) { outputAssemblyToProjectIdMap[p.OutputFilePath] = p.Id; } } // now fix each project if necessary foreach (var pid in solution.ProjectIds) { var project = solution.GetProject(pid); // convert metadata references to project references if the metadata reference matches some project's output assembly. foreach (var meta in project.MetadataReferences) { var pemeta = meta as PortableExecutableReference; if (pemeta != null) { ProjectId matchingProjectId; // check both Display and FilePath. FilePath points to the actually bits, but Display should match output path if // the metadata reference is shadow copied. if ((!string.IsNullOrEmpty(pemeta.Display) && outputAssemblyToProjectIdMap.TryGetValue(pemeta.Display, out matchingProjectId)) || (!string.IsNullOrEmpty(pemeta.FilePath) && outputAssemblyToProjectIdMap.TryGetValue(pemeta.FilePath, out matchingProjectId))) { var newProjRef = new ProjectReference(matchingProjectId, pemeta.Properties.Aliases, pemeta.Properties.EmbedInteropTypes); if (!project.ProjectReferences.Contains(newProjRef)) { project = project.WithProjectReferences(project.ProjectReferences.Concat(newProjRef)); } project = project.WithMetadataReferences(project.MetadataReferences.Where(mr => mr != meta)); } } } solution = project.Solution; } return solution; } private async Task<ProjectId> GetOrLoadProjectAsync(string projectFilePath, IProjectFileLoader loader, bool preferMetadata, List<ProjectInfo> loadedProjects, CancellationToken cancellationToken) { var projectId = GetProjectId(projectFilePath); if (projectId == null) { projectId = await this.LoadProjectAsync(projectFilePath, loader, preferMetadata, loadedProjects, cancellationToken).ConfigureAwait(false); } return projectId; } private async Task<ProjectId> LoadProjectAsync(string projectFilePath, IProjectFileLoader loader, bool preferMetadata, List<ProjectInfo> loadedProjects, CancellationToken cancellationToken) { System.Diagnostics.Debug.Assert(projectFilePath != null); System.Diagnostics.Debug.Assert(loader != null); var projectId = this.GetOrCreateProjectId(projectFilePath); var projectName = Path.GetFileNameWithoutExtension(projectFilePath); var projectFile = await loader.LoadProjectFileAsync(projectFilePath, _properties, cancellationToken).ConfigureAwait(false); var projectFileInfo = await projectFile.GetProjectFileInfoAsync(cancellationToken).ConfigureAwait(false); VersionStamp version; if (!string.IsNullOrEmpty(projectFilePath) && File.Exists(projectFilePath)) { version = VersionStamp.Create(File.GetLastWriteTimeUtc(projectFilePath)); } else { version = VersionStamp.Create(); } // Documents var docFileInfos = projectFileInfo.Documents.ToImmutableArrayOrEmpty(); CheckDocuments(docFileInfos, projectFilePath, projectId); Encoding defaultEncoding = GetDefaultEncoding(projectFileInfo.CodePage); var docs = new List<DocumentInfo>(); foreach (var docFileInfo in docFileInfos) { string name; ImmutableArray<string> folders; GetDocumentNameAndFolders(docFileInfo.LogicalPath, out name, out folders); docs.Add(DocumentInfo.Create( DocumentId.CreateNewId(projectId, debugName: docFileInfo.FilePath), name, folders, projectFile.GetSourceCodeKind(docFileInfo.FilePath), new FileTextLoader(docFileInfo.FilePath, defaultEncoding), docFileInfo.FilePath, docFileInfo.IsGenerated)); } var additonalDocs = new List<DocumentInfo>(); foreach (var docFileInfo in projectFileInfo.AdditionalDocuments) { string name; ImmutableArray<string> folders; GetDocumentNameAndFolders(docFileInfo.LogicalPath, out name, out folders); additonalDocs.Add(DocumentInfo.Create( DocumentId.CreateNewId(projectId, debugName: docFileInfo.FilePath), name, folders, SourceCodeKind.Regular, new FileTextLoader(docFileInfo.FilePath, defaultEncoding), docFileInfo.FilePath, docFileInfo.IsGenerated)); } // project references var resolvedReferences = await this.ResolveProjectReferencesAsync( projectFilePath, projectFileInfo.ProjectReferences, preferMetadata, loadedProjects, cancellationToken).ConfigureAwait(false); var metadataReferences = projectFileInfo.MetadataReferences .Concat(resolvedReferences.MetadataReferences); var outputFilePath = projectFileInfo.OutputFilePath; var assemblyName = projectFileInfo.AssemblyName; // if the project file loader couldn't figure out an assembly name, make one using the project's file path. if (string.IsNullOrWhiteSpace(assemblyName)) { assemblyName = Path.GetFileNameWithoutExtension(projectFilePath); // if this is still unreasonable, use a fixed name. if (string.IsNullOrWhiteSpace(assemblyName)) { assemblyName = "assembly"; } } loadedProjects.Add( ProjectInfo.Create( projectId, version, projectName, assemblyName, loader.Language, projectFilePath, outputFilePath, projectFileInfo.CompilationOptions, projectFileInfo.ParseOptions, docs, resolvedReferences.ProjectReferences, metadataReferences, analyzerReferences: projectFileInfo.AnalyzerReferences, additionalDocuments: additonalDocs, isSubmission: false, hostObjectType: null)); return projectId; } private static Encoding GetDefaultEncoding(int codePage) { // If no CodePage was specified in the project file, then the FileTextLoader will // attempt to use UTF8 before falling back on Encoding.Default. if (codePage == 0) { return null; } try { return Encoding.GetEncoding(codePage); } catch (ArgumentOutOfRangeException) { return null; } } private static readonly char[] s_directorySplitChars = new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; private static void GetDocumentNameAndFolders(string logicalPath, out string name, out ImmutableArray<string> folders) { var pathNames = logicalPath.Split(s_directorySplitChars, StringSplitOptions.RemoveEmptyEntries); if (pathNames.Length > 0) { if (pathNames.Length > 1) { folders = pathNames.Take(pathNames.Length - 1).ToImmutableArray(); } else { folders = ImmutableArray.Create<string>(); } name = pathNames[pathNames.Length - 1]; } else { name = logicalPath; folders = ImmutableArray.Create<string>(); } } private void CheckDocuments(IEnumerable<DocumentFileInfo> docs, string projectFilePath, ProjectId projectId) { var paths = new HashSet<string>(); foreach (var doc in docs) { if (paths.Contains(doc.FilePath)) { this.OnWorkspaceFailed(new ProjectDiagnostic(WorkspaceDiagnosticKind.Warning, string.Format(WorkspacesResources.DuplicateSourceFileInProject, doc.FilePath, projectFilePath), projectId)); } paths.Add(doc.FilePath); } } private class ResolvedReferences { public readonly List<ProjectReference> ProjectReferences = new List<ProjectReference>(); public readonly List<MetadataReference> MetadataReferences = new List<MetadataReference>(); } private async Task<ResolvedReferences> ResolveProjectReferencesAsync( string thisProjectPath, IReadOnlyList<ProjectFileReference> projectFileReferences, bool preferMetadata, List<ProjectInfo> loadedProjects, CancellationToken cancellationToken) { var resolvedReferences = new ResolvedReferences(); var reportMode = this.SkipUnrecognizedProjects ? ReportMode.Log : ReportMode.Throw; foreach (var projectFileReference in projectFileReferences) { string fullPath; if (TryGetAbsoluteProjectPath(projectFileReference.Path, Path.GetDirectoryName(thisProjectPath), reportMode, out fullPath)) { // if the project is already loaded, then just reference the one we have var existingProjectId = this.GetProjectId(fullPath); if (existingProjectId != null) { resolvedReferences.ProjectReferences.Add(new ProjectReference(existingProjectId, projectFileReference.Aliases)); continue; } IProjectFileLoader loader; TryGetLoaderFromProjectPath(fullPath, ReportMode.Ignore, out loader); // get metadata if preferred or if loader is unknown if (preferMetadata || loader == null) { var projectMetadata = await this.GetProjectMetadata(fullPath, projectFileReference.Aliases, _properties, cancellationToken).ConfigureAwait(false); if (projectMetadata != null) { resolvedReferences.MetadataReferences.Add(projectMetadata); continue; } } // must load, so we really need loader if (TryGetLoaderFromProjectPath(fullPath, reportMode, out loader)) { // load the project var projectId = await this.GetOrLoadProjectAsync(fullPath, loader, preferMetadata, loadedProjects, cancellationToken).ConfigureAwait(false); resolvedReferences.ProjectReferences.Add(new ProjectReference(projectId, projectFileReference.Aliases)); continue; } } else { fullPath = projectFileReference.Path; } // cannot find metadata and project cannot be loaded, so leave a project reference to a non-existent project. var id = this.GetOrCreateProjectId(fullPath); resolvedReferences.ProjectReferences.Add(new ProjectReference(id, projectFileReference.Aliases)); } return resolvedReferences; } /// <summary> /// Gets a MetadataReference to a project's output assembly. /// </summary> private async Task<MetadataReference> GetProjectMetadata(string projectFilePath, ImmutableArray<string> aliases, IDictionary<string, string> globalProperties, CancellationToken cancellationToken) { // use loader service to determine output file for project if possible string outputFilePath = null; try { outputFilePath = await ProjectFileLoader.GetOutputFilePathAsync(projectFilePath, globalProperties, cancellationToken).ConfigureAwait(false); } catch (Exception e) { this.OnWorkspaceFailed(new WorkspaceDiagnostic(WorkspaceDiagnosticKind.Failure, e.Message)); } if (outputFilePath != null && File.Exists(outputFilePath)) { if (Workspace.TestHookStandaloneProjectsDoNotHoldReferences) { var documentationService = this.Services.GetService<IDocumentationProviderService>(); var docProvider = documentationService.GetDocumentationProvider(outputFilePath); var metadata = AssemblyMetadata.CreateFromImage(File.ReadAllBytes(outputFilePath)); return metadata.GetReference( documentation: docProvider, aliases: aliases, display: outputFilePath); } else { var metadataService = this.Services.GetService<IMetadataService>(); return metadataService.GetReference(outputFilePath, new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases)); } } return null; } #endregion #region Apply Changes public override bool CanApplyChange(ApplyChangesKind feature) { switch (feature) { case ApplyChangesKind.ChangeDocument: case ApplyChangesKind.AddDocument: case ApplyChangesKind.RemoveDocument: case ApplyChangesKind.AddMetadataReference: case ApplyChangesKind.RemoveMetadataReference: case ApplyChangesKind.AddProjectReference: case ApplyChangesKind.RemoveProjectReference: case ApplyChangesKind.AddAnalyzerReference: case ApplyChangesKind.RemoveAnalyzerReference: return true; default: return false; } } private bool HasProjectFileChanges(ProjectChanges changes) { return changes.GetAddedDocuments().Any() || changes.GetRemovedDocuments().Any() || changes.GetAddedMetadataReferences().Any() || changes.GetRemovedMetadataReferences().Any() || changes.GetAddedProjectReferences().Any() || changes.GetRemovedProjectReferences().Any() || changes.GetAddedAnalyzerReferences().Any() || changes.GetRemovedAnalyzerReferences().Any(); } private IProjectFile _applyChangesProjectFile; public override bool TryApplyChanges(Solution newSolution) { using (_serializationLock.DisposableWait()) { return base.TryApplyChanges(newSolution); } } protected override void ApplyProjectChanges(ProjectChanges projectChanges) { System.Diagnostics.Debug.Assert(_applyChangesProjectFile == null); var project = projectChanges.OldProject ?? projectChanges.NewProject; try { // if we need to modify the project file, load it first. if (this.HasProjectFileChanges(projectChanges)) { var projectPath = project.FilePath; IProjectFileLoader loader; if (this.TryGetLoaderFromProjectPath(projectPath, ReportMode.Ignore, out loader)) { try { _applyChangesProjectFile = loader.LoadProjectFileAsync(projectPath, _properties, CancellationToken.None).Result; } catch (System.IO.IOException exception) { this.OnWorkspaceFailed(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, projectChanges.ProjectId)); } } } // do normal apply operations base.ApplyProjectChanges(projectChanges); // save project file if (_applyChangesProjectFile != null) { try { _applyChangesProjectFile.Save(); } catch (System.IO.IOException exception) { this.OnWorkspaceFailed(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, projectChanges.ProjectId)); } } } finally { _applyChangesProjectFile = null; } } protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText text) { var document = this.CurrentSolution.GetDocument(documentId); if (document != null) { Encoding encoding = DetermineEncoding(text, document); this.SaveDocumentText(documentId, document.FilePath, text, encoding ?? new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); this.OnDocumentTextChanged(documentId, text, PreservationMode.PreserveValue); } } private static Encoding DetermineEncoding(SourceText text, Document document) { if (text.Encoding != null) { return text.Encoding; } try { using (ExceptionHelpers.SuppressFailFast()) { using (var stream = new FileStream(document.FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var onDiskText = EncodedStringText.Create(stream); return onDiskText.Encoding; } } } catch (IOException) { } catch (InvalidDataException) { } return null; } protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text) { System.Diagnostics.Debug.Assert(_applyChangesProjectFile != null); var project = this.CurrentSolution.GetProject(info.Id.ProjectId); IProjectFileLoader loader; if (this.TryGetLoaderFromProjectPath(project.FilePath, ReportMode.Ignore, out loader)) { var extension = _applyChangesProjectFile.GetDocumentExtension(info.SourceCodeKind); var fileName = Path.ChangeExtension(info.Name, extension); var relativePath = (info.Folders != null && info.Folders.Count > 0) ? Path.Combine(Path.Combine(info.Folders.ToArray()), fileName) : fileName; var fullPath = GetAbsolutePath(relativePath, Path.GetDirectoryName(project.FilePath)); var newDocumentInfo = info.WithName(fileName) .WithFilePath(fullPath) .WithTextLoader(new FileTextLoader(fullPath, text.Encoding)); // add document to project file _applyChangesProjectFile.AddDocument(relativePath); // add to solution this.OnDocumentAdded(newDocumentInfo); // save text to disk if (text != null) { this.SaveDocumentText(info.Id, fullPath, text, text.Encoding ?? Encoding.UTF8); } } } private void SaveDocumentText(DocumentId id, string fullPath, SourceText newText, Encoding encoding) { try { using (ExceptionHelpers.SuppressFailFast()) { var dir = Path.GetDirectoryName(fullPath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } Debug.Assert(encoding != null); using (var writer = new StreamWriter(fullPath, append: false, encoding: encoding)) { newText.Write(writer); } } } catch (IOException exception) { this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, id)); } } protected override void ApplyDocumentRemoved(DocumentId documentId) { Debug.Assert(_applyChangesProjectFile != null); var document = this.CurrentSolution.GetDocument(documentId); if (document != null) { _applyChangesProjectFile.RemoveDocument(document.FilePath); this.DeleteDocumentFile(document.Id, document.FilePath); this.OnDocumentRemoved(documentId); } } private void DeleteDocumentFile(DocumentId documentId, string fullPath) { try { if (File.Exists(fullPath)) { File.Delete(fullPath); } } catch (IOException exception) { this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId)); } catch (NotSupportedException exception) { this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId)); } catch (UnauthorizedAccessException exception) { this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId)); } } protected override void ApplyMetadataReferenceAdded(ProjectId projectId, MetadataReference metadataReference) { Debug.Assert(_applyChangesProjectFile != null); var identity = GetAssemblyIdentity(projectId, metadataReference); _applyChangesProjectFile.AddMetadataReference(metadataReference, identity); this.OnMetadataReferenceAdded(projectId, metadataReference); } protected override void ApplyMetadataReferenceRemoved(ProjectId projectId, MetadataReference metadataReference) { Debug.Assert(_applyChangesProjectFile != null); var identity = GetAssemblyIdentity(projectId, metadataReference); _applyChangesProjectFile.RemoveMetadataReference(metadataReference, identity); this.OnMetadataReferenceRemoved(projectId, metadataReference); } private AssemblyIdentity GetAssemblyIdentity(ProjectId projectId, MetadataReference metadataReference) { var project = this.CurrentSolution.GetProject(projectId); if (!project.MetadataReferences.Contains(metadataReference)) { project = project.AddMetadataReference(metadataReference); } var compilation = project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var symbol = compilation.GetAssemblyOrModuleSymbol(metadataReference) as IAssemblySymbol; return symbol != null ? symbol.Identity : null; } protected override void ApplyProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { Debug.Assert(_applyChangesProjectFile != null); var project = this.CurrentSolution.GetProject(projectReference.ProjectId); if (project != null) { _applyChangesProjectFile.AddProjectReference(project.Name, new ProjectFileReference(project.FilePath, projectReference.Aliases)); } this.OnProjectReferenceAdded(projectId, projectReference); } protected override void ApplyProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { Debug.Assert(_applyChangesProjectFile != null); var project = this.CurrentSolution.GetProject(projectReference.ProjectId); if (project != null) { _applyChangesProjectFile.RemoveProjectReference(project.Name, project.FilePath); } this.OnProjectReferenceRemoved(projectId, projectReference); } protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { Debug.Assert(_applyChangesProjectFile != null); _applyChangesProjectFile.AddAnalyzerReference(analyzerReference); this.OnAnalyzerReferenceAdded(projectId, analyzerReference); } protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { Debug.Assert(_applyChangesProjectFile != null); _applyChangesProjectFile.RemoveAnalyzerReference(analyzerReference); this.OnAnalyzerReferenceRemoved(projectId, analyzerReference); } } #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; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests { public class DistinctTests : EnumerableTests { [Fact] public void SameResultsRepeatCallsIntQuery() { var q = from x in new[] { 0, 9999, 0, 888, -1, 66, -1, -777, 1, 2, -12345, 66, 66, -1, -1 } where x > Int32.MinValue select x; Assert.Equal(q.Distinct(), q.Distinct()); } [Fact] public void SameResultsRepeatCallsStringQuery() { var q = from x in new[] { "!@#$%^", "C", "AAA", "Calling Twice", "SoS" } where String.IsNullOrEmpty(x) select x; Assert.Equal(q.Distinct(), q.Distinct()); } [Fact] public void EmptySource() { int[] source = { }; Assert.Empty(source.Distinct()); } [Fact] public void SingleNullElementExplicitlyUseDefaultComparer() { string[] source = { null }; string[] expected = { null }; Assert.Equal(expected, source.Distinct(EqualityComparer<string>.Default)); } [Fact] public void EmptyStringDistinctFromNull() { string[] source = { null, null, string.Empty }; string[] expected = { null, string.Empty }; Assert.Equal(expected, source.Distinct(EqualityComparer<string>.Default)); } [Fact] public void CollapsDuplicateNulls() { string[] source = { null, null }; string[] expected = { null }; Assert.Equal(expected, source.Distinct(EqualityComparer<string>.Default)); } [Fact] public void SourceAllDuplicates() { int[] source = { 5, 5, 5, 5, 5, 5 }; int[] expected = { 5 }; Assert.Equal(expected, source.Distinct()); } [Fact] public void AllUnique() { int[] source = { 2, -5, 0, 6, 10, 9 }; Assert.Equal(source, source.Distinct()); } [Fact] public void SomeDuplicatesIncludingNulls() { int?[] source = { 1, 1, 1, 2, 2, 2, null, null }; int?[] expected = { 1, 2, null }; Assert.Equal(expected, source.Distinct()); } [Fact] public void LastSameAsFirst() { int[] source = { 1, 2, 3, 4, 5, 1 }; int[] expected = { 1, 2, 3, 4, 5 }; Assert.Equal(expected, source.Distinct()); } // Multiple elements repeat non-consecutively [Fact] public void RepeatsNonConsecutive() { int[] source = { 1, 1, 2, 2, 4, 3, 1, 3, 2 }; int[] expected = { 1, 2, 4, 3 }; Assert.Equal(expected, source.Distinct()); } [Fact] public void NullComparer() { string[] source = { "Bob", "Tim", "bBo", "miT", "Robert", "iTm" }; string[] expected = { "Bob", "Tim", "bBo", "miT", "Robert", "iTm" }; Assert.Equal(expected, source.Distinct()); } [Fact] public void NullSource() { string[] source = null; Assert.Throws<ArgumentNullException>("source", () => source.Distinct()); } [Fact] public void NullSourceCustomComparer() { string[] source = null; Assert.Throws<ArgumentNullException>("source", () => source.Distinct(StringComparer.Ordinal)); } [Fact] public void CustomEqualityComparer() { string[] source = { "Bob", "Tim", "bBo", "miT", "Robert", "iTm" }; string[] expected = { "Bob", "Tim", "Robert" }; Assert.Equal(expected, source.Distinct(new AnagramEqualityComparer()), new AnagramEqualityComparer()); } [Theory, MemberData("SequencesWithDuplicates")] public void FindDistinctAndValidate<T>(T unusedArgumentToForceTypeInference, IEnumerable<T> original) { // Convert to list to avoid repeated enumerations of the enumerables. var originalList = original.ToList(); var distinctList = originalList.Distinct().ToList(); // Ensure the result doesn't contain duplicates. var hashSet = new HashSet<T>(); foreach (var i in distinctList) Assert.True(hashSet.Add(i)); var originalSet = new HashSet<T>(original); Assert.Superset(originalSet, hashSet); Assert.Subset(originalSet, hashSet); } public static IEnumerable<object[]> SequencesWithDuplicates() { // Validate an array of different numeric data types. yield return new object[] { 0, new int[] { 1, 1, 1, 2, 3, 5, 5, 6, 6, 10 } }; yield return new object[] { 0L, new long[] { 1, 1, 1, 2, 3, 5, 5, 6, 6, 10 } }; yield return new object[] { 0F, new float[] { 1, 1, 1, 2, 3, 5, 5, 6, 6, 10 } }; yield return new object[] { 0.0, new double[] { 1, 1, 1, 2, 3, 5, 5, 6, 6, 10 } }; yield return new object[] { 0M, new decimal[] { 1, 1, 1, 2, 3, 5, 5, 6, 6, 10 } }; // Try strings yield return new object[] { "", new [] { "add", "add", "subtract", "multiply", "divide", "divide2", "subtract", "add", "power", "exponent", "hello", "class", "namespace", "namespace", "namespace", } }; } [Fact] public void ForcedToEnumeratorDoesntEnumerate() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Distinct(); // Don't insist on this behaviour, but check its correct if it happens var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } } }
// --------------------------------------------------------------------------- // <copyright file="MainForm.cs" company="Tethys"> // Copyright (C) 1998-2021 T. Graf // </copyright> // // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 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. // --------------------------------------------------------------------------- namespace RingBufferDemo { using System; using System.Globalization; using System.Windows.Forms; using Tethys.IO; /// <summary> /// Summary description for Form1. /// </summary> public class MainForm : Form { /// <summary> /// Required designer variable. /// </summary> private readonly System.ComponentModel.Container components = null; private Label label1; private TextBox txtSizeNew; private Label label2; private Button btnCreate; private Label label3; private TextBox txtSize; private Label label4; private Label label5; private TextBox txtContents; private Button btnUpdate; private Button btnReset; private TextBox txtPosition; private Label label6; private Button btnAddString; private Button btnAddCharArry; private TextBox txtDataAdd; private Label label7; private Button btnGetData; private TextBox txtDataReturn; private Label label8; private TextBox txtCharReq; private Label label9; private Button btnConsume; private Label label10; private TextBox txtConsume; private Button btnGetNextLine; private GroupBox groupCreation; private GroupBox groupStatus; private GroupBox groupOperations; private Button btnAddCr; private Button btnAddLf; private Button bntUnitTests; private RingBuffer rb; /// <summary> /// Initializes a new instance of the <see cref="MainForm"/> class. /// </summary> public MainForm() { // Required for Windows Form Designer support this.InitializeComponent(); this.rb = null; } // MainForm() /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true to release both managed and /// unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (disposing) { this.components?.Dispose(); } // if base.Dispose(disposing); } // Dispose() #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.groupCreation = new System.Windows.Forms.GroupBox(); this.btnCreate = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.txtSizeNew = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.groupStatus = new System.Windows.Forms.GroupBox(); this.txtPosition = new System.Windows.Forms.TextBox(); this.label6 = new System.Windows.Forms.Label(); this.txtContents = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.txtSize = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.btnUpdate = new System.Windows.Forms.Button(); this.groupOperations = new System.Windows.Forms.GroupBox(); this.btnAddLf = new System.Windows.Forms.Button(); this.btnAddCr = new System.Windows.Forms.Button(); this.btnGetNextLine = new System.Windows.Forms.Button(); this.btnConsume = new System.Windows.Forms.Button(); this.label10 = new System.Windows.Forms.Label(); this.txtConsume = new System.Windows.Forms.TextBox(); this.label9 = new System.Windows.Forms.Label(); this.txtDataReturn = new System.Windows.Forms.TextBox(); this.btnGetData = new System.Windows.Forms.Button(); this.btnAddCharArry = new System.Windows.Forms.Button(); this.btnAddString = new System.Windows.Forms.Button(); this.btnReset = new System.Windows.Forms.Button(); this.label7 = new System.Windows.Forms.Label(); this.txtDataAdd = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.txtCharReq = new System.Windows.Forms.TextBox(); this.bntUnitTests = new System.Windows.Forms.Button(); this.groupCreation.SuspendLayout(); this.groupStatus.SuspendLayout(); this.groupOperations.SuspendLayout(); this.SuspendLayout(); // --- // groupCreation // --- this.groupCreation.Controls.Add(this.btnCreate); this.groupCreation.Controls.Add(this.label2); this.groupCreation.Controls.Add(this.txtSizeNew); this.groupCreation.Controls.Add(this.label1); this.groupCreation.Location = new System.Drawing.Point(8, 8); this.groupCreation.Name = "groupCreation"; this.groupCreation.Size = new System.Drawing.Size(272, 52); this.groupCreation.TabIndex = 0; this.groupCreation.TabStop = false; this.groupCreation.Text = " RingBuffer Creation "; // --- // btnCreate // --- this.btnCreate.Location = new System.Drawing.Point(184, 20); this.btnCreate.Name = "btnCreate"; this.btnCreate.TabIndex = 3; this.btnCreate.Text = "Create"; this.btnCreate.Click += new System.EventHandler(this.BtnCreateClick); // --- // label2 // --- this.label2.Location = new System.Drawing.Point(112, 24); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(64, 16); this.label2.TabIndex = 2; this.label2.Text = "characters"; // --- // txtSizeNew // --- this.txtSizeNew.Location = new System.Drawing.Point(52, 20); this.txtSizeNew.Name = "txtSizeNew"; this.txtSizeNew.Size = new System.Drawing.Size(56, 20); this.txtSizeNew.TabIndex = 1; this.txtSizeNew.Text = string.Empty; // --- // label1 // --- this.label1.Location = new System.Drawing.Point(12, 24); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(40, 16); this.label1.TabIndex = 0; this.label1.Text = "Size:"; // --- // groupStatus // --- this.groupStatus.Controls.Add(this.txtPosition); this.groupStatus.Controls.Add(this.label6); this.groupStatus.Controls.Add(this.txtContents); this.groupStatus.Controls.Add(this.label5); this.groupStatus.Controls.Add(this.label3); this.groupStatus.Controls.Add(this.txtSize); this.groupStatus.Controls.Add(this.label4); this.groupStatus.Controls.Add(this.btnUpdate); this.groupStatus.Location = new System.Drawing.Point(8, 68); this.groupStatus.Name = "groupStatus"; this.groupStatus.Size = new System.Drawing.Size(272, 280); this.groupStatus.TabIndex = 1; this.groupStatus.TabStop = false; this.groupStatus.Text = " RingBuffer Status"; // --- // txtPosition // --- this.txtPosition.Location = new System.Drawing.Point(68, 48); this.txtPosition.Name = "txtPosition"; this.txtPosition.ReadOnly = true; this.txtPosition.Size = new System.Drawing.Size(56, 20); this.txtPosition.TabIndex = 9; this.txtPosition.Text = string.Empty; // --- // label6 // --- this.label6.Location = new System.Drawing.Point(12, 52); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(52, 16); this.label6.TabIndex = 8; this.label6.Text = "Position:"; // --- // txtContents // --- this.txtContents.Location = new System.Drawing.Point(12, 100); this.txtContents.Multiline = true; this.txtContents.Name = "txtContents"; this.txtContents.ReadOnly = true; this.txtContents.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtContents.Size = new System.Drawing.Size(252, 176); this.txtContents.TabIndex = 7; this.txtContents.Text = string.Empty; // --- // label5 // --- this.label5.Location = new System.Drawing.Point(12, 80); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(116, 16); this.label5.TabIndex = 6; this.label5.Text = "RingBuffer Contents:"; // --- // label3 // --- this.label3.Location = new System.Drawing.Point(112, 24); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(64, 16); this.label3.TabIndex = 5; this.label3.Text = "characters"; // --- // txtSize // --- this.txtSize.Location = new System.Drawing.Point(52, 20); this.txtSize.Name = "txtSize"; this.txtSize.ReadOnly = true; this.txtSize.Size = new System.Drawing.Size(56, 20); this.txtSize.TabIndex = 4; this.txtSize.Text = string.Empty; // --- // label4 // --- this.label4.Location = new System.Drawing.Point(12, 24); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(40, 16); this.label4.TabIndex = 3; this.label4.Text = "Size:"; // --- // btnUpdate // --- this.btnUpdate.Location = new System.Drawing.Point(184, 20); this.btnUpdate.Name = "btnUpdate"; this.btnUpdate.TabIndex = 4; this.btnUpdate.Text = "Update"; this.btnUpdate.Click += new System.EventHandler(this.BtnUpdateClick); // --- // groupOperations // --- this.groupOperations.Controls.Add(this.btnAddLf); this.groupOperations.Controls.Add(this.btnAddCr); this.groupOperations.Controls.Add(this.btnGetNextLine); this.groupOperations.Controls.Add(this.btnConsume); this.groupOperations.Controls.Add(this.label10); this.groupOperations.Controls.Add(this.txtConsume); this.groupOperations.Controls.Add(this.label9); this.groupOperations.Controls.Add(this.txtDataReturn); this.groupOperations.Controls.Add(this.btnGetData); this.groupOperations.Controls.Add(this.btnAddCharArry); this.groupOperations.Controls.Add(this.btnAddString); this.groupOperations.Controls.Add(this.btnReset); this.groupOperations.Controls.Add(this.label7); this.groupOperations.Controls.Add(this.txtDataAdd); this.groupOperations.Controls.Add(this.label8); this.groupOperations.Controls.Add(this.txtCharReq); this.groupOperations.Location = new System.Drawing.Point(288, 8); this.groupOperations.Name = "groupOperations"; this.groupOperations.Size = new System.Drawing.Size(276, 340); this.groupOperations.TabIndex = 2; this.groupOperations.TabStop = false; this.groupOperations.Text = " Operations "; // --- // btnAddLf // --- this.btnAddLf.Location = new System.Drawing.Point(112, 128); this.btnAddLf.Name = "btnAddLf"; this.btnAddLf.Size = new System.Drawing.Size(92, 23); this.btnAddLf.TabIndex = 20; this.btnAddLf.Text = "Add LF (\\n)"; this.btnAddLf.Click += new System.EventHandler(this.BtnAddLfClick); // --- // btnAddCr // --- this.btnAddCr.Location = new System.Drawing.Point(12, 128); this.btnAddCr.Name = "btnAddCr"; this.btnAddCr.Size = new System.Drawing.Size(92, 23); this.btnAddCr.TabIndex = 19; this.btnAddCr.Text = "Add CR (\\r)"; this.btnAddCr.Click += new System.EventHandler(this.BtnAddCrClick); // --- // btnGetNextLine // --- this.btnGetNextLine.Location = new System.Drawing.Point(12, 296); this.btnGetNextLine.Name = "btnGetNextLine"; this.btnGetNextLine.Size = new System.Drawing.Size(112, 23); this.btnGetNextLine.TabIndex = 18; this.btnGetNextLine.Text = "Get Next Line"; this.btnGetNextLine.Click += new System.EventHandler(this.BtnGetNextLineClick); // --- // btnConsume // --- this.btnConsume.Location = new System.Drawing.Point(12, 264); this.btnConsume.Name = "btnConsume"; this.btnConsume.Size = new System.Drawing.Size(112, 23); this.btnConsume.TabIndex = 17; this.btnConsume.Text = "Consume Data"; this.btnConsume.Click += new System.EventHandler(this.BtnConsumeClick); // --- // label10 // --- this.label10.Location = new System.Drawing.Point(136, 268); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(64, 16); this.label10.TabIndex = 16; this.label10.Text = "characters"; // --- // txtConsume // --- this.txtConsume.Location = new System.Drawing.Point(200, 264); this.txtConsume.Name = "txtConsume"; this.txtConsume.Size = new System.Drawing.Size(64, 20); this.txtConsume.TabIndex = 15; this.txtConsume.Text = string.Empty; // --- // label9 // --- this.label9.Location = new System.Drawing.Point(12, 188); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(192, 16); this.label9.TabIndex = 14; this.label9.Text = "Return of Get Data or Get Next Line:"; // --- // txtDataReturn // --- this.txtDataReturn.Location = new System.Drawing.Point(12, 204); this.txtDataReturn.Multiline = true; this.txtDataReturn.Name = "txtDataReturn"; this.txtDataReturn.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtDataReturn.Size = new System.Drawing.Size(252, 52); this.txtDataReturn.TabIndex = 13; this.txtDataReturn.Text = string.Empty; // --- // btnGetData // --- this.btnGetData.Location = new System.Drawing.Point(12, 160); this.btnGetData.Name = "btnGetData"; this.btnGetData.Size = new System.Drawing.Size(112, 23); this.btnGetData.TabIndex = 12; this.btnGetData.Text = "Get Data"; this.btnGetData.Click += new System.EventHandler(this.BtnGetDataClick); // --- // btnAddCharArry // --- this.btnAddCharArry.Location = new System.Drawing.Point(132, 96); this.btnAddCharArry.Name = "btnAddCharArry"; this.btnAddCharArry.Size = new System.Drawing.Size(132, 23); this.btnAddCharArry.TabIndex = 6; this.btnAddCharArry.Text = "Add Data as Char Array"; this.btnAddCharArry.Click += new System.EventHandler(this.BtnAddCharArryClick); // --- // btnAddString // --- this.btnAddString.Location = new System.Drawing.Point(12, 96); this.btnAddString.Name = "btnAddString"; this.btnAddString.Size = new System.Drawing.Size(112, 23); this.btnAddString.TabIndex = 5; this.btnAddString.Text = "Add Data as String"; this.btnAddString.Click += new System.EventHandler(this.BtnAddStringClick); // --- // btnReset // --- this.btnReset.Location = new System.Drawing.Point(132, 296); this.btnReset.Name = "btnReset"; this.btnReset.Size = new System.Drawing.Size(68, 23); this.btnReset.TabIndex = 4; this.btnReset.Text = "Reset"; this.btnReset.Click += new System.EventHandler(this.BtnResetClick); // --- // label7 // --- this.label7.Location = new System.Drawing.Point(12, 20); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(100, 16); this.label7.TabIndex = 10; this.label7.Text = "Data to be added:"; // --- // txtDataAdd // --- this.txtDataAdd.Location = new System.Drawing.Point(12, 36); this.txtDataAdd.Multiline = true; this.txtDataAdd.Name = "txtDataAdd"; this.txtDataAdd.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtDataAdd.Size = new System.Drawing.Size(252, 52); this.txtDataAdd.TabIndex = 11; this.txtDataAdd.Text = string.Empty; // --- // label8 // --- this.label8.Location = new System.Drawing.Point(136, 164); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(64, 16); this.label8.TabIndex = 4; this.label8.Text = "characters"; // --- // txtCharReq // --- this.txtCharReq.Location = new System.Drawing.Point(200, 160); this.txtCharReq.Name = "txtCharReq"; this.txtCharReq.Size = new System.Drawing.Size(64, 20); this.txtCharReq.TabIndex = 4; this.txtCharReq.Text = string.Empty; // --- // bntUnitTests // --- this.bntUnitTests.Location = new System.Drawing.Point(448, 356); this.bntUnitTests.Name = "bntUnitTests"; this.bntUnitTests.Size = new System.Drawing.Size(116, 23); this.bntUnitTests.TabIndex = 5; this.bntUnitTests.Text = "Unit Tests"; // --- // MainForm // --- this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(568, 386); this.Controls.Add(this.bntUnitTests); this.Controls.Add(this.groupOperations); this.Controls.Add(this.groupStatus); this.Controls.Add(this.groupCreation); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "MainForm"; this.Text = "Ringbuffer Demo"; this.Load += new System.EventHandler(this.MainFormLoad); this.groupCreation.ResumeLayout(false); this.groupStatus.ResumeLayout(false); this.groupOperations.ResumeLayout(false); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] public static void Main() { Application.Run(new MainForm()); } // Main() /// <summary> /// Handles the Click event of the <c>btnCreate</c> control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance /// containing the event data.</param> private void BtnCreateClick(object sender, EventArgs e) { if (this.txtSizeNew.Text.Length > 0) { var n = int.Parse(this.txtSizeNew.Text); if (n > 0) { this.rb = new RingBuffer(n); } // if this.UpdateStatus(); } // if } // btnCreate_Click() /// <summary> /// Updates the status. /// </summary> private void UpdateStatus() { if (this.rb == null) { this.txtSize.Text = "-"; this.txtPosition.Text = "-"; this.txtContents.Text = string.Empty; } else { this.txtSize.Text = this.rb.Size.ToString(CultureInfo.InvariantCulture); this.txtPosition.Text = this.rb.Position.ToString(CultureInfo.InvariantCulture); this.txtContents.Text = this.rb.GetData(); } // if } // UpdateStatus() /// <summary> /// Handles the Click event of the <c>btnUpdate</c> control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance /// containing the event data.</param> private void BtnUpdateClick(object sender, EventArgs e) { this.UpdateStatus(); } // btnUpdate_Click() /// <summary> /// Handles the Click event of the <c>btnAddString</c> control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance /// containing the event data.</param> private void BtnAddStringClick(object sender, EventArgs e) { if (this.txtDataAdd.Text.Length > 0) { this.rb.AddData(this.txtDataAdd.Text); this.UpdateStatus(); } // if } // btnAddString_Click() /// <summary> /// Handles the Click event of the <c>btnAddCharArry</c> control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance /// containing the event data.</param> private void BtnAddCharArryClick(object sender, EventArgs e) { if (this.txtDataAdd.Text.Length > 0) { var ca = this.txtDataAdd.Text.ToCharArray(); this.rb.AddData(ca, ca.Length); this.UpdateStatus(); } // if } // btnAddCharArry_Click() /// <summary> /// Handles the Click event of the <c>btnGetData</c> control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance /// containing the event data.</param> private void BtnGetDataClick(object sender, EventArgs e) { if (this.txtCharReq.Text.Length > 0) { var n = int.Parse(this.txtCharReq.Text); if (n > 0) { this.txtDataReturn.Text = this.rb.GetData(n); } // if } else { this.txtDataReturn.Text = this.rb.GetData(); } // if this.UpdateStatus(); } // btnGetData_Click() /// <summary> /// Handles the Click event of the <c>btnConsume</c> control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance /// containing the event data.</param> private void BtnConsumeClick(object sender, EventArgs e) { if (this.txtConsume.Text.Length > 0) { int n = int.Parse(this.txtConsume.Text); if (n > 0) { this.rb.Consume(n); this.UpdateStatus(); } // if } // if } // btnConsume_Click() /// <summary> /// Handles the Click event of the <c>btnGetNextLine</c> control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance /// containing the event data.</param> private void BtnGetNextLineClick(object sender, EventArgs e) { this.txtDataReturn.Text = this.rb.GetNextLine(); this.UpdateStatus(); } // btnGetNextLine_Click() /// <summary> /// Handles the Click event of the <c>btnReset</c> control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance /// containing the event data.</param> private void BtnResetClick(object sender, EventArgs e) { this.rb.Reset(); this.UpdateStatus(); } // btnReset_Click() /// <summary> /// Handles the Load event of the MainForm control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance /// containing the event data.</param> private void MainFormLoad(object sender, EventArgs e) { this.UpdateStatus(); } /// <summary> /// Handles the Click event of the <c>btnAddCr</c> control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance /// containing the event data.</param> private void BtnAddCrClick(object sender, EventArgs e) { this.rb.AddData("\r"); } /// <summary> /// Handles the Click event of the <c>btnAddLf</c> control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance /// containing the event data.</param> private void BtnAddLfClick(object sender, EventArgs e) { this.rb.AddData("\n"); } // MainForm_Load() } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; namespace System.Linq.Expressions { /// <summary> /// Represents a try/catch/finally/fault block. /// /// The body is protected by the try block. /// The handlers consist of a set of <see cref="CatchBlock"/>s that can either be catch or filters. /// The fault runs if an exception is thrown. /// The finally runs regardless of how control exits the body. /// Only one of fault or finally can be supplied. /// The return type of the try block must match the return type of any associated catch statements. /// </summary> [DebuggerTypeProxy(typeof(Expression.TryExpressionProxy))] public sealed class TryExpression : Expression { private readonly Type _type; private readonly Expression _body; private readonly ReadOnlyCollection<CatchBlock> _handlers; private readonly Expression _finally; private readonly Expression _fault; internal TryExpression(Type type, Expression body, Expression @finally, Expression fault, ReadOnlyCollection<CatchBlock> handlers) { _type = type; _body = body; _handlers = handlers; _finally = @finally; _fault = fault; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get { return _type; } } /// <summary> /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.Try; } } /// <summary> /// Gets the <see cref="Expression"/> representing the body of the try block. /// </summary> public Expression Body { get { return _body; } } /// <summary> /// Gets the collection of <see cref="CatchBlock"/>s associated with the try block. /// </summary> public ReadOnlyCollection<CatchBlock> Handlers { get { return _handlers; } } /// <summary> /// Gets the <see cref="Expression"/> representing the finally block. /// </summary> public Expression Finally { get { return _finally; } } /// <summary> /// Gets the <see cref="Expression"/> representing the fault block. /// </summary> public Expression Fault { get { return _fault; } } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitTry(this); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="body">The <see cref="Body" /> property of the result.</param> /// <param name="handlers">The <see cref="Handlers" /> property of the result.</param> /// <param name="finally">The <see cref="Finally" /> property of the result.</param> /// <param name="fault">The <see cref="Fault" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public TryExpression Update(Expression body, IEnumerable<CatchBlock> handlers, Expression @finally, Expression fault) { if (body == Body && handlers == Handlers && @finally == Finally && fault == Fault) { return this; } return Expression.MakeTry(Type, body, @finally, fault, handlers); } } public partial class Expression { /// <summary> /// Creates a <see cref="TryExpression"/> representing a try block with a fault block and no catch statements. /// </summary> /// <param name="body">The body of the try block.</param> /// <param name="fault">The body of the fault block.</param> /// <returns>The created <see cref="TryExpression"/>.</returns> public static TryExpression TryFault(Expression body, Expression fault) { return MakeTry(null, body, null, fault, null); } /// <summary> /// Creates a <see cref="TryExpression"/> representing a try block with a finally block and no catch statements. /// </summary> /// <param name="body">The body of the try block.</param> /// <param name="finally">The body of the finally block.</param> /// <returns>The created <see cref="TryExpression"/>.</returns> public static TryExpression TryFinally(Expression body, Expression @finally) { return MakeTry(null, body, @finally, null, null); } /// <summary> /// Creates a <see cref="TryExpression"/> representing a try block with any number of catch statements and neither a fault nor finally block. /// </summary> /// <param name="body">The body of the try block.</param> /// <param name="handlers">The array of zero or more <see cref="CatchBlock"/>s representing the catch statements to be associated with the try block.</param> /// <returns>The created <see cref="TryExpression"/>.</returns> public static TryExpression TryCatch(Expression body, params CatchBlock[] handlers) { return MakeTry(null, body, null, null, handlers); } /// <summary> /// Creates a <see cref="TryExpression"/> representing a try block with any number of catch statements and a finally block. /// </summary> /// <param name="body">The body of the try block.</param> /// <param name="finally">The body of the finally block.</param> /// <param name="handlers">The array of zero or more <see cref="CatchBlock"/>s representing the catch statements to be associated with the try block.</param> /// <returns>The created <see cref="TryExpression"/>.</returns> public static TryExpression TryCatchFinally(Expression body, Expression @finally, params CatchBlock[] handlers) { return MakeTry(null, body, @finally, null, handlers); } /// <summary> /// Creates a <see cref="TryExpression"/> representing a try block with the specified elements. /// </summary> /// <param name="type">The result type of the try expression. If null, body and all handlers must have identical type.</param> /// <param name="body">The body of the try block.</param> /// <param name="finally">The body of the finally block. Pass null if the try block has no finally block associated with it.</param> /// <param name="fault">The body of the t block. Pass null if the try block has no fault block associated with it.</param> /// <param name="handlers">A collection of <see cref="CatchBlock"/>s representing the catch statements to be associated with the try block.</param> /// <returns>The created <see cref="TryExpression"/>.</returns> public static TryExpression MakeTry(Type type, Expression body, Expression @finally, Expression fault, IEnumerable<CatchBlock> handlers) { RequiresCanRead(body, nameof(body)); var @catch = handlers.ToReadOnly(); ContractUtils.RequiresNotNullItems(@catch, nameof(handlers)); ValidateTryAndCatchHaveSameType(type, body, @catch); if (fault != null) { if (@finally != null || @catch.Count > 0) { throw Error.FaultCannotHaveCatchOrFinally(nameof(fault)); } RequiresCanRead(fault, nameof(fault)); } else if (@finally != null) { RequiresCanRead(@finally, nameof(@finally)); } else if (@catch.Count == 0) { throw Error.TryMustHaveCatchFinallyOrFault(); } return new TryExpression(type ?? body.Type, body, @finally, fault, @catch); } //Validate that the body of the try expression must have the same type as the body of every try block. private static void ValidateTryAndCatchHaveSameType(Type type, Expression tryBody, ReadOnlyCollection<CatchBlock> handlers) { Debug.Assert(tryBody != null); // Type unification ... all parts must be reference assignable to "type" if (type != null) { if (type != typeof(void)) { if (!TypeUtils.AreReferenceAssignable(type, tryBody.Type)) { throw Error.ArgumentTypesMustMatch(); } foreach (var cb in handlers) { if (!TypeUtils.AreReferenceAssignable(type, cb.Body.Type)) { throw Error.ArgumentTypesMustMatch(); } } } } else if (tryBody.Type == typeof(void)) { //The body of every try block must be null or have void type. foreach (CatchBlock cb in handlers) { Debug.Assert(cb.Body != null); if (cb.Body.Type != typeof(void)) { throw Error.BodyOfCatchMustHaveSameTypeAsBodyOfTry(); } } } else { //Body of every catch must have the same type of body of try. type = tryBody.Type; foreach (CatchBlock cb in handlers) { Debug.Assert(cb.Body != null); if (!TypeUtils.AreEquivalent(cb.Body.Type, type)) { throw Error.BodyOfCatchMustHaveSameTypeAsBodyOfTry(); } } } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V10.Services; namespace Google.Ads.GoogleAds.Tests.V10.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedRecommendationServiceClientTest { [Category("Autogenerated")][Test] public void ApplyRecommendationRequestObject() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); ApplyRecommendationRequest request = new ApplyRecommendationRequest { CustomerId = "customer_id3b3724cb", Operations = { new ApplyRecommendationOperation(), }, PartialFailure = false, }; ApplyRecommendationResponse expectedResponse = new ApplyRecommendationResponse { Results = { new ApplyRecommendationResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.ApplyRecommendation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); ApplyRecommendationResponse response = client.ApplyRecommendation(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task ApplyRecommendationRequestObjectAsync() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); ApplyRecommendationRequest request = new ApplyRecommendationRequest { CustomerId = "customer_id3b3724cb", Operations = { new ApplyRecommendationOperation(), }, PartialFailure = false, }; ApplyRecommendationResponse expectedResponse = new ApplyRecommendationResponse { Results = { new ApplyRecommendationResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.ApplyRecommendationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ApplyRecommendationResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); ApplyRecommendationResponse responseCallSettings = await client.ApplyRecommendationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); ApplyRecommendationResponse responseCancellationToken = await client.ApplyRecommendationAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void ApplyRecommendation() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); ApplyRecommendationRequest request = new ApplyRecommendationRequest { CustomerId = "customer_id3b3724cb", Operations = { new ApplyRecommendationOperation(), }, }; ApplyRecommendationResponse expectedResponse = new ApplyRecommendationResponse { Results = { new ApplyRecommendationResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.ApplyRecommendation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); ApplyRecommendationResponse response = client.ApplyRecommendation(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task ApplyRecommendationAsync() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); ApplyRecommendationRequest request = new ApplyRecommendationRequest { CustomerId = "customer_id3b3724cb", Operations = { new ApplyRecommendationOperation(), }, }; ApplyRecommendationResponse expectedResponse = new ApplyRecommendationResponse { Results = { new ApplyRecommendationResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.ApplyRecommendationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ApplyRecommendationResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); ApplyRecommendationResponse responseCallSettings = await client.ApplyRecommendationAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); ApplyRecommendationResponse responseCancellationToken = await client.ApplyRecommendationAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void DismissRecommendationRequestObject() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); DismissRecommendationRequest request = new DismissRecommendationRequest { CustomerId = "customer_id3b3724cb", PartialFailure = false, Operations = { new DismissRecommendationRequest.Types.DismissRecommendationOperation(), }, }; DismissRecommendationResponse expectedResponse = new DismissRecommendationResponse { Results = { new DismissRecommendationResponse.Types.DismissRecommendationResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.DismissRecommendation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); DismissRecommendationResponse response = client.DismissRecommendation(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task DismissRecommendationRequestObjectAsync() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); DismissRecommendationRequest request = new DismissRecommendationRequest { CustomerId = "customer_id3b3724cb", PartialFailure = false, Operations = { new DismissRecommendationRequest.Types.DismissRecommendationOperation(), }, }; DismissRecommendationResponse expectedResponse = new DismissRecommendationResponse { Results = { new DismissRecommendationResponse.Types.DismissRecommendationResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.DismissRecommendationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DismissRecommendationResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); DismissRecommendationResponse responseCallSettings = await client.DismissRecommendationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); DismissRecommendationResponse responseCancellationToken = await client.DismissRecommendationAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void DismissRecommendation() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); DismissRecommendationRequest request = new DismissRecommendationRequest { CustomerId = "customer_id3b3724cb", Operations = { new DismissRecommendationRequest.Types.DismissRecommendationOperation(), }, }; DismissRecommendationResponse expectedResponse = new DismissRecommendationResponse { Results = { new DismissRecommendationResponse.Types.DismissRecommendationResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.DismissRecommendation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); DismissRecommendationResponse response = client.DismissRecommendation(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task DismissRecommendationAsync() { moq::Mock<RecommendationService.RecommendationServiceClient> mockGrpcClient = new moq::Mock<RecommendationService.RecommendationServiceClient>(moq::MockBehavior.Strict); DismissRecommendationRequest request = new DismissRecommendationRequest { CustomerId = "customer_id3b3724cb", Operations = { new DismissRecommendationRequest.Types.DismissRecommendationOperation(), }, }; DismissRecommendationResponse expectedResponse = new DismissRecommendationResponse { Results = { new DismissRecommendationResponse.Types.DismissRecommendationResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.DismissRecommendationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DismissRecommendationResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RecommendationServiceClient client = new RecommendationServiceClientImpl(mockGrpcClient.Object, null); DismissRecommendationResponse responseCallSettings = await client.DismissRecommendationAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); DismissRecommendationResponse responseCancellationToken = await client.DismissRecommendationAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
#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.Globalization; using System.Reflection; using System.Runtime.Serialization; using Newtonsoft.Json.Utilities; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Converters { /// <summary> /// Converts an <see cref="Enum"/> to and from its name string value. /// </summary> public class StringEnumConverter : JsonConverter { private readonly Dictionary<Type, BidirectionalDictionary<string, string>> _enumMemberNamesPerType = new Dictionary<Type, BidirectionalDictionary<string, string>>(); /// <summary> /// Gets or sets a value indicating whether the written enum text should be camel case. /// </summary> /// <value><c>true</c> if the written enum text will be camel case; otherwise, <c>false</c>.</value> public bool CamelCaseText { get; set; } /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param> /// <param name="value">The value.</param> /// <param name="serializer">The calling serializer.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { writer.WriteNull(); return; } Enum e = (Enum)value; string enumName = e.ToString("G"); if (char.IsNumber(enumName[0]) || enumName[0] == '-') { // enum value has no name so write number writer.WriteValue(value); } else { BidirectionalDictionary<string, string> map = GetEnumNameMap(e.GetType()); string[] names = enumName.Split(','); for (int i = 0; i < names.Length; i++) { string name = names[i].Trim(); string resolvedEnumName; map.TryGetByFirst(name, out resolvedEnumName); resolvedEnumName = resolvedEnumName ?? name; if (CamelCaseText) resolvedEnumName = StringUtils.ToCamelCase(resolvedEnumName); names[i] = resolvedEnumName; } string finalName = string.Join(", ", names); writer.WriteValue(finalName); } } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { bool isNullable = ReflectionUtils.IsNullableType(objectType); Type t = isNullable ? Nullable.GetUnderlyingType(objectType) : objectType; if (reader.TokenType == JsonToken.Null) { if (!ReflectionUtils.IsNullableType(objectType)) throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); return null; } try { if (reader.TokenType == JsonToken.String) { string enumText = reader.Value.ToString(); if (enumText == string.Empty && isNullable) return null; string finalEnumText; BidirectionalDictionary<string, string> map = GetEnumNameMap(t); if (enumText.IndexOf(',') != -1) { string[] names = enumText.Split(','); for (int i = 0; i < names.Length; i++) { string name = names[i].Trim(); names[i] = ResolvedEnumName(map, name); } finalEnumText = string.Join(", ", names); } else { finalEnumText = ResolvedEnumName(map, enumText); } return Enum.Parse(t, finalEnumText, true); } if (reader.TokenType == JsonToken.Integer) return ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, t); } catch (Exception ex) { throw JsonSerializationException.Create(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.FormatValueForPrint(reader.Value), objectType), ex); } throw JsonSerializationException.Create(reader, "Unexpected token when parsing enum. Expected String or Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } private static string ResolvedEnumName(BidirectionalDictionary<string, string> map, string enumText) { string resolvedEnumName; map.TryGetBySecond(enumText, out resolvedEnumName); resolvedEnumName = resolvedEnumName ?? enumText; return resolvedEnumName; } private BidirectionalDictionary<string, string> GetEnumNameMap(Type t) { BidirectionalDictionary<string, string> map; if (!_enumMemberNamesPerType.TryGetValue(t, out map)) { lock (_enumMemberNamesPerType) { if (_enumMemberNamesPerType.TryGetValue(t, out map)) return map; map = new BidirectionalDictionary<string, string>( StringComparer.OrdinalIgnoreCase, StringComparer.OrdinalIgnoreCase); foreach (FieldInfo f in t.GetFields()) { string n1 = f.Name; string n2; #if !NET20 n2 = f.GetCustomAttributes(typeof (EnumMemberAttribute), true) .Cast<EnumMemberAttribute>() .Select(a => a.Value) .SingleOrDefault() ?? f.Name; #else n2 = f.Name; #endif string s; if (map.TryGetBySecond(n2, out s)) { throw new InvalidOperationException("Enum name '{0}' already exists on enum '{1}'." .FormatWith(CultureInfo.InvariantCulture, n2, t.Name)); } map.Set(n1, n2); } _enumMemberNamesPerType[t] = map; } } return map; } /// <summary> /// Determines whether this instance can convert the specified object type. /// </summary> /// <param name="objectType">Type of the object.</param> /// <returns> /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type objectType) { Type t = (ReflectionUtils.IsNullableType(objectType)) ? Nullable.GetUnderlyingType(objectType) : objectType; return t.IsEnum(); } } }
using System; using Avalonia.Controls.Metadata; using Avalonia.Controls.Primitives; using Avalonia.Layout; using Avalonia.Media; namespace Avalonia.Controls { /// <summary> /// A control used to indicate the progress of an operation. /// </summary> [PseudoClasses(":vertical", ":horizontal", ":indeterminate")] public class ProgressBar : RangeBase { public class ProgressBarTemplateProperties : AvaloniaObject { private double _container2Width; private double _containerWidth; private double _containerAnimationStartPosition; private double _containerAnimationEndPosition; private double _container2AnimationStartPosition; private double _container2AnimationEndPosition; public static readonly DirectProperty<ProgressBarTemplateProperties, double> ContainerAnimationStartPositionProperty = AvaloniaProperty.RegisterDirect<ProgressBarTemplateProperties, double>( nameof(ContainerAnimationStartPosition), p => p.ContainerAnimationStartPosition, (p, o) => p.ContainerAnimationStartPosition = o, 0d); public static readonly DirectProperty<ProgressBarTemplateProperties, double> ContainerAnimationEndPositionProperty = AvaloniaProperty.RegisterDirect<ProgressBarTemplateProperties, double>( nameof(ContainerAnimationEndPosition), p => p.ContainerAnimationEndPosition, (p, o) => p.ContainerAnimationEndPosition = o, 0d); public static readonly DirectProperty<ProgressBarTemplateProperties, double> Container2AnimationStartPositionProperty = AvaloniaProperty.RegisterDirect<ProgressBarTemplateProperties, double>( nameof(Container2AnimationStartPosition), p => p.Container2AnimationStartPosition, (p, o) => p.Container2AnimationStartPosition = o, 0d); public static readonly DirectProperty<ProgressBarTemplateProperties, double> Container2AnimationEndPositionProperty = AvaloniaProperty.RegisterDirect<ProgressBarTemplateProperties, double>( nameof(Container2AnimationEndPosition), p => p.Container2AnimationEndPosition, (p, o) => p.Container2AnimationEndPosition = o); public static readonly DirectProperty<ProgressBarTemplateProperties, double> Container2WidthProperty = AvaloniaProperty.RegisterDirect<ProgressBarTemplateProperties, double>( nameof(Container2Width), p => p.Container2Width, (p, o) => p.Container2Width = o); public static readonly DirectProperty<ProgressBarTemplateProperties, double> ContainerWidthProperty = AvaloniaProperty.RegisterDirect<ProgressBarTemplateProperties, double>( nameof(ContainerWidth), p => p.ContainerWidth, (p, o) => p.ContainerWidth = o); public double ContainerAnimationStartPosition { get => _containerAnimationStartPosition; set => SetAndRaise(ContainerAnimationStartPositionProperty, ref _containerAnimationStartPosition, value); } public double ContainerAnimationEndPosition { get => _containerAnimationEndPosition; set => SetAndRaise(ContainerAnimationEndPositionProperty, ref _containerAnimationEndPosition, value); } public double Container2AnimationStartPosition { get => _container2AnimationStartPosition; set => SetAndRaise(Container2AnimationStartPositionProperty, ref _container2AnimationStartPosition, value); } public double Container2Width { get => _container2Width; set => SetAndRaise(Container2WidthProperty, ref _container2Width, value); } public double ContainerWidth { get => _containerWidth; set => SetAndRaise(ContainerWidthProperty, ref _containerWidth, value); } public double Container2AnimationEndPosition { get => _container2AnimationEndPosition; set => SetAndRaise(Container2AnimationEndPositionProperty, ref _container2AnimationEndPosition, value); } } private double _indeterminateStartingOffset; private double _indeterminateEndingOffset; private Border _indicator; public static readonly StyledProperty<bool> IsIndeterminateProperty = AvaloniaProperty.Register<ProgressBar, bool>(nameof(IsIndeterminate)); public static readonly StyledProperty<bool> ShowProgressTextProperty = AvaloniaProperty.Register<ProgressBar, bool>(nameof(ShowProgressText)); public static readonly StyledProperty<Orientation> OrientationProperty = AvaloniaProperty.Register<ProgressBar, Orientation>(nameof(Orientation), Orientation.Horizontal); [Obsolete("To be removed when Avalonia.Themes.Default is discontinued.")] public static readonly DirectProperty<ProgressBar, double> IndeterminateStartingOffsetProperty = AvaloniaProperty.RegisterDirect<ProgressBar, double>( nameof(IndeterminateStartingOffset), p => p.IndeterminateStartingOffset, (p, o) => p.IndeterminateStartingOffset = o); [Obsolete("To be removed when Avalonia.Themes.Default is discontinued.")] public static readonly DirectProperty<ProgressBar, double> IndeterminateEndingOffsetProperty = AvaloniaProperty.RegisterDirect<ProgressBar, double>( nameof(IndeterminateEndingOffset), p => p.IndeterminateEndingOffset, (p, o) => p.IndeterminateEndingOffset = o); [Obsolete("To be removed when Avalonia.Themes.Default is discontinued.")] public double IndeterminateStartingOffset { get => _indeterminateStartingOffset; set => SetAndRaise(IndeterminateStartingOffsetProperty, ref _indeterminateStartingOffset, value); } [Obsolete("To be removed when Avalonia.Themes.Default is discontinued.")] public double IndeterminateEndingOffset { get => _indeterminateEndingOffset; set => SetAndRaise(IndeterminateEndingOffsetProperty, ref _indeterminateEndingOffset, value); } static ProgressBar() { ValueProperty.Changed.AddClassHandler<ProgressBar>((x, e) => x.UpdateIndicatorWhenPropChanged(e)); IsIndeterminateProperty.Changed.AddClassHandler<ProgressBar>((x, e) => x.UpdateIndicatorWhenPropChanged(e)); } public ProgressBar() { UpdatePseudoClasses(IsIndeterminate, Orientation); } public ProgressBarTemplateProperties TemplateProperties { get; } = new ProgressBarTemplateProperties(); public bool IsIndeterminate { get => GetValue(IsIndeterminateProperty); set => SetValue(IsIndeterminateProperty, value); } public bool ShowProgressText { get => GetValue(ShowProgressTextProperty); set => SetValue(ShowProgressTextProperty, value); } public Orientation Orientation { get => GetValue(OrientationProperty); set => SetValue(OrientationProperty, value); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { UpdateIndicator(finalSize); return base.ArrangeOverride(finalSize); } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); if (change.Property == IsIndeterminateProperty) { UpdatePseudoClasses(change.NewValue.GetValueOrDefault<bool>(), null); } else if (change.Property == OrientationProperty) { UpdatePseudoClasses(null, change.NewValue.GetValueOrDefault<Orientation>()); } } /// <inheritdoc/> protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { _indicator = e.NameScope.Get<Border>("PART_Indicator"); UpdateIndicator(Bounds.Size); } private void UpdateIndicator(Size bounds) { if (_indicator != null) { if (IsIndeterminate) { // Pulled from ModernWPF. var dim = Orientation == Orientation.Horizontal ? bounds.Width : bounds.Height; var barIndicatorWidth = dim * 0.4; // Indicator width at 40% of ProgressBar var barIndicatorWidth2 = dim * 0.6; // Indicator width at 60% of ProgressBar TemplateProperties.ContainerWidth = barIndicatorWidth; TemplateProperties.Container2Width = barIndicatorWidth2; TemplateProperties.ContainerAnimationStartPosition = barIndicatorWidth * -1.8; // Position at -180% TemplateProperties.ContainerAnimationEndPosition = barIndicatorWidth * 3.0; // Position at 300% TemplateProperties.Container2AnimationStartPosition = barIndicatorWidth2 * -1.5; // Position at -150% TemplateProperties.Container2AnimationEndPosition = barIndicatorWidth2 * 1.66; // Position at 166% // Remove these properties when we switch to fluent as default and removed the old one. IndeterminateStartingOffset = -dim; IndeterminateEndingOffset = dim; var padding = Padding; var rectangle = new RectangleGeometry( new Rect( padding.Left, padding.Top, bounds.Width - (padding.Right + padding.Left), bounds.Height - (padding.Bottom + padding.Top) )); } else { double percent = Maximum == Minimum ? 1.0 : (Value - Minimum) / (Maximum - Minimum); if (Orientation == Orientation.Horizontal) _indicator.Width = bounds.Width * percent; else _indicator.Height = bounds.Height * percent; } } } private void UpdateIndicatorWhenPropChanged(AvaloniaPropertyChangedEventArgs e) { UpdateIndicator(Bounds.Size); } private void UpdatePseudoClasses( bool? isIndeterminate, Orientation? o) { if (isIndeterminate.HasValue) { PseudoClasses.Set(":indeterminate", isIndeterminate.Value); } if (o.HasValue) { PseudoClasses.Set(":vertical", o == Orientation.Vertical); PseudoClasses.Set(":horizontal", o == Orientation.Horizontal); } } } }
// 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 ConvertToVector256DoubleSingle() { var test = new SimpleUnaryOpTest__ConvertToVector256DoubleSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ConvertToVector256DoubleSingle { private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static Single[] _data = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar; private Vector128<Single> _fld; private SimpleUnaryOpTest__DataTable<Double, Single> _dataTable; static SimpleUnaryOpTest__ConvertToVector256DoubleSingle() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleUnaryOpTest__ConvertToVector256DoubleSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); } _dataTable = new SimpleUnaryOpTest__DataTable<Double, Single>(_data, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.ConvertToVector256Double( Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx.ConvertToVector256Double( Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx.ConvertToVector256Double( Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx).GetMethod(nameof(Avx.ConvertToVector256Double), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx).GetMethod(nameof(Avx.ConvertToVector256Double), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx).GetMethod(nameof(Avx.ConvertToVector256Double), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx.ConvertToVector256Double( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr); var result = Avx.ConvertToVector256Double(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)); var result = Avx.ConvertToVector256Double(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)); var result = Avx.ConvertToVector256Double(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ConvertToVector256DoubleSingle(); var result = Avx.ConvertToVector256Double(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx.ConvertToVector256Double(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> firstOp, void* result, [CallerMemberName] string method = "") { Single[] inArray = new Single[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Single[] inArray = new Single[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Single[] firstOp, Double[] result, [CallerMemberName] string method = "") { if (result[0] != (Double)(firstOp[0])) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (Double)(firstOp[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.ConvertToVector256Double)}(Vector128<Single>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using UnityEngine; using System.Collections.Generic; using UMA.CharacterSystem; namespace UMA { /// <summary> /// Gloal container for various UMA objects in the scene. /// </summary> public class UMAContext : UMAContextBase { /// <summary> /// The race library. /// </summary> public RaceLibraryBase raceLibrary; /// <summary> /// The slot library. /// </summary> public SlotLibraryBase slotLibrary; /// <summary> /// The overlay library. /// </summary> public OverlayLibraryBase overlayLibrary; public UMA.CharacterSystem.DynamicCharacterSystem dynamicCharacterSystem; #pragma warning disable 618 public override void Start() { if (!slotLibrary) { slotLibrary = GameObject.Find("SlotLibrary").GetComponent<SlotLibraryBase>(); } if (!raceLibrary) { raceLibrary = GameObject.Find("RaceLibrary").GetComponent<RaceLibraryBase>(); } if (!overlayLibrary) { overlayLibrary = GameObject.Find("OverlayLibrary").GetComponent<OverlayLibraryBase>(); } // Note: Removed null check so that this is always assigned if you have a UMAContextBase in your scene // This will avoid those occasions where someone drops in a bogus context in a test scene, and then // later loads a valid scene (and everything breaks) Instance = this; } /// <summary> /// Validates the library contents. /// </summary> public override void ValidateDictionaries() { slotLibrary.ValidateDictionary(); raceLibrary.ValidateDictionary(); overlayLibrary.ValidateDictionary(); if (dynamicCharacterSystem != null) { dynamicCharacterSystem.Refresh(false); dynamicCharacterSystem.RefreshRaceKeys(); } } /// <summary> /// Gets a race by name, if it has been added to the library /// </summary> /// <returns>The race.</returns> /// <param name="name">Name.</param> public override RaceData HasRace(string name) { return raceLibrary.HasRace(name); } /// <summary> /// Gets a race by name hash, if it has been added to the library. /// </summary> /// <returns>The race.</returns> /// <param name="nameHash">Name hash.</param> public override RaceData HasRace(int nameHash) { return raceLibrary.HasRace(nameHash); } public override void EnsureRaceKey(string name) { if (dynamicCharacterSystem != null) { dynamicCharacterSystem.EnsureRaceKey(name); } } /// <summary> /// Gets a race by name, if the library is a DynamicRaceLibrary it will try to find it. /// </summary> /// <returns>The race.</returns> /// <param name="name">Name.</param> public override RaceData GetRace(string name) { #if SUPER_LOGGING Debug.Log("Getting Race: " + name); #endif return raceLibrary.GetRace(name); } /// <summary> /// Gets a race by name hash, if the library is a DynamicRaceLibrary it will try to find it. /// </summary> /// <returns>The race.</returns> /// <param name="nameHash">Name hash.</param> public override RaceData GetRace(int nameHash) { return raceLibrary.GetRace(nameHash); } public override RaceData GetRaceWithUpdate(int nameHash, bool allowUpdate) { if (raceLibrary is DynamicRaceLibrary) { return (raceLibrary as DynamicRaceLibrary).GetRace(nameHash, allowUpdate); } return raceLibrary.GetRace(nameHash); } /// <summary> /// Array of all races in the context. /// </summary> /// <returns>The array of race data.</returns> public override RaceData[] GetAllRaces() { return raceLibrary.GetAllRaces(); } public override RaceData[] GetAllRacesBase() { if (raceLibrary is DynamicRaceLibrary) { return (raceLibrary as DynamicRaceLibrary).GetAllRacesBase(); } return raceLibrary.GetAllRaces(); } /// <summary> /// Add a race to the context. /// </summary> /// <param name="race">New race.</param> public override void AddRace(RaceData race) { raceLibrary.AddRace(race); raceLibrary.UpdateDictionary(); if (dynamicCharacterSystem != null) { dynamicCharacterSystem.RefreshRaceKeys(); } } /// <summary> /// Instantiate a slot by name. /// </summary> /// <returns>The slot.</returns> /// <param name="name">Name.</param> public override SlotData InstantiateSlot(string name) { #if SUPER_LOGGING Debug.Log("Instantiating slot: " + name); #endif return slotLibrary.InstantiateSlot(name); } /// <summary> /// Instantiate a slot by name hash. /// </summary> /// <returns>The slot.</returns> /// <param name="nameHash">Name hash.</param> public override SlotData InstantiateSlot(int nameHash) { return slotLibrary.InstantiateSlot(nameHash); } /// <summary> /// Instantiate a slot by name, with overlays. /// </summary> /// <returns>The slot.</returns> /// <param name="name">Name.</param> /// <param name="overlayList">Overlay list.</param> public override SlotData InstantiateSlot(string name, List<OverlayData> overlayList) { #if SUPER_LOGGING Debug.Log("Instantiating slot: " + name); #endif return slotLibrary.InstantiateSlot(name, overlayList); } /// <summary> /// Instantiate a slot by name hash, with overlays. /// </summary> /// <returns>The slot.</returns> /// <param name="nameHash">Name hash.</param> /// <param name="overlayList">Overlay list.</param> public override SlotData InstantiateSlot(int nameHash, List<OverlayData> overlayList) { return slotLibrary.InstantiateSlot(nameHash, overlayList); } /// <summary> /// Check for presence of a slot by name. /// </summary> /// <returns><c>True</c> if the slot exists in this context.</returns> /// <param name="name">Name.</param> public override bool HasSlot(string name) { if (slotLibrary.HasSlot(name)) return true; else { if (UMAAssetIndexer.Instance.GetAssetItem<SlotDataAsset>(name) != null) return true; } return false; } /// <summary> /// Check for presence of a slot by name hash. /// </summary> /// <returns><c>True</c> if the slot exists in this context.</returns> /// <param name="nameHash">Name hash.</param> public override bool HasSlot(int nameHash) { if (slotLibrary.HasSlot(nameHash)) return true; else { if (UMAAssetIndexer.Instance.GetAsset<SlotDataAsset>(nameHash) != null) return true; } return false; } /// <summary> /// Add a slot asset to the context. /// </summary> /// <param name="slot">New slot asset.</param> public override void AddSlotAsset(SlotDataAsset slot) { slotLibrary.AddSlotAsset(slot); } /// <summary> /// Check for presence of an overlay by name. /// </summary> /// <returns><c>True</c> if the overlay exists in this context.</returns> /// <param name="name">Name.</param> public override bool HasOverlay(string name) { return overlayLibrary.HasOverlay(name); } /// <summary> /// Check for presence of an overlay by name hash. /// </summary> /// <returns><c>True</c> if the overlay exists in this context.</returns> /// <param name="nameHash">Name hash.</param> public override bool HasOverlay(int nameHash) { return overlayLibrary.HasOverlay(nameHash); } /// <summary> /// Instantiate an overlay by name. /// </summary> /// <returns>The overlay.</returns> /// <param name="name">Name.</param> public override OverlayData InstantiateOverlay(string name) { #if SUPER_LOGGING Debug.Log("Instantiating Overlay: " + name); #endif return overlayLibrary.InstantiateOverlay(name); } /// <summary> /// Instantiate an overlay by name hash. /// </summary> /// <returns>The overlay.</returns> /// <param name="nameHash">Name hash.</param> public override OverlayData InstantiateOverlay(int nameHash) { return overlayLibrary.InstantiateOverlay(nameHash); } /// <summary> /// Instantiate a tinted overlay by name. /// </summary> /// <returns>The overlay.</returns> /// <param name="name">Name.</param> /// <param name="color">Color.</param> public override OverlayData InstantiateOverlay(string name, Color color) { #if SUPER_LOGGING Debug.Log("Instantiating Overlay: " + name); #endif return overlayLibrary.InstantiateOverlay(name, color); } /// <summary> /// Instantiate a tinted overlay by name hash. /// </summary> /// <returns>The overlay.</returns> /// <param name="nameHash">Name hash.</param> /// <param name="color">Color.</param> public override OverlayData InstantiateOverlay(int nameHash, Color color) { return overlayLibrary.InstantiateOverlay(nameHash, color); } /// <summary> /// Add an overlay asset to the context. /// </summary> /// <param name="overlay">New overlay asset.</param> public override void AddOverlayAsset(OverlayDataAsset overlay) { overlayLibrary.AddOverlayAsset(overlay); } // Get all DNA public override List<DynamicUMADnaAsset> GetAllDNA() { return UMAAssetIndexer.Instance.GetAllAssets<DynamicUMADnaAsset>(); } // Get a DNA Asset By Name public override DynamicUMADnaAsset GetDNA(string Name) { return UMAAssetIndexer.Instance.GetAsset<DynamicUMADnaAsset>(Name); } public override RuntimeAnimatorController GetAnimatorController(string Name) { return UMAAssetIndexer.Instance.GetAsset<RuntimeAnimatorController>(Name); } public override List<RuntimeAnimatorController> GetAllAnimatorControllers() { return UMAAssetIndexer.Instance.GetAllAssets<RuntimeAnimatorController>(); } public override void AddRecipe(UMATextRecipe recipe) { dynamicCharacterSystem.AddRecipe(recipe); } public override UMATextRecipe GetRecipe(string filename, bool dynamicallyAdd = true) { return dynamicCharacterSystem.GetRecipe(filename, dynamicallyAdd); } public override UMARecipeBase GetBaseRecipe(string filename, bool dynamicallyAdd) { return GetRecipe(filename, dynamicallyAdd); } public override string GetCharacterRecipe(string filename) { if (dynamicCharacterSystem.CharacterRecipes.ContainsKey(filename)) return dynamicCharacterSystem.CharacterRecipes[filename]; return ""; } public override List<string> GetRecipeFiles() { List<string> keys = new List<string>(); keys.AddRange(dynamicCharacterSystem.CharacterRecipes.Keys); return keys; } public override bool HasRecipe(string Name) { if (dynamicCharacterSystem == null) return false; return dynamicCharacterSystem.RecipeIndex.ContainsKey(Name); } /// <summary> /// This checks through everything, not just the currently loaded index. /// </summary> /// <param name="recipeName"></param> /// <returns></returns> public override bool CheckRecipeAvailability(string recipeName) { return dynamicCharacterSystem.CheckRecipeAvailability(recipeName); } public override List<string> GetRecipeNamesForRaceSlot(string race, string slot) { return dynamicCharacterSystem.GetRecipeNamesForRaceSlot(race, slot); } public override List<UMARecipeBase> GetRecipesForRaceSlot(string race, string slot) { return dynamicCharacterSystem.GetRecipesForRaceSlot(race, slot); } public override Dictionary<string, List<UMATextRecipe>> GetRecipes(string raceName) { return dynamicCharacterSystem.Recipes[raceName]; } } }
// // Copyright (c) 2008-2012, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Vhdx { using System; using System.Collections.Generic; using System.Globalization; using System.IO; /// <summary> /// Represents a VHDX-backed disk. /// </summary> public sealed class Disk : VirtualDisk { /// <summary> /// The list of files that make up the disk. /// </summary> private List<DiscUtils.Tuple<DiskImageFile, Ownership>> _files; /// <summary> /// The stream representing the disk's contents. /// </summary> private SparseStream _content; /// <summary> /// Initializes a new instance of the Disk class. Differencing disks are not supported. /// </summary> /// <param name="stream">The stream to read</param> /// <param name="ownsStream">Indicates if the new instance should control the lifetime of the stream.</param> public Disk(Stream stream, Ownership ownsStream) { _files = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>(); _files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(new DiskImageFile(stream, ownsStream), Ownership.Dispose)); if (_files[0].First.NeedsParent) { throw new NotSupportedException("Differencing disks cannot be opened from a stream"); } } /// <summary> /// Initializes a new instance of the Disk class. Differencing disks are supported. /// </summary> /// <param name="path">The path to the disk image</param> public Disk(string path) { DiskImageFile file = new DiskImageFile(path, FileAccess.ReadWrite); _files = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>(); _files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(file, Ownership.Dispose)); ResolveFileChain(); } /// <summary> /// Initializes a new instance of the Disk class. Differencing disks are supported. /// </summary> /// <param name="path">The path to the disk image</param> /// <param name="access">The access requested to the disk</param> public Disk(string path, FileAccess access) { DiskImageFile file = new DiskImageFile(path, access); _files = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>(); _files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(file, Ownership.Dispose)); ResolveFileChain(); } /// <summary> /// Initializes a new instance of the Disk class. Differencing disks are supported. /// </summary> /// <param name="fileSystem">The file system containing the disk.</param> /// <param name="path">The file system relative path to the disk.</param> /// <param name="access">The access requested to the disk.</param> public Disk(DiscFileSystem fileSystem, string path, FileAccess access) { FileLocator fileLocator = new DiscFileLocator(fileSystem, Utilities.GetDirectoryFromPath(path)); DiskImageFile file = new DiskImageFile(fileLocator, Utilities.GetFileFromPath(path), access); _files = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>(); _files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(file, Ownership.Dispose)); ResolveFileChain(); } /// <summary> /// Initializes a new instance of the Disk class. /// </summary> /// <param name="files">The set of image files</param> /// <param name="ownsFiles">Indicates if the new instance controls the lifetime of the image files</param> /// <remarks>The disks shound be ordered with the first file referencing the second, etc. The final /// file must not require any parent.</remarks> public Disk(IList<DiskImageFile> files, Ownership ownsFiles) { if (files == null || files.Count == 0) { throw new ArgumentException("At least one file must be provided"); } if (files[files.Count - 1].NeedsParent) { throw new ArgumentException("Final image file needs a parent"); } List<DiscUtils.Tuple<DiskImageFile, Ownership>> tempList = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>(files.Count); for (int i = 0; i < files.Count - 1; ++i) { if (!files[i].NeedsParent) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "File at index {0} does not have a parent disk", i)); } if (files[i].ParentUniqueId != files[i + 1].UniqueId) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "File at index {0} is not the parent of file at index {1} - Unique Ids don't match", i + 1, i)); } tempList.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(files[i], ownsFiles)); } tempList.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(files[files.Count - 1], ownsFiles)); _files = tempList; } /// <summary> /// Initializes a new instance of the Disk class. Differencing disks are supported. /// </summary> /// <param name="locator">The locator to access relative files</param> /// <param name="path">The path to the disk image</param> /// <param name="access">The access requested to the disk</param> internal Disk(FileLocator locator, string path, FileAccess access) { DiskImageFile file = new DiskImageFile(locator, path, access); _files = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>(); _files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(file, Ownership.Dispose)); ResolveFileChain(); } /// <summary> /// Initializes a new instance of the Disk class. Differencing disks are not supported. /// </summary> /// <param name="file">The file containing the disk</param> /// <param name="ownsFile">Indicates if the new instance should control the lifetime of the file.</param> private Disk(DiskImageFile file, Ownership ownsFile) { _files = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>(); _files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(file, ownsFile)); ResolveFileChain(); } /// <summary> /// Initializes a new instance of the Disk class. Differencing disks are supported. /// </summary> /// <param name="file">The file containing the disk</param> /// <param name="ownsFile">Indicates if the new instance should control the lifetime of the file.</param> /// <param name="parentLocator">Object used to locate the parent disk</param> /// <param name="parentPath">Path to the parent disk (if required)</param> private Disk(DiskImageFile file, Ownership ownsFile, FileLocator parentLocator, string parentPath) { _files = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>(); _files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(file, ownsFile)); if (file.NeedsParent) { _files.Add( new DiscUtils.Tuple<DiskImageFile, Ownership>( new DiskImageFile(parentLocator, parentPath, FileAccess.Read), Ownership.Dispose)); ResolveFileChain(); } } /// <summary> /// Initializes a new instance of the Disk class. Differencing disks are supported. /// </summary> /// <param name="file">The file containing the disk</param> /// <param name="ownsFile">Indicates if the new instance should control the lifetime of the file.</param> /// <param name="parentFile">The file containing the disk's parent</param> /// <param name="ownsParent">Indicates if the new instance should control the lifetime of the parentFile</param> private Disk(DiskImageFile file, Ownership ownsFile, DiskImageFile parentFile, Ownership ownsParent) { _files = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>(); _files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(file, ownsFile)); if (file.NeedsParent) { _files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(parentFile, ownsParent)); ResolveFileChain(); } else { if (parentFile != null && ownsParent == Ownership.Dispose) { parentFile.Dispose(); } } } /// <summary> /// Gets the geometry of the disk. /// </summary> public override Geometry Geometry { get { return _files[0].First.Geometry; } } /// <summary> /// Gets the type of disk represented by this object. /// </summary> public override VirtualDiskClass DiskClass { get { return VirtualDiskClass.HardDisk; } } /// <summary> /// Gets the capacity of the disk (in bytes). /// </summary> public override long Capacity { get { return _files[0].First.Capacity; } } /// <summary> /// Gets the content of the disk as a stream. /// </summary> /// <remarks>Note the returned stream is not guaranteed to be at any particular position. The actual position /// will depend on the last partition table/file system activity, since all access to the disk contents pass /// through a single stream instance. Set the stream position before accessing the stream.</remarks> public override SparseStream Content { get { if (_content == null) { SparseStream stream = null; for (int i = _files.Count - 1; i >= 0; --i) { stream = _files[i].First.OpenContent(stream, Ownership.Dispose); } _content = stream; } return _content; } } /// <summary> /// Gets the layers that make up the disk. /// </summary> public override IEnumerable<VirtualDiskLayer> Layers { get { foreach (var file in _files) { yield return file.First as VirtualDiskLayer; } } } /// <summary> /// Gets information about the type of disk. /// </summary> /// <remarks>This property provides access to meta-data about the disk format, for example whether the /// BIOS geometry is preserved in the disk file.</remarks> public override VirtualDiskTypeInfo DiskTypeInfo { get { return DiskFactory.MakeDiskTypeInfo(_files[_files.Count - 1].First.IsSparse ? "dynamic" : "fixed"); } } /// <summary> /// Initializes a stream as a fixed-sized VHDX file. /// </summary> /// <param name="stream">The stream to initialize.</param> /// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param> /// <param name="capacity">The desired capacity of the new disk</param> /// <returns>An object that accesses the stream as a VHDX file</returns> public static Disk InitializeFixed(Stream stream, Ownership ownsStream, long capacity) { return InitializeFixed(stream, ownsStream, capacity, null); } /// <summary> /// Initializes a stream as a fixed-sized VHDX file. /// </summary> /// <param name="stream">The stream to initialize.</param> /// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param> /// <param name="capacity">The desired capacity of the new disk</param> /// <param name="geometry">The desired geometry of the new disk, or <c>null</c> for default</param> /// <returns>An object that accesses the stream as a VHDX file</returns> public static Disk InitializeFixed(Stream stream, Ownership ownsStream, long capacity, Geometry geometry) { return new Disk(DiskImageFile.InitializeFixed(stream, ownsStream, capacity, geometry), Ownership.Dispose); } /// <summary> /// Initializes a stream as a dynamically-sized VHDX file. /// </summary> /// <param name="stream">The stream to initialize.</param> /// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param> /// <param name="capacity">The desired capacity of the new disk</param> /// <returns>An object that accesses the stream as a VHDX file</returns> public static Disk InitializeDynamic(Stream stream, Ownership ownsStream, long capacity) { return InitializeDynamic(stream, ownsStream, capacity, null); } /// <summary> /// Initializes a stream as a dynamically-sized VHDX file. /// </summary> /// <param name="stream">The stream to initialize.</param> /// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param> /// <param name="capacity">The desired capacity of the new disk</param> /// <param name="geometry">The desired geometry of the new disk, or <c>null</c> for default</param> /// <returns>An object that accesses the stream as a VHDX file</returns> public static Disk InitializeDynamic(Stream stream, Ownership ownsStream, long capacity, Geometry geometry) { return new Disk(DiskImageFile.InitializeDynamic(stream, ownsStream, capacity, geometry), Ownership.Dispose); } /// <summary> /// Initializes a stream as a dynamically-sized VHDX file. /// </summary> /// <param name="stream">The stream to initialize.</param> /// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param> /// <param name="capacity">The desired capacity of the new disk</param> /// <param name="blockSize">The size of each block (unit of allocation)</param> /// <returns>An object that accesses the stream as a VHDX file</returns> public static Disk InitializeDynamic(Stream stream, Ownership ownsStream, long capacity, long blockSize) { return new Disk(DiskImageFile.InitializeDynamic(stream, ownsStream, capacity, blockSize), Ownership.Dispose); } /// <summary> /// Creates a new VHDX differencing disk file. /// </summary> /// <param name="path">The path to the new disk file</param> /// <param name="parentPath">The path to the parent disk file</param> /// <returns>An object that accesses the new file as a Disk</returns> public static Disk InitializeDifferencing(string path, string parentPath) { LocalFileLocator parentLocator = new LocalFileLocator(Path.GetDirectoryName(parentPath)); string parentFileName = Path.GetFileName(parentPath); DiskImageFile newFile; using (DiskImageFile parent = new DiskImageFile(parentLocator, parentFileName, FileAccess.Read)) { LocalFileLocator locator = new LocalFileLocator(Path.GetDirectoryName(path)); newFile = parent.CreateDifferencing(locator, Path.GetFileName(path)); } return new Disk(newFile, Ownership.Dispose, parentLocator, parentFileName); } /// <summary> /// Initializes a stream as a differencing disk VHDX file. /// </summary> /// <param name="stream">The stream to initialize.</param> /// <param name="ownsStream">Indicates if the new instance controls the lifetime of the <paramref name="stream"/>.</param> /// <param name="parent">The disk this file is a different from.</param> /// <param name="ownsParent">Indicates if the new instance controls the lifetime of the <paramref name="parent"/> file.</param> /// <param name="parentAbsolutePath">The full path to the parent disk.</param> /// <param name="parentRelativePath">The relative path from the new disk to the parent disk.</param> /// <param name="parentModificationTime">The time the parent disk's file was last modified (from file system).</param> /// <returns>An object that accesses the stream as a VHDX file</returns> public static Disk InitializeDifferencing( Stream stream, Ownership ownsStream, DiskImageFile parent, Ownership ownsParent, string parentAbsolutePath, string parentRelativePath, DateTime parentModificationTime) { DiskImageFile file = DiskImageFile.InitializeDifferencing(stream, ownsStream, parent, parentAbsolutePath, parentRelativePath, parentModificationTime); return new Disk(file, Ownership.Dispose, parent, ownsParent); } /// <summary> /// Create a new differencing disk, possibly within an existing disk. /// </summary> /// <param name="fileSystem">The file system to create the disk on</param> /// <param name="path">The path (or URI) for the disk to create</param> /// <returns>The newly created disk</returns> public override VirtualDisk CreateDifferencingDisk(DiscFileSystem fileSystem, string path) { FileLocator locator = new DiscFileLocator(fileSystem, Utilities.GetDirectoryFromPath(path)); DiskImageFile file = _files[0].First.CreateDifferencing(locator, Utilities.GetFileFromPath(path)); return new Disk(file, Ownership.Dispose); } /// <summary> /// Create a new differencing disk. /// </summary> /// <param name="path">The path (or URI) for the disk to create</param> /// <returns>The newly created disk</returns> public override VirtualDisk CreateDifferencingDisk(string path) { FileLocator locator = new LocalFileLocator(Path.GetDirectoryName(path)); DiskImageFile file = _files[0].First.CreateDifferencing(locator, Path.GetFileName(path)); return new Disk(file, Ownership.Dispose); } internal static Disk InitializeFixed(FileLocator fileLocator, string path, long capacity, Geometry geometry) { return new Disk(DiskImageFile.InitializeFixed(fileLocator, path, capacity, geometry), Ownership.Dispose); } /// <summary> /// Disposes of underlying resources. /// </summary> /// <param name="disposing">Set to <c>true</c> if called within Dispose(), /// else <c>false</c>.</param> protected override void Dispose(bool disposing) { try { if (disposing) { if (_content != null) { _content.Dispose(); _content = null; } if (_files != null) { foreach (var record in _files) { if (record.Second == Ownership.Dispose) { record.First.Dispose(); } } _files = null; } } } finally { base.Dispose(disposing); } } private void ResolveFileChain() { DiskImageFile file = _files[_files.Count - 1].First; while (file.NeedsParent) { FileLocator fileLocator = file.RelativeFileLocator; bool found = false; foreach (string testPath in file.GetParentLocations()) { if (fileLocator.Exists(testPath)) { DiskImageFile newFile = new DiskImageFile(fileLocator, testPath, FileAccess.Read); if (newFile.UniqueId != file.ParentUniqueId) { throw new IOException(string.Format(CultureInfo.InstalledUICulture, "Invalid disk chain found looking for parent with id {0}, found {1} with id {2}", file.ParentUniqueId, newFile.FullPath, newFile.UniqueId)); } file = newFile; _files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(file, Ownership.Dispose)); found = true; break; } } if (!found) { throw new IOException(string.Format(CultureInfo.InvariantCulture, "Failed to find parent for disk '{0}'", file.FullPath)); } } } } }
/* * Copyright (c) 2013 Calvin Rien * * Based on the JSON parser by Patrick van Bergen * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html * * Simplified it so that it doesn't throw exceptions * and can be used in Unity iPhone with maximum code stripping. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; namespace AssetBundleGraph { // Example usage: // // using UnityEngine; // using System.Collections; // using System.Collections.Generic; // using MiniJSON; // // public class MiniJSONTest : MonoBehaviour { // void Start () { // var jsonString = "{ \"array\": [1.44,2,3], " + // "\"object\": {\"key1\":\"value1\", \"key2\":256}, " + // "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " + // "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " + // "\"int\": 65536, " + // "\"float\": 3.1415926, " + // "\"bool\": true, " + // "\"null\": null }"; // // var dict = Json.Deserialize(jsonString) as Dictionary<string,object>; // // LogUtility.Logger.Log("deserialized: " + dict.GetType()); // LogUtility.Logger.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]); // LogUtility.Logger.Log("dict['string']: " + (string) dict["string"]); // LogUtility.Logger.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles // LogUtility.Logger.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs // LogUtility.Logger.Log("dict['unicode']: " + (string) dict["unicode"]); // // var str = Json.Serialize(dict); // // LogUtility.Logger.Log("serialized: " + str); // } // } /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary. /// All numbers are parsed to doubles. /// </summary> public static class Json { /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An List&lt;object&gt;, a Dictionary&lt;string, object&gt;, a double, an integer,a string, null, true, or false</returns> public static object Deserialize(string json) { // save the string for debug information if (json == null) { return null; } return Parser.Parse(json); } sealed class Parser : IDisposable { const string WORD_BREAK = "{}[],:\""; public static bool IsWordBreak(char c) { return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1; } enum TOKEN { NONE, CURLY_OPEN, CURLY_CLOSE, SQUARED_OPEN, SQUARED_CLOSE, COLON, COMMA, STRING, NUMBER, TRUE, FALSE, NULL }; StringReader json; Parser(string jsonString) { json = new StringReader(jsonString); } public static object Parse(string jsonString) { using (var instance = new Parser(jsonString)) { return instance.ParseValue(); } } public void Dispose() { json.Dispose(); json = null; } Dictionary<string, object> ParseObject() { Dictionary<string, object> table = new Dictionary<string, object>(); // ditch opening brace json.Read(); // { while (true) { switch (NextToken) { case TOKEN.NONE: return null; case TOKEN.COMMA: continue; case TOKEN.CURLY_CLOSE: return table; default: // name string name = ParseString(); if (name == null) { return null; } // : if (NextToken != TOKEN.COLON) { return null; } // ditch the colon json.Read(); // value table[name] = ParseValue(); break; } } } List<object> ParseArray() { List<object> array = new List<object>(); // ditch opening bracket json.Read(); // [ var parsing = true; while (parsing) { TOKEN nextToken = NextToken; switch (nextToken) { case TOKEN.NONE: return null; case TOKEN.COMMA: continue; case TOKEN.SQUARED_CLOSE: parsing = false; break; default: object value = ParseByToken(nextToken); array.Add(value); break; } } return array; } object ParseValue() { TOKEN nextToken = NextToken; return ParseByToken(nextToken); } object ParseByToken(TOKEN token) { switch (token) { case TOKEN.STRING: return ParseString(); case TOKEN.NUMBER: return ParseNumber(); case TOKEN.CURLY_OPEN: return ParseObject(); case TOKEN.SQUARED_OPEN: return ParseArray(); case TOKEN.TRUE: return true; case TOKEN.FALSE: return false; case TOKEN.NULL: return null; default: return null; } } string ParseString() { StringBuilder s = new StringBuilder(); char c; // ditch opening quote json.Read(); bool parsing = true; while (parsing) { if (json.Peek() == -1) { parsing = false; break; } c = NextChar; switch (c) { case '"': parsing = false; break; case '\\': if (json.Peek() == -1) { parsing = false; break; } c = NextChar; switch (c) { case '"': case '\\': case '/': s.Append(c); break; case 'b': s.Append('\b'); break; case 'f': s.Append('\f'); break; case 'n': s.Append('\n'); break; case 'r': s.Append('\r'); break; case 't': s.Append('\t'); break; case 'u': var hex = new char[4]; for (int i=0; i< 4; i++) { hex[i] = NextChar; } s.Append((char) Convert.ToInt32(new string(hex), 16)); break; } break; default: s.Append(c); break; } } return s.ToString(); } object ParseNumber() { string number = NextWord; if (number.IndexOf('.') == -1) { long parsedInt; Int64.TryParse(number, out parsedInt); return parsedInt; } double parsedDouble; Double.TryParse(number, out parsedDouble); return parsedDouble; } void EatWhitespace() { while (Char.IsWhiteSpace(PeekChar)) { json.Read(); if (json.Peek() == -1) { break; } } } char PeekChar { get { return Convert.ToChar(json.Peek()); } } char NextChar { get { return Convert.ToChar(json.Read()); } } string NextWord { get { StringBuilder word = new StringBuilder(); while (!IsWordBreak(PeekChar)) { word.Append(NextChar); if (json.Peek() == -1) { break; } } return word.ToString(); } } TOKEN NextToken { get { EatWhitespace(); if (json.Peek() == -1) { return TOKEN.NONE; } switch (PeekChar) { case '{': return TOKEN.CURLY_OPEN; case '}': json.Read(); return TOKEN.CURLY_CLOSE; case '[': return TOKEN.SQUARED_OPEN; case ']': json.Read(); return TOKEN.SQUARED_CLOSE; case ',': json.Read(); return TOKEN.COMMA; case '"': return TOKEN.STRING; case ':': return TOKEN.COLON; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return TOKEN.NUMBER; } switch (NextWord) { case "false": return TOKEN.FALSE; case "true": return TOKEN.TRUE; case "null": return TOKEN.NULL; } return TOKEN.NONE; } } } /// <summary> /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string /// </summary> /// <param name="json">A Dictionary&lt;string, object&gt; / List&lt;object&gt;</param> /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns> public static string Serialize(object obj) { return Serializer.Serialize(obj); } sealed class Serializer { StringBuilder builder; Serializer() { builder = new StringBuilder(); } public static string Serialize(object obj) { var instance = new Serializer(); instance.SerializeValue(obj); return instance.builder.ToString(); } void SerializeValue(object value) { IList asList; IDictionary asDict; string asStr; if (value == null) { builder.Append("null"); } else if ((asStr = value as string) != null) { SerializeString(asStr); } else if (value is bool) { builder.Append((bool) value ? "true" : "false"); } else if ((asList = value as IList) != null) { SerializeArray(asList); } else if ((asDict = value as IDictionary) != null) { SerializeObject(asDict); } else if (value is char) { SerializeString(new string((char) value, 1)); } else { SerializeOther(value); } } void SerializeObject(IDictionary obj) { bool first = true; builder.Append('{'); foreach (object e in obj.Keys) { if (!first) { builder.Append(','); } SerializeString(e.ToString()); builder.Append(':'); SerializeValue(obj[e]); first = false; } builder.Append('}'); } void SerializeArray(IList anArray) { builder.Append('['); bool first = true; foreach (object obj in anArray) { if (!first) { builder.Append(','); } SerializeValue(obj); first = false; } builder.Append(']'); } void SerializeString(string str) { builder.Append('\"'); char[] charArray = str.ToCharArray(); foreach (var c in charArray) { switch (c) { case '"': builder.Append("\\\""); break; case '\\': builder.Append("\\\\"); break; case '\b': builder.Append("\\b"); break; case '\f': builder.Append("\\f"); break; case '\n': builder.Append("\\n"); break; case '\r': builder.Append("\\r"); break; case '\t': builder.Append("\\t"); break; default: int codepoint = Convert.ToInt32(c); if ((codepoint >= 32) && (codepoint <= 126)) { builder.Append(c); } else { builder.Append("\\u"); builder.Append(codepoint.ToString("x4")); } break; } } builder.Append('\"'); } void SerializeOther(object value) { // NOTE: decimals lose precision during serialization. // They always have, I'm just letting you know. // Previously floats and doubles lost precision too. if (value is float) { builder.Append(((float) value).ToString("R")); } else if (value is int || value is uint || value is long || value is sbyte || value is byte || value is short || value is ushort || value is ulong) { builder.Append(value); } else if (value is double || value is decimal) { builder.Append(Convert.ToDouble(value).ToString("R")); } else { SerializeString(value.ToString()); } } } public static string Prettify (string sourceJson) { var lines = sourceJson .Replace("{", "{\n").Replace("}", "\n}") .Replace("[", "[\n").Replace("]", "\n]") .Replace(",", ",\n") .Split('\n'); Func<string, int, string> indents = (string baseLine, int indentDepth) => { var indentsStr = string.Empty; for (var i = 0; i < indentDepth; i++) indentsStr += "\t"; return indentsStr + baseLine; }; var indent = 0; for (var i = 0; i < lines.Length; i++) { var line = lines[i]; // reduce indent for "}" if (line.Contains("}") || line.Contains("]")) { indent--; } /* adopt indent. */ lines[i] = indents(lines[i], indent); // indent continued all line after "{" if (line.Contains("{") || line.Contains("[")) { indent++; continue; } } return string.Join("\n", lines); } } }
// 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.Globalization; using System.IO; using System.Reflection; using System.Reflection.Emit; using System.Runtime.Remoting; using Xunit; namespace System.Tests { public partial class ActivatorTests : RemoteExecutorTestBase { [Fact] public void CreateInstance_NonPublicValueTypeWithPrivateDefaultConstructor_Success() { AssemblyName assemblyName = new AssemblyName("Assembly"); AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type", TypeAttributes.Public, typeof(ValueType)); FieldBuilder fieldBuilder = typeBuilder.DefineField("_field", typeof(int), FieldAttributes.Public); ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Private | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.HideBySig, CallingConventions.Standard, new Type[0]); ILGenerator generator = constructorBuilder.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldc_I4, -1); generator.Emit(OpCodes.Stfld, fieldBuilder); generator.Emit(OpCodes.Ret); Type type = typeBuilder.CreateType(); FieldInfo field = type.GetField("_field"); // Activator holds a cache of constructors and the types to which they belong. // Test caching behaviour by activating multiple times. object v1 = Activator.CreateInstance(type, nonPublic: true); Assert.Equal(-1, field.GetValue(v1)); object v2 = Activator.CreateInstance(type, nonPublic: true); Assert.Equal(-1, field.GetValue(v2)); } [Fact] public void CreateInstance_PublicOnlyValueTypeWithPrivateDefaultConstructor_ThrowsMissingMethodException() { AssemblyName assemblyName = new AssemblyName("Assembly"); AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type", TypeAttributes.Public, typeof(ValueType)); FieldBuilder fieldBuilder = typeBuilder.DefineField("_field", typeof(int), FieldAttributes.Public); ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Private | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.HideBySig, CallingConventions.Standard, new Type[0]); ILGenerator generator = constructorBuilder.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldc_I4, -1); generator.Emit(OpCodes.Stfld, fieldBuilder); generator.Emit(OpCodes.Ret); Type type = typeBuilder.CreateType(); Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(type)); Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(type, nonPublic: false)); // Put the private default constructor into the cache and make sure we still throw if public only. Assert.NotNull(Activator.CreateInstance(type, nonPublic: true)); Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(type)); Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(type, nonPublic: false)); } [Theory] [MemberData(nameof(TestingCreateInstanceFromObjectHandleData))] public static void TestingCreateInstanceFromObjectHandle(string physicalFileName, string assemblyFile, string type, string returnedFullNameType, Type exceptionType) { ObjectHandle oh = null; if (exceptionType != null) { Assert.Throws(exceptionType, () => Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type)); } else { oh = Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type); CheckValidity(oh, returnedFullNameType); } if (exceptionType != null) { Assert.Throws(exceptionType, () => Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type, null)); } else { oh = Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type, null); CheckValidity(oh, returnedFullNameType); } Assert.True(File.Exists(physicalFileName)); } public static TheoryData<string, string, string, string, Type> TestingCreateInstanceFromObjectHandleData => new TheoryData<string, string, string, string, Type>() { // string physicalFileName, string assemblyFile, string typeName, returnedFullNameType, expectedException { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PublicClassSample", "PublicClassSample", null }, { "TestLoadAssembly.dll", "testloadassembly.dll", "publicclasssample", "PublicClassSample", typeof(TypeLoadException) }, { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PrivateClassSample", "PrivateClassSample", null }, { "TestLoadAssembly.dll", "testloadassembly.dll", "privateclasssample", "PrivateClassSample", typeof(TypeLoadException) }, { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PublicClassNoDefaultConstructorSample", "PublicClassNoDefaultConstructorSample", typeof(MissingMethodException) }, { "TestLoadAssembly.dll", "testloadassembly.dll", "publicclassnodefaultconstructorsample", "PublicClassNoDefaultConstructorSample", typeof(TypeLoadException) } }; [Theory] [MemberData(nameof(TestingCreateInstanceObjectHandleData))] public static void TestingCreateInstanceObjectHandle(string assemblyName, string type, string returnedFullNameType, Type exceptionType, bool returnNull) { ObjectHandle oh = null; if (exceptionType != null) { Assert.Throws(exceptionType, () => Activator.CreateInstance(assemblyName: assemblyName, typeName: type)); } else { oh = Activator.CreateInstance(assemblyName: assemblyName, typeName: type); if (returnNull) { Assert.Null(oh); } else { CheckValidity(oh, returnedFullNameType); } } if (exceptionType != null) { Assert.Throws(exceptionType, () => Activator.CreateInstance(assemblyName: assemblyName, typeName: type, null)); } else { oh = Activator.CreateInstance(assemblyName: assemblyName, typeName: type, null); if (returnNull) { Assert.Null(oh); } else { CheckValidity(oh, returnedFullNameType); } } } public static TheoryData<string, string, string, Type, bool> TestingCreateInstanceObjectHandleData => new TheoryData<string, string, string, Type, bool>() { // string assemblyName, string typeName, returnedFullNameType, expectedException { "TestLoadAssembly", "PublicClassSample", "PublicClassSample", null, false }, { "testloadassembly", "publicclasssample", "PublicClassSample", typeof(TypeLoadException), false }, { "TestLoadAssembly", "PrivateClassSample", "PrivateClassSample", null, false }, { "testloadassembly", "privateclasssample", "PrivateClassSample", typeof(TypeLoadException), false }, { "TestLoadAssembly", "PublicClassNoDefaultConstructorSample", "PublicClassNoDefaultConstructorSample", typeof(MissingMethodException), false }, { "testloadassembly", "publicclassnodefaultconstructorsample", "PublicClassNoDefaultConstructorSample", typeof(TypeLoadException), false }, { "mscorlib", "System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", "", null, true } }; [Theory] [MemberData(nameof(TestingCreateInstanceFromObjectHandleFullSignatureData))] public static void TestingCreateInstanceFromObjectHandleFullSignature(string physicalFileName, string assemblyFile, string type, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, string returnedFullNameType) { ObjectHandle oh = Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type, ignoreCase: ignoreCase, bindingAttr: bindingAttr, binder: binder, args: args, culture: culture, activationAttributes: activationAttributes); CheckValidity(oh, returnedFullNameType); Assert.True(File.Exists(physicalFileName)); } public static IEnumerable<object[]> TestingCreateInstanceFromObjectHandleFullSignatureData() { // string physicalFileName, string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, returnedFullNameType yield return new object[] { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PublicClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "testloadassembly.dll", "publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PublicClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PublicClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "testloadassembly.dll", "publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PublicClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PrivateClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "testloadassembly.dll", "privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PrivateClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PrivateClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "testloadassembly.dll", "privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PrivateClassSample" }; } [Theory] [MemberData(nameof(TestingCreateInstanceObjectHandleFullSignatureData))] public static void TestingCreateInstanceObjectHandleFullSignature(string assemblyName, string type, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, string returnedFullNameType, bool returnNull) { ObjectHandle oh = Activator.CreateInstance(assemblyName: assemblyName, typeName: type, ignoreCase: ignoreCase, bindingAttr: bindingAttr, binder: binder, args: args, culture: culture, activationAttributes: activationAttributes); if (returnNull) { Assert.Null(oh); } else { CheckValidity(oh, returnedFullNameType); } } public static IEnumerable<object[]> TestingCreateInstanceObjectHandleFullSignatureData() { // string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, returnedFullNameType yield return new object[] { "TestLoadAssembly", "PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PublicClassSample" , false }; yield return new object[] { "testloadassembly", "publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PublicClassSample" , false }; yield return new object[] { "TestLoadAssembly", "PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PublicClassSample" , false }; yield return new object[] { "testloadassembly", "publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PublicClassSample" , false }; yield return new object[] { "TestLoadAssembly", "PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PrivateClassSample", false }; yield return new object[] { "testloadassembly", "privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PrivateClassSample", false }; yield return new object[] { "TestLoadAssembly", "PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PrivateClassSample", false }; yield return new object[] { "testloadassembly", "privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PrivateClassSample", false }; yield return new object[] { null, typeof(PublicType).FullName, false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, typeof(PublicType).FullName, false }; yield return new object[] { null, typeof(PrivateType).FullName, false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, typeof(PrivateType).FullName, false }; yield return new object[] { "mscorlib", "System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "", true }; } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWinRTSupported), nameof(PlatformDetection.IsNotWindows8x), nameof(PlatformDetection.IsNotWindowsServerCore), nameof(PlatformDetection.IsNotWindowsNanoServer), nameof(PlatformDetection.IsNotWindowsIoTCore))] [PlatformSpecific(TestPlatforms.Windows)] [MemberData(nameof(TestingCreateInstanceObjectHandleFullSignatureWinRTData))] public static void TestingCreateInstanceObjectHandleFullSignatureWinRT(string assemblyName, string type, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, string returnedFullNameType) { ObjectHandle oh = Activator.CreateInstance(assemblyName: assemblyName, typeName: type, ignoreCase: ignoreCase, bindingAttr: bindingAttr, binder: binder, args: args, culture: culture, activationAttributes: activationAttributes); CheckValidity(oh, returnedFullNameType); } public static IEnumerable<object[]> TestingCreateInstanceObjectHandleFullSignatureWinRTData() { // string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, returnedFullNameType yield return new object[] { "Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime", "Windows.Foundation.Collections.StringMap", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "Windows.Foundation.Collections.StringMap" }; } private static void CheckValidity(ObjectHandle instance, string expected) { Assert.NotNull(instance); Assert.Equal(expected, instance.Unwrap().GetType().FullName); } public class PublicType { public PublicType() { } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.LoadFile is not supported in AppX.")] public static void CreateInstanceAssemblyResolve() { RemoteInvoke(() => { AppDomain.CurrentDomain.AssemblyResolve += (object sender, ResolveEventArgs args) => Assembly.LoadFile(Path.Combine(Directory.GetCurrentDirectory(), "TestLoadAssembly.dll")); ObjectHandle oh = Activator.CreateInstance(",,,,", "PublicClassSample"); Assert.NotNull(oh.Unwrap()); }).Dispose(); } [Fact] public void CreateInstance_TypeBuilder_ThrowsNotSupportedException() { AssemblyName assemblyName = new AssemblyName("Assembly"); AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type", TypeAttributes.Public); Assert.Throws<ArgumentException>("type", () => Activator.CreateInstance(typeBuilder)); Assert.Throws<NotSupportedException>(() => Activator.CreateInstance(typeBuilder, new object[0])); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "AssemblyBuilderAccess.ReflectionOnly is not supported in .NET Core")] public void CreateInstance_ReflectionOnlyType_ThrowsInvalidOperationException() { AssemblyName assemblyName = new AssemblyName("Assembly"); AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, (AssemblyBuilderAccess)6); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type", TypeAttributes.Public); Assert.Throws<InvalidOperationException>(() => Activator.CreateInstance(typeBuilder.CreateType())); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "AssemblyBuilderAccess.Save is not supported in .NET Core")] public void CreateInstance_DynamicTypeWithoutRunAccess_ThrowsNotSupportedException() { AssemblyName assemblyName = new AssemblyName("Assembly"); AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, (AssemblyBuilderAccess)2); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type", TypeAttributes.Public); Assert.Throws<NotSupportedException>(() => Activator.CreateInstance(typeBuilder.CreateType())); } } }
using UnityEngine; using System.Collections.Generic; /* * TODO: * Replace LinkedList by an array or fields * OnHover for DisplayedBioBrick * OnPress for AvailableDisplayedBioBrick + Update of _currentDisplayedBricks in CraftZone * OnPress for CraftZoneDisplayedBioBrick + Update of _currentDisplayedBricks in CraftZone * Update of state of CraftFinalizationButton */ //TODO refactor CraftZoneManager and AvailableBioBricksManager? public class CraftZoneManager : MonoBehaviour { //////////////////////////////// singleton fields & methods //////////////////////////////// private const string gameObjectName = "CraftZoneManager"; private static CraftZoneManager _instance; public static CraftZoneManager get() { // Debug.Log("CraftZoneManager get"); if (_instance == null) { Debug.LogWarning("CraftZoneManager get was badly initialized"); _instance = GameObject.Find(gameObjectName).GetComponent<CraftZoneManager>(); } return _instance; } void Awake() { // Debug.Log(this.GetType() + " Awake"); if ((_instance != null) && (_instance != this)) { Debug.LogError(this.GetType() + " has two running instances"); } else { _instance = this; } } void OnDestroy() { // Debug.Log(this.GetType() + " OnDestroy " + (_instance == this)); _instance = (_instance == this) ? null : _instance; } void Start() { // Debug.Log(this.GetType() + " Start"); initializeIfNecessary(); } //////////////////////////////////////////////////////////////////////////////////////////// private const int _sandboxSlotCount = 10; private const int _tutorialSlotCount = 1; private List<CraftDeviceSlot> _slots = new List<CraftDeviceSlot>(); public int getSlotCount() { return _slots.Count; } private CraftDeviceSlot _selectedSlot; private int _slotCount; [SerializeField] private GameObject _slotPrefab; public const string _brickNameRoot = "brick"; public const string _slotNameRoot = "slot"; [HideInInspector] public Transform slotsGrid; private LinkedList<CraftZoneDisplayedBioBrick> _currentDisplayedBricks = new LinkedList<CraftZoneDisplayedBioBrick>(); private Device _currentDevice = null; [HideInInspector] public CraftFinalizer craftFinalizer; [HideInInspector] public GameObject assemblyZonePanel; private static EditMode _editMode = EditMode.UNLOCKED; private bool _initialized = false; private enum EditMode { LOCKED, UNLOCKED } public LinkedList<CraftZoneDisplayedBioBrick> getCurrentDisplayedBricks() { return new LinkedList<CraftZoneDisplayedBioBrick>(_currentDisplayedBricks); } public static bool isDeviceEditionOn() { return EditMode.UNLOCKED == _editMode; } public static void setDeviceEdition(bool editionOn) { _editMode = editionOn ? EditMode.UNLOCKED : EditMode.LOCKED; } private LinkedList<BioBrick> _currentBioBricks { get { if (null != _selectedSlot) { return _selectedSlot.getCurrentBricks(); } else { return new LinkedList<BioBrick>(); } } } public void initializeIfNecessary() { if (!_initialized) { if (null != slotsGrid) { _slots.Clear(); _slotCount = GameConfiguration.gameMap == GameConfiguration.GameMap.SANDBOX2 ? _sandboxSlotCount : _tutorialSlotCount; // Debug.Log("going to destroy children slots"); for (int index = 0; index < slotsGrid.childCount; index++) { Destroy(slotsGrid.GetChild(index).gameObject); } // Debug.Log("going to add children slots"); for (int index = 0; index < _slotCount; index++) { addSlot(); } // Debug.Log("done children slots"); selectSlot(_slots[0]); displayDevice(); _initialized = true; } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // BioBricks //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public void setBioBricks(LinkedList<BioBrick> bricks) { // Debug.Log(this.GetType() + " setBioBricks(" + Logger.ToString<BioBrick>(bricks) + ")"); removeAllBricksFromCraftZone(); foreach (BioBrick brick in bricks) { AvailableBioBricksManager.get().addBrickAmount(brick, -1); } _currentBioBricks.AppendRange(bricks); OnBioBricksChanged(); } public Equipment.AddingResult equip() { Equipment.AddingResult result = Equipment.get().askAddDevice(getCurrentDevice()); OnBioBricksChanged(); return result; } public void unequip() { Equipment.get().removeDevice(getCurrentDevice()); OnBioBricksChanged(); } public void unequip(Device device) { // Debug.Log("LBCZM unequip"); foreach (CraftDeviceSlot slot in _slots) { // TODO check why Device.Equals fails if (device.hasSameBricks(slot.getCurrentDevice())) { // Debug.Log("LBCZM unequip: match on slot " + slot.name); slot.removeAllBricks(); return; } } } public void OnBioBricksChanged() { foreach (CraftDeviceSlot slot in _slots) { slot.updateDisplay(); } } private static int getIndex(BioBrick brick) { int idx; switch (brick.getType()) { case BioBrick.Type.PROMOTER: idx = 0; break; case BioBrick.Type.RBS: idx = 1; break; case BioBrick.Type.GENE: idx = 2; break; case BioBrick.Type.TERMINATOR: idx = 3; break; default: idx = 0; Debug.LogWarning("CraftZoneManager getIndex unknown type " + brick.getType()); break; } return idx; } private void removePreviousDisplayedBricks() { // Debug.Log(this.GetType() + " removePreviousDisplayedBricks()"); //remove all previous biobricks foreach (CraftZoneDisplayedBioBrick brick in _currentDisplayedBricks) { Destroy(brick.gameObject); } _currentDisplayedBricks.Clear(); } public void removeBioBrick(CraftZoneDisplayedBioBrick brick) { // Debug.Log(this.GetType() + "removeBioBrick(czdb)"); if (null != brick) { // Debug.Log("removeBioBrick null != brick"); foreach (CraftDeviceSlot slot in _slots) { // Debug.Log("removeBioBrick slot "+slot); if (null != slot && slot.removeBrick(brick)) { return; } } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // slots public void addSlot() { // Debug.Log("adding slot #"+slotsGrid.childCount); GameObject slotGO = GameObject.Instantiate(_slotPrefab, Vector3.zero, Quaternion.identity, slotsGrid) as GameObject; slotGO.transform.localPosition = new Vector3(slotGO.transform.localPosition.x, slotGO.transform.localPosition.y, 0); slotGO.name = _slotNameRoot + _slots.Count; CraftDeviceSlot slot = slotGO.GetComponent<CraftDeviceSlot>(); _slots.Add(slot); slotsGrid.GetComponent<UIGrid>().repositionNow = true; } public void selectSlot(CraftDeviceSlot slot) { // Debug.Log(this.GetType() + " selectSlot"); if (null != slot) { if (null != _selectedSlot) { _selectedSlot.setSelectedBackground(false); } _selectedSlot = slot; // Debug.Log("selectSlot selectedSlot.setSelectedBackground(true); with selectedSlot="+selectedSlot); _selectedSlot.setSelectedBackground(true); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // utilities private BioBrick findFirstBioBrick(BioBrick.Type type) { foreach (BioBrick brick in _currentBioBricks) { if (brick.getType() == type) return brick; } // Debug.Log(this.GetType() + " findFirstBioBrick(" + type + ") failed with current bricks=" + Logger.ToString<BioBrick>(_currentBioBricks)); return null; } public void replaceWithBioBrick(BioBrick brick) { // Debug.Log("replaceWithBioBrick("+brick.getName()+")"); if (null != _selectedSlot) { // Debug.Log("null != selectedSlot"); _selectedSlot.addBrick(brick); } else { // Debug.Log("null == selectedSlot"); } } private void insertOrdered(BioBrick toInsert) { // Debug.Log("insertOrdered("+toInsert.getName()+")"); BioBrick sameBrick = LinkedListExtensions.Find(_currentBioBricks, b => b.getName() == toInsert.getName()); if (null != sameBrick) { // the brick is already present on the crafting table: remove it removeBioBrick(toInsert); } else { bool inserted = false; foreach (BioBrick brick in _currentBioBricks) { if (brick.getType() > toInsert.getType()) { // the brick is inserted before the next brick LinkedListNode<BioBrick> afterNode = _currentBioBricks.Find(brick); _currentBioBricks.AddBefore(afterNode, toInsert); inserted = true; break; } else if (brick.getType() == toInsert.getType()) { // the brick will replace a brick of the same type LinkedListNode<BioBrick> toReplaceNode = _currentBioBricks.Find(brick); _currentBioBricks.AddAfter(toReplaceNode, toInsert); _currentBioBricks.Remove(brick); //the brick is put out of the crafting table and is therefore available for new crafts AvailableBioBricksManager.get().addBrickAmount(brick, 1); inserted = true; break; } } if (!inserted) { // the brick is inserted in the last position _currentBioBricks.AddLast(toInsert); } // the brick was inserted: there's one less brick to use AvailableBioBricksManager.get().addBrickAmount(toInsert, -1); } } public void removeBioBrick(BioBrick brick) { // Debug.Log(this.GetType() + " removeBioBrick"); string debug = null != brick ? "contains=" + _currentBioBricks.Contains(brick) : "brick==null"; // Debug.Log(this.GetType() + " removeBioBrick with "+debug); if (null != brick && _currentBioBricks.Contains(brick)) { // Debug.Log(this.GetType() + " removeBioBrick(" + brick.getInternalName() + ")"); unequip(); _currentBioBricks.Remove(brick); AvailableBioBricksManager.get().addBrickAmount(brick, 1); OnBioBricksChanged(); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Device //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public void addAndEquipDevice(Device device, bool replace = true) { if (Device.isValid(device)) { //add every brick to the stock foreach (BioBrick brick in device.getExpressionModules().First.Value.getBioBricks()) { AvailableBioBricksManager.get().addAvailableBioBrick(brick, false); } //set device setDevice(device); } } public bool canAfford(Device device) { bool canAfford = true; AvailableBioBricksManager abbm = AvailableBioBricksManager.get(); foreach (ExpressionModule module in device.getExpressionModules()) { foreach (BioBrick brick in module.getBioBricks()) { canAfford &= ((abbm.getBrickAmount(brick) > 0) || _currentBioBricks.Contains(brick)); } } return canAfford; } public void setDevice(Device device, bool replace = true) { // Debug.Log(this.GetType() + " setDevice("+device+")"); if (!replace) { foreach (CraftDeviceSlot slot in _slots) { if (!slot.isEquipped) { slot.setSelected(true); break; } } } if (null != _selectedSlot) { _selectedSlot.setDevice(device); } } private void removeAllBricksFromCraftZone() { if (null != _selectedSlot) { _selectedSlot.removeAllBricks(); } } public void craft() { // Debug.Log(this.GetType() + " craft"); } private void consumeBricks() { // Debug.Log(this.GetType() + " consumeBricks()"); foreach (BioBrick brick in _currentBioBricks) { AvailableBioBricksManager.get().addBrickAmount(brick, -1); } } private void displayDevice() { // Debug.Log(this.GetType() + " displayDevice()"); if (null != craftFinalizer) { craftFinalizer.setDisplayedDevice(_currentDevice); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // utilities public Device getDeviceFromBricks(LinkedList<BioBrick> bricks) { // Debug.Log(this.GetType() + " getDeviceFromBricks(" + Logger.ToString<BioBrick>(bricks) + ")"); if (!ExpressionModule.isBioBricksSequenceValid(bricks)) { Debug.LogWarning(this.GetType() + " getDeviceFromBricks invalid biobricks sequence"); return null; } ExpressionModule module = new ExpressionModule("test", bricks); LinkedList<ExpressionModule> modules = new LinkedList<ExpressionModule>(); modules.AddLast(module); Device device = Device.buildDevice(modules); if (device != null) { // Debug.Log(this.GetType() + " getDeviceFromBricks produced " + device.getInternalName()); } else { Debug.LogWarning(this.GetType() + " getDeviceFromBricks device==null with bricks=" + Logger.ToString<BioBrick>(bricks)); } return device; } public Device getCurrentDevice() { // Debug.Log(this.GetType() + " getCurrentDevice"); return _selectedSlot.getCurrentDevice(); } public static bool isOpenable() { //FIXME doesn't work with test null != _instance._currentDevice return ( 0 != AvailableBioBricksManager.get().getAvailableBioBricks().Count && (!Character.isBeingInjured || PhenoAmpicillinProducer.get().isSpawningAmpicillin) ); } public static string getInternalDevicesString() { string result = ""; foreach(CraftDeviceSlot slot in _instance._slots) { string slotString = slot.getInternalBricksString(); if(!string.IsNullOrEmpty(slotString)) { if(!string.IsNullOrEmpty(result)) { result += ", "; } result += slotString; } } return result; } }
// 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.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; using Validation; namespace System.Collections.Immutable { /// <summary> /// Extension methods for immutable types. /// </summary> internal static class ImmutableExtensions { /// <summary> /// Tries to divine the number of elements in a sequence without actually enumerating each element. /// </summary> /// <typeparam name="T">The type of elements in the sequence.</typeparam> /// <param name="sequence">The enumerable source.</param> /// <param name="count">Receives the number of elements in the enumeration, if it could be determined.</param> /// <returns><c>true</c> if the count could be determined; <c>false</c> otherwise.</returns> internal static bool TryGetCount<T>(this IEnumerable<T> sequence, out int count) { return TryGetCount<T>((IEnumerable)sequence, out count); } /// <summary> /// Tries to divine the number of elements in a sequence without actually enumerating each element. /// </summary> /// <typeparam name="T">The type of elements in the sequence.</typeparam> /// <param name="sequence">The enumerable source.</param> /// <param name="count">Receives the number of elements in the enumeration, if it could be determined.</param> /// <returns><c>true</c> if the count could be determined; <c>false</c> otherwise.</returns> internal static bool TryGetCount<T>(this IEnumerable sequence, out int count) { var collection = sequence as ICollection; if (collection != null) { count = collection.Count; return true; } var collectionOfT = sequence as ICollection<T>; if (collectionOfT != null) { count = collectionOfT.Count; return true; } var readOnlyCollection = sequence as IReadOnlyCollection<T>; if (readOnlyCollection != null) { count = readOnlyCollection.Count; return true; } count = 0; return false; } /// <summary> /// Gets the number of elements in the specified sequence, /// while guaranteeing that the sequence is only enumerated once /// in total by this method and the caller. /// </summary> /// <typeparam name="T">The type of element in the collection.</typeparam> /// <param name="sequence">The sequence.</param> /// <returns>The number of elements in the sequence.</returns> internal static int GetCount<T>(ref IEnumerable<T> sequence) { int count; if (!sequence.TryGetCount(out count)) { // We cannot predict the length of the sequence. We must walk the entire sequence // to find the count. But avoid our caller also having to enumerate by capturing // the enumeration in a snapshot and passing that back to the caller. var list = sequence.ToList(); count = list.Count; sequence = list; } return count; } /// <summary> /// Gets a copy of a sequence as an array. /// </summary> /// <typeparam name="T">The type of element.</typeparam> /// <param name="sequence">The sequence to be copied.</param> /// <param name="count">The number of elements in the sequence.</param> /// <returns>The array.</returns> /// <remarks> /// This is more efficient than the Enumerable.ToArray{T} extension method /// because that only tries to cast the sequence to ICollection{T} to determine /// the count before it falls back to reallocating arrays as it enumerates. /// </remarks> internal static T[] ToArray<T>(this IEnumerable<T> sequence, int count) { Requires.NotNull(sequence, "sequence"); Requires.Range(count >= 0, "count"); T[] array = new T[count]; int i = 0; foreach (var item in sequence) { Requires.Argument(i < count); array[i++] = item; } Requires.Argument(i == count); return array; } #if EqualsStructurally /// <summary> /// An optimized version of <see cref="Enumerable.SequenceEqual{T}(IEnumerable{T}, IEnumerable{T}, IEqualityComparer{T})"/> /// that allows nulls, considers reference equality and count before beginning the enumeration. /// </summary> /// <typeparam name="T">The type of elements in the sequence.</typeparam> /// <param name="sequence1">The first sequence.</param> /// <param name="sequence2">The second sequence.</param> /// <param name="equalityComparer">The equality comparer to use for the elements.</param> /// <returns><c>true</c> if the sequences are equal (same elements in the same order); <c>false</c> otherwise.</returns> internal static bool CollectionEquals<T>(this IEnumerable<T> sequence1, IEnumerable<T> sequence2, IEqualityComparer<T> equalityComparer = null) { if (sequence1 == sequence2) { return true; } if ((sequence1 == null) ^ (sequence2 == null)) { return false; } int count1, count2; if (sequence1.TryGetCount(out count1) && sequence2.TryGetCount(out count2)) { if (count1 != count2) { return false; } if (count1 == 0 && count2 == 0) { return true; } } return sequence1.SequenceEqual(sequence2, equalityComparer); } /// <summary> /// An optimized version of <see cref="Enumerable.SequenceEqual{T}(IEnumerable{T}, IEnumerable{T}, IEqualityComparer{T})"/> /// that allows nulls, considers reference equality and count before beginning the enumeration. /// </summary> /// <typeparam name="T">The type of elements in the sequence.</typeparam> /// <param name="sequence1">The first sequence.</param> /// <param name="sequence2">The second sequence.</param> /// <param name="equalityComparer">The equality comparer to use for the elements.</param> /// <returns><c>true</c> if the sequences are equal (same elements in the same order); <c>false</c> otherwise.</returns> internal static bool CollectionEquals<T>(this IEnumerable<T> sequence1, IEnumerable sequence2, IEqualityComparer equalityComparer = null) { if (sequence1 == sequence2) { return true; } if ((sequence1 == null) ^ (sequence2 == null)) { return false; } int count1, count2; if (sequence1.TryGetCount(out count1) && sequence2.TryGetCount<T>(out count2)) { if (count1 != count2) { return false; } if (count1 == 0 && count2 == 0) { return true; } } if (equalityComparer == null) { equalityComparer = EqualityComparer<T>.Default; } // If we have generic types we can use, use them to avoid boxing. var sequence2OfT = sequence2 as IEnumerable<T>; var equalityComparerOfT = equalityComparer as IEqualityComparer<T>; if (sequence2OfT != null && equalityComparerOfT != null) { return sequence1.SequenceEqual(sequence2OfT, equalityComparerOfT); } else { // We have to fallback to doing it manually since the underlying collection // being compared isn't a (matching) generic type. using (var enumerator = sequence1.GetEnumerator()) { var enumerator2 = sequence2.GetEnumerator(); try { while (enumerator.MoveNext()) { if (!enumerator2.MoveNext() || !equalityComparer.Equals(enumerator.Current, enumerator2.Current)) { return false; } } if (enumerator2.MoveNext()) { return false; } return true; } finally { var enum2Disposable = enumerator2 as IDisposable; if (enum2Disposable != null) { enum2Disposable.Dispose(); } } } } } #endif /// <summary> /// Provides a known wrapper around a sequence of elements that provides the number of elements /// and an indexer into its contents. /// </summary> /// <typeparam name="T">The type of elements in the collection.</typeparam> /// <param name="sequence">The collection.</param> /// <returns>An ordered collection. May not be thread-safe. Never null.</returns> internal static IOrderedCollection<T> AsOrderedCollection<T>(this IEnumerable<T> sequence) { Requires.NotNull(sequence, "sequence"); Contract.Ensures(Contract.Result<IOrderedCollection<T>>() != null); var orderedCollection = sequence as IOrderedCollection<T>; if (orderedCollection != null) { return orderedCollection; } var listOfT = sequence as IList<T>; if (listOfT != null) { return new ListOfTWrapper<T>(listOfT); } // It would be great if SortedSet<T> and SortedDictionary<T> provided indexers into their collections, // but since they don't we have to clone them to an array. return new FallbackWrapper<T>(sequence); } /// <summary> /// Clears the specified stack. For empty stacks, it avoids the call to Clear, which /// avoids a call into the runtime's implementation of Array.Clear, helping performance, /// in particular around inlining. Stack.Count typically gets inlined by today's JIT, while /// stack.Clear and Array.Clear typically don't. /// </summary> /// <typeparam name="T">Specifies the type of data in the stack to be cleared.</typeparam> /// <param name="stack">The stack to clear.</param> internal static void ClearFastWhenEmpty<T>(this Stack<T> stack) { if (stack.Count > 0) { stack.Clear(); } } /// <summary> /// Gets a non-disposable enumerable that can be used as the source for a C# foreach loop /// that will not box the enumerator if it is of a particular type. /// </summary> /// <typeparam name="T">The type of value to be enumerated.</typeparam> /// <typeparam name="TEnumerator"> /// The type of the Enumerator struct. This must NOT implement <see cref="IDisposable"/> (or <see cref="IEnumerator{T}"/>). /// If it does, call <see cref="GetEnumerableDisposable{T, TEnumerator}"/> instead. /// </typeparam> /// <param name="enumerable">The collection to be enumerated.</param> /// <returns>A struct that enumerates the collection.</returns> internal static EnumeratorAdapter<T, TEnumerator> GetEnumerable<T, TEnumerator>(this IEnumerable<T> enumerable) where TEnumerator : struct, IStrongEnumerator<T> { Requires.NotNull(enumerable, "enumerable"); // This debug-only check is sufficient to cause test failures to flag errors so they never get checked in. Debug.Assert(!typeof(IDisposable).GetTypeInfo().IsAssignableFrom(typeof(TEnumerator).GetTypeInfo()), "The enumerator struct implements IDisposable. Call GetEnumerableDisposable instead."); var strongEnumerable = enumerable as IStrongEnumerable<T, TEnumerator>; if (strongEnumerable != null) { return new EnumeratorAdapter<T, TEnumerator>(strongEnumerable.GetEnumerator()); } else { // Consider for future: we could add more special cases for common // mutable collection types like List<T>+Enumerator and such. return new EnumeratorAdapter<T, TEnumerator>(enumerable.GetEnumerator()); } } /// <summary> /// Gets a disposable enumerable that can be used as the source for a C# foreach loop /// that will not box the enumerator if it is of a particular type. /// </summary> /// <typeparam name="T">The type of value to be enumerated.</typeparam> /// <typeparam name="TEnumerator">The type of the Enumerator struct.</typeparam> /// <param name="enumerable">The collection to be enumerated.</param> /// <returns>A struct that enumerates the collection.</returns> internal static DisposableEnumeratorAdapter<T, TEnumerator> GetEnumerableDisposable<T, TEnumerator>(this IEnumerable<T> enumerable) where TEnumerator : struct, IStrongEnumerator<T>, IEnumerator<T> { Requires.NotNull(enumerable, "enumerable"); var strongEnumerable = enumerable as IStrongEnumerable<T, TEnumerator>; if (strongEnumerable != null) { return new DisposableEnumeratorAdapter<T, TEnumerator>(strongEnumerable.GetEnumerator()); } else { // Consider for future: we could add more special cases for common // mutable collection types like List<T>+Enumerator and such. return new DisposableEnumeratorAdapter<T, TEnumerator>(enumerable.GetEnumerator()); } } /// <summary> /// Wraps a List{T} as an ordered collection. /// </summary> /// <typeparam name="T">The type of element in the collection.</typeparam> private class ListOfTWrapper<T> : IOrderedCollection<T> { /// <summary> /// The list being exposed. /// </summary> private readonly IList<T> _collection; /// <summary> /// Initializes a new instance of the <see cref="ListOfTWrapper&lt;T&gt;"/> class. /// </summary> /// <param name="collection">The collection.</param> internal ListOfTWrapper(IList<T> collection) { Requires.NotNull(collection, "collection"); _collection = collection; } /// <summary> /// Gets the count. /// </summary> public int Count { get { return _collection.Count; } } /// <summary> /// Gets the <typeparamref name="T"/> at the specified index. /// </summary> public T this[int index] { get { return _collection[index]; } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<T> GetEnumerator() { return _collection.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } /// <summary> /// Wraps any IEnumerable as an ordered, indexable list. /// </summary> /// <typeparam name="T">The type of element in the collection.</typeparam> private class FallbackWrapper<T> : IOrderedCollection<T> { /// <summary> /// The original sequence. /// </summary> private readonly IEnumerable<T> _sequence; /// <summary> /// The list-ified sequence. /// </summary> private IList<T> _collection; /// <summary> /// Initializes a new instance of the <see cref="FallbackWrapper&lt;T&gt;"/> class. /// </summary> /// <param name="sequence">The sequence.</param> internal FallbackWrapper(IEnumerable<T> sequence) { Requires.NotNull(sequence, "sequence"); _sequence = sequence; } /// <summary> /// Gets the count. /// </summary> public int Count { get { if (_collection == null) { int count; if (_sequence.TryGetCount(out count)) { return count; } _collection = _sequence.ToArray(); } return _collection.Count; } } /// <summary> /// Gets the <typeparamref name="T"/> at the specified index. /// </summary> public T this[int index] { get { if (_collection == null) { _collection = _sequence.ToArray(); } return _collection[index]; } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<T> GetEnumerator() { return _sequence.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> [ExcludeFromCodeCoverage] IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using MsgPack.Rpc.Server.Dispatch.Reflection; namespace MsgPack.Rpc.Server.Dispatch { /// <summary> /// Generates <see cref="AsyncServiceInvoker{T}"/> implementation. /// </summary> internal sealed class ServiceInvokerGenerator : IDisposable { private static readonly ConstructorInfo _debuggableAttributeCtor = typeof( DebuggableAttribute ).GetConstructor( new[] { typeof( bool ), typeof( bool ) } ); private static readonly object[] _debuggableAttributeCtorArguments = new object[] { true, true }; private static readonly MethodInfo _func_1_Invoke = FromExpression.ToMethod( ( Func<object> @this ) => @this.Invoke() ); private static readonly MethodInfo _unpackerReadSubtreeMethod = FromExpression.ToMethod( ( Unpacker unpacker ) => unpacker.ReadSubtree() ); private static readonly MethodInfo _unpackerReadMethod = FromExpression.ToMethod( ( Unpacker unpacker ) => unpacker.Read() ); private static readonly PropertyInfo _cultureInfoCurrentCultureProperty = FromExpression.ToProperty( () => CultureInfo.CurrentCulture ); private static readonly MethodInfo _stringFormatMethod = FromExpression.ToMethod( ( IFormatProvider formatProvider, String format, object[] args ) => String.Format( formatProvider, format, args ) ); private static readonly ConstructorInfo _serializationExceptionCtorStringConstructor = FromExpression.ToConstructor( ( string message ) => new SerializationException( message ) ); private static readonly MethodInfo _idisposableDisposeMethod = FromExpression.ToMethod( ( IDisposable disposable ) => disposable.Dispose() ); private static readonly MethodInfo _dispatcherBeginOperationMethod = FromExpression.ToMethod( ( AsyncServiceInvoker @base ) => @base.BeginOperation() ); private static readonly MethodInfo _dispatcherHandleThreadAbortExceptionMethod = FromExpression.ToMethod( ( AsyncServiceInvoker @base, ThreadAbortException exception ) => @base.HandleThreadAbortException( exception ) ); private static readonly MethodInfo _dispatcherEndOperationMethod = FromExpression.ToMethod( ( AsyncServiceInvoker @base ) => @base.EndOperation() ); private static readonly ConstructorInfo _asyncInvocationResultErrorConstructor = FromExpression.ToConstructor( ( RpcErrorMessage invocationError ) => new AsyncInvocationResult( invocationError ) ); private static readonly ConstructorInfo _asyncInvocationResultTaskConstructor = FromExpression.ToConstructor( ( Task asyncTask ) => new AsyncInvocationResult( asyncTask ) ); private static ServiceInvokerGenerator _default = new ServiceInvokerGenerator( false ); /// <summary> /// Gets the default instance. /// </summary> /// <value> /// The default instance. /// This value will not be <c>null</c>. /// </value> public static ServiceInvokerGenerator Default { get { Contract.Ensures( Contract.Result<ServiceInvokerGenerator>() != null ); return _default; } internal set // For test { if ( value != null ) { _default = value; } } } internal void Dump() { this._assemblyBuilder.Save( this._assemblyName.Name + ".dll" ); } private static long _assemblySequence; private long _typeSequence; private readonly AssemblyName _assemblyName; // For debugging purposes. internal AssemblyName AssemblyName { get { return this._assemblyName; } } private readonly AssemblyBuilder _assemblyBuilder; private readonly ModuleBuilder _moduleBuilder; private readonly ReaderWriterLockSlim _lock; private readonly IDictionary<RuntimeMethodHandle, IAsyncServiceInvoker> _cache; private readonly bool _isDebuggable; internal ServiceInvokerGenerator( bool isDebuggable ) { this._isDebuggable = isDebuggable; this._assemblyName = new AssemblyName( "SeamGeneratorHolder" + Interlocked.Increment( ref _assemblySequence ) ); this._assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly( this._assemblyName, isDebuggable ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Run ); if ( isDebuggable ) { this._assemblyBuilder.SetCustomAttribute( new CustomAttributeBuilder( _debuggableAttributeCtor, _debuggableAttributeCtorArguments ) ); } else { this._assemblyBuilder.SetCustomAttribute( new CustomAttributeBuilder( typeof( DebuggableAttribute ).GetConstructor( new[] { typeof( DebuggableAttribute.DebuggingModes ) } ), new object[] { DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints } ) ); } this._assemblyBuilder.SetCustomAttribute( new CustomAttributeBuilder( typeof( System.Runtime.CompilerServices.CompilationRelaxationsAttribute ).GetConstructor( new[] { typeof( int ) } ), new object[] { 8 } ) ); #if !SILVERLIGHT this._assemblyBuilder.SetCustomAttribute( new CustomAttributeBuilder( typeof( System.Security.SecurityRulesAttribute ).GetConstructor( new[] { typeof( System.Security.SecurityRuleSet ) } ), new object[] { System.Security.SecurityRuleSet.Level2 }, new[] { typeof( System.Security.SecurityRulesAttribute ).GetProperty( "SkipVerificationInFullTrust" ) }, new object[] { true } ) ); #endif if ( isDebuggable ) { this._moduleBuilder = this._assemblyBuilder.DefineDynamicModule( this._assemblyName.Name, this._assemblyName.Name + ".dll", true ); } else { this._moduleBuilder = this._assemblyBuilder.DefineDynamicModule( this._assemblyName.Name, true ); } this._cache = new Dictionary<RuntimeMethodHandle, IAsyncServiceInvoker>(); this._lock = new ReaderWriterLockSlim( LockRecursionPolicy.NoRecursion ); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { if ( this._lock != null ) { this._lock.Dispose(); } } /// <summary> /// Gets service invoker. /// If the concrete type is already created, returns the cached instance. /// Else creates new concrete type and its instance, then returns it. /// </summary> /// <param name="runtime"> /// The <see cref="RpcServerRuntime"/>. /// </param> /// <param name="serviceDescription"> /// <see cref="ServiceDescription"/> which holds the service spec. /// </param> /// <param name="targetOperation"> /// <see cref="MethodInfo"/> of the target operation. /// </param> /// <returns> /// <see cref="AsyncServiceInvoker{T}"/> where T is return type of the target method. /// </returns> public IAsyncServiceInvoker GetServiceInvoker( RpcServerRuntime runtime, ServiceDescription serviceDescription, MethodInfo targetOperation ) { Contract.Requires( runtime != null ); Contract.Requires( serviceDescription != null ); Contract.Requires( targetOperation != null ); bool isReadLockHeld = false; try { try { } finally { this._lock.EnterUpgradeableReadLock(); isReadLockHeld = true; } IAsyncServiceInvoker result; if ( this._cache.TryGetValue( targetOperation.MethodHandle, out result ) ) { return result; } IAsyncServiceInvoker newInvoker = CreateInvoker( runtime, serviceDescription, targetOperation ); bool isWriteLockHeld = false; try { try { } finally { this._lock.EnterWriteLock(); isWriteLockHeld = true; } if ( !this._cache.TryGetValue( targetOperation.MethodHandle, out result ) ) { this._cache[ targetOperation.MethodHandle ] = newInvoker; result = newInvoker; } return result; } finally { if ( isWriteLockHeld ) { this._lock.ExitWriteLock(); } } } finally { if ( isReadLockHeld ) { this._lock.ExitUpgradeableReadLock(); } } } private IAsyncServiceInvoker CreateInvoker( RpcServerRuntime runtime, ServiceDescription serviceDescription, MethodInfo targetOperation ) { var parameters = targetOperation.GetParameters(); CheckParameters( parameters ); bool isWrapperNeeded = !typeof( Task ).IsAssignableFrom( targetOperation.ReturnType ); var emitter = new ServiceInvokerEmitter( this._moduleBuilder, Interlocked.Increment( ref this._typeSequence ), targetOperation.DeclaringType, targetOperation.ReturnType, this._isDebuggable ); EmitInvokeCore( emitter, targetOperation, parameters, typeof( Task ), isWrapperNeeded ); return emitter.CreateInstance( runtime, serviceDescription, targetOperation ); } private static void EmitInvokeCore( ServiceInvokerEmitter emitter, MethodInfo targetOperation, ParameterInfo[] parameters, Type returnType, bool isWrapperNeeded ) { var methodReturnType = targetOperation.ReturnType == typeof( void ) ? typeof( Missing ) : targetOperation.ReturnType; var asyncInvokerIsDebugModeProperty = typeof( AsyncServiceInvoker<> ).MakeGenericType( methodReturnType ).GetProperty( "IsDebugMode", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ); var il = emitter.GetInvokeCoreMethodILGenerator(); try { var endOfMethod = il.DefineLabel(); var unpackedArguments = parameters.Select( item => il.DeclareLocal( item.ParameterType, item.Name ) ).ToArray(); var serializers = unpackedArguments.Select( item => emitter.RegisterSerializer( item.LocalType ) ).ToArray(); var result = il.DeclareLocal( typeof( AsyncInvocationResult ), "result" ); /* * using( var argumentsItemUnpacker = arguments.ReadSubTree() ) * { * argumentsItemUnpacker. * ... * } */ var argumentsItemUnpacker = il.DeclareLocal( typeof( Unpacker ), "argumentsItemUnpacker" ); il.EmitAnyLdarg( 1 ); il.EmitAnyCall( _unpackerReadSubtreeMethod ); il.EmitAnyStloc( argumentsItemUnpacker ); il.BeginExceptionBlock(); for ( int i = 0; i < parameters.Length; i++ ) { /* * if ( !argumentsItemUnpacker.Read() ) * { * throw new SerializationException( String.Format( CultureInfo.CurrentCuture, "Stream unexpectedly ends at argument {0}.", N ) ); * } * * T argN; * try * { * argN = this._serializerN.UnpackFrom( argumentsItemUnpacker ); * } * catch( Exception ex ) * { * return new AsyncInvocatonResult( InvocationHelper.HandleArgumentDeserializationException( ex, "argN" ) ); * return; * } */ il.EmitAnyLdloc( argumentsItemUnpacker ); il.EmitAnyCall( _unpackerReadMethod ); var endIf = il.DefineLabel(); il.EmitBrtrue_S( endIf ); var args = il.DeclareLocal( typeof( object[] ), "args" ); il.EmitNewarr( typeof( object ), 1 ); il.EmitAnyStloc( args ); il.EmitGetProperty( _cultureInfoCurrentCultureProperty ); il.EmitLdstr( "Stream unexpectedly ends at arguments array {0}." ); il.EmitAnyLdloc( args ); il.EmitAnyLdc_I4( 0 ); il.EmitAnyLdc_I4( i ); il.EmitBox( typeof( int ) ); il.EmitStelem( typeof( object ) ); il.EmitAnyLdloc( args ); il.EmitAnyCall( _stringFormatMethod ); il.EmitNewobj( _serializationExceptionCtorStringConstructor ); il.EmitThrow(); il.MarkLabel( endIf ); il.BeginExceptionBlock(); il.EmitAnyLdarg( 0 ); il.EmitLdfld( serializers[ i ] ); il.EmitAnyLdloc( argumentsItemUnpacker ); il.EmitAnyCall( serializers[ i ].FieldType.GetMethod( "UnpackFrom", BindingFlags.Public | BindingFlags.Instance ) ); il.EmitAnyStloc( unpackedArguments[ i ] ); EmitExceptionHandling( il, returnType, endOfMethod, ( il0, exception ) => { il0.EmitAnyLdloc( exception ); il0.EmitLdstr( parameters[ i ].Name ); il0.EmitAnyLdarg( 0 ); il0.EmitGetProperty( asyncInvokerIsDebugModeProperty ); il0.EmitCall( InvocationHelper.HandleArgumentDeserializationExceptionMethod ); il0.EmitNewobj( _asyncInvocationResultErrorConstructor ); il0.EmitAnyStloc( result ); } ); } il.BeginFinallyBlock(); il.EmitAnyLdloc( argumentsItemUnpacker ); il.EmitAnyCall( _idisposableDisposeMethod ); il.EndExceptionBlock(); /* * TService service = this._serviceDescription.Initializer() */ var service = il.DeclareLocal( targetOperation.DeclaringType, "service" ); il.EmitAnyLdarg( 0 ); il.EmitGetProperty( typeof( AsyncServiceInvoker<> ).MakeGenericType( methodReturnType ).GetProperty( "ServiceDescription" ) ); il.EmitGetProperty( ServiceDescription.InitializerProperty ); il.EmitAnyCall( _func_1_Invoke ); il.EmitCastclass( service.LocalType ); il.EmitAnyStloc( service ); /* * #if IS_TASK * return new AsyncInvocationResult( service.Target( arg1, ..., argN ) ); * #else * return new AsyncInvocationResult( this.PrivateInvokeCore( state as Tuple<...> ), new Tuple<...>(...) ) ); * #endif */ if ( !isWrapperNeeded ) { il.EmitAnyLdloc( service ); foreach ( var arg in unpackedArguments ) { il.EmitAnyLdloc( arg ); } il.EmitAnyCall( targetOperation ); } else { EmitWrapperInvocation( emitter, il, service, targetOperation, unpackedArguments ); } il.EmitNewobj( _asyncInvocationResultTaskConstructor ); il.EmitAnyStloc( result ); il.MarkLabel( endOfMethod ); il.EmitAnyLdloc( result ); il.EmitRet(); } finally { il.FlushTrace(); } } private static readonly Type[] _delegateConstructorParameterTypes = new[] { typeof( object ), typeof( IntPtr ) }; private static readonly PropertyInfo _taskFactoryProperty = FromExpression.ToProperty( () => Task.Factory ); private static readonly MethodInfo _taskFactoryStartNew_Action_1_Object_Object = FromExpression.ToMethod( ( TaskFactory @this, Action<Object> action, object state ) => @this.StartNew( action, state ) ); private static readonly MethodInfo _taskFactoryStartNew_Func_1_Object_T_Object = typeof( TaskFactory ).GetMethods( BindingFlags.Public | BindingFlags.Instance ).Single( m => m.Name == "StartNew" && m.IsGenericMethod && m.GetParameters().Length == 2 && m.GetParameters()[ 0 ].ParameterType.IsGenericType && m.GetParameters()[ 0 ].ParameterType.GetGenericTypeDefinition() == typeof( Func<,> ) && m.GetParameters()[ 1 ].ParameterType == typeof( object ) ); private static void EmitWrapperInvocation( ServiceInvokerEmitter emitter, TracingILGenerator il, LocalBuilder service, MethodInfo targetOperation, LocalBuilder[] unpackedArguments ) { /* * returnValue = Task.Factory.StartNew( this.PrivateInvokeCore( state as Tuple<...> ), new Tuple<...>(...) ); */ var itemTypes = Enumerable.Repeat( service, 1 ).Concat( unpackedArguments ).Select( item => item.LocalType ).ToArray(); var tupleTypes = TupleItems.CreateTupleTypeList( itemTypes ); EmitPrivateInvoke( emitter.GetPrivateInvokeMethodILGenerator( targetOperation.ReturnType ), targetOperation, tupleTypes, itemTypes ); il.EmitGetProperty( _taskFactoryProperty ); // new DELEGATE( PrivateInvoke ) ->new DELGATE( null, funcof( PrivateInvoke ) ) il.EmitLdarg_0(); il.EmitLdftn( emitter.PrivateInvokeMethod ); il.EmitNewobj( targetOperation.ReturnType == typeof( void ) ? typeof( Action<object> ).GetConstructor( _delegateConstructorParameterTypes ) : typeof( Func<,> ).MakeGenericType( typeof( object ), targetOperation.ReturnType ).GetConstructor( _delegateConstructorParameterTypes ) ); il.EmitAnyLdloc( service ); foreach ( var item in unpackedArguments ) { il.EmitAnyLdloc( item ); } foreach ( var tupleType in tupleTypes ) { il.EmitNewobj( tupleType.GetConstructors().Single() ); } if ( targetOperation.ReturnType == typeof( void ) ) { il.EmitAnyCall( _taskFactoryStartNew_Action_1_Object_Object ); } else { il.EmitAnyCall( _taskFactoryStartNew_Func_1_Object_T_Object.MakeGenericMethod( targetOperation.ReturnType ) ); } } /// <summary> /// Emits helper function to avoid lexical closure emitting. /// </summary> /// <param name="il"><see cref="TracingILGenerator"/>.</param> /// <param name="targetOperation"><see cref="MethodInfo"/> of the method to be invoked.</param> /// <param name="tupleTypes">The array of <see cref="Type"/> of nested tuples. The outermost is the first, innermost is the last.</param> /// <param name="itemTypes">The array of <see cref="Type"/> of flatten tuple items.</param> private static void EmitPrivateInvoke( TracingILGenerator il, MethodInfo targetOperation, IList<Type> tupleTypes, Type[] itemTypes ) { /* * private void/T PrivateInvoke( object state ) * { * T result; * Dispatcher.BeginOperation(); * try * { * var tuple = state as Tuple<...>; * result = * tuple.Item1.Target( * tuple.Item2, * : * tuple.Rest.Rest....ItemN * ); * } * catch( TheradAbortException ) * { * Dispatcher.HandleThreadAbortException( ex ); * } * finally * { * Dispatcher.EndOperation(); * } * * return result; * } */ var tuple = il.DeclareLocal( tupleTypes.First(), "tuple" ); var result = targetOperation.ReturnType == typeof( void ) ? null : il.DeclareLocal( targetOperation.ReturnType, "result" ); il.EmitAnyLdarg( 0 ); il.EmitCall( _dispatcherBeginOperationMethod ); il.BeginExceptionBlock(); il.EmitAnyLdarg( 1 ); il.EmitIsinst( tupleTypes.First() ); il.EmitAnyStloc( tuple ); int depth = -1; for ( int i = 0; i < itemTypes.Length; i++ ) { if ( i % 7 == 0 ) { depth++; } il.EmitAnyLdloc( tuple ); for ( int j = 0; j < depth; j++ ) { // .TRest.TRest ... var rest = tupleTypes[ j ].GetProperty( "Rest" ); il.EmitGetProperty( rest ); } var itemn = tupleTypes[ depth ].GetProperty( "Item" + ( ( i % 7 ) + 1 ) ); il.EmitGetProperty( itemn ); } il.EmitAnyCall( targetOperation ); if ( targetOperation.ReturnType != typeof( void ) ) { il.EmitAnyStloc( result ); } il.BeginCatchBlock( typeof( ThreadAbortException ) ); var ex = il.DeclareLocal(typeof(ThreadAbortException), "ex"); il.EmitAnyStloc( ex ); il.EmitAnyLdarg( 0 ); il.EmitAnyLdloc( ex ); il.EmitCall( _dispatcherHandleThreadAbortExceptionMethod ); il.BeginFinallyBlock(); il.EmitAnyLdarg( 0 ); il.EmitCall( _dispatcherEndOperationMethod ); il.EndExceptionBlock(); if ( targetOperation.ReturnType != typeof( void ) ) { il.EmitAnyLdloc( result ); } il.EmitRet(); } private static void CheckParameters( IList<ParameterInfo> parameters ) { foreach ( var item in parameters ) { if ( item.ParameterType == typeof( void ) || item.ParameterType == typeof( Missing ) ) { throw new NotSupportedException( String.Format( CultureInfo.CurrentCulture, "Parameter '{0}' at position {1} is invalid. Type '{2}' is not supported.", item.Name, item.Position, item.ParameterType.FullName ) ); } if ( item.ParameterType.IsByRef ) { throw new NotSupportedException( String.Format( CultureInfo.CurrentCulture, "Parameter '{0}' at position {1} is invalid. Managed pointer ('byref') is not supported.", item.Name, item.Position ) ); } if ( item.ParameterType.IsPointer ) { throw new NotSupportedException( String.Format( CultureInfo.CurrentCulture, "Parameter '{0}' at position {1} is invalid. Unmanaged pointer is not supported.", item.Name, item.Position ) ); } if ( item.ParameterType.IsArray && ( item.ParameterType.GetArrayRank() > 1 ) ) { throw new NotSupportedException( String.Format( CultureInfo.CurrentCulture, "Parameter '{0}' at position {1} is invalid. Non vector array is not supported.", item.Name, item.Position ) ); } } } private static void EmitExceptionHandling( TracingILGenerator il, Type returnType, Label endOfMethod, Action<TracingILGenerator, LocalBuilder> exceptionHandlerInvocation ) { il.BeginCatchBlock( typeof( Exception ) ); var exception = il.DeclareLocal( typeof( Exception ), "exception" ); il.EmitAnyStloc( exception ); exceptionHandlerInvocation( il, exception ); il.EmitLeave( endOfMethod ); il.EndExceptionBlock(); } } }
// <copyright file="PageFactory.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> #if !NETSTANDARD2_0 using System; using System.Collections.Generic; using System.Reflection; namespace OpenQA.Selenium.Support.PageObjects { /// <summary> /// Provides the ability to produce Page Objects modeling a page. This class cannot be inherited. /// </summary> [Obsolete("The PageFactory implementation in the .NET bindings is deprecated and will be removed in a future release. This portion of the code has been migrated to the DotNetSeleniumExtras repository on GitHub (https://github.com/DotNetSeleniumTools/DotNetSeleniumExtras)")] public sealed class PageFactory { /// <summary> /// Initializes a new instance of the <see cref="PageFactory"/> class. /// Private constructor prevents a default instance from being created. /// </summary> private PageFactory() { } /// <summary> /// Initializes the elements in the Page Object with the given type. /// </summary> /// <typeparam name="T">The <see cref="Type"/> of the Page Object class.</typeparam> /// <param name="driver">The <see cref="IWebDriver"/> instance used to populate the page.</param> /// <returns>An instance of the Page Object class with the elements initialized.</returns> /// <remarks> /// The class used in the <typeparamref name="T"/> argument must have a public constructor /// that takes a single argument of type <see cref="IWebDriver"/>. This helps to enforce /// best practices of the Page Object pattern, and encapsulates the driver into the Page /// Object so that it can have no external WebDriver dependencies. /// </remarks> /// <exception cref="ArgumentException"> /// thrown if no constructor to the class can be found with a single IWebDriver argument /// <para>-or-</para> /// if a field or property decorated with the <see cref="FindsByAttribute"/> is not of type /// <see cref="IWebElement"/> or IList{IWebElement}. /// </exception> public static T InitElements<T>(IWebDriver driver) { return InitElements<T>(new DefaultElementLocator(driver)); } /// <summary> /// Initializes the elements in the Page Object with the given type. /// </summary> /// <typeparam name="T">The <see cref="Type"/> of the Page Object class.</typeparam> /// <param name="locator">The <see cref="IElementLocator"/> implementation that /// determines how elements are located.</param> /// <returns>An instance of the Page Object class with the elements initialized.</returns> /// <remarks> /// The class used in the <typeparamref name="T"/> argument must have a public constructor /// that takes a single argument of type <see cref="IWebDriver"/>. This helps to enforce /// best practices of the Page Object pattern, and encapsulates the driver into the Page /// Object so that it can have no external WebDriver dependencies. /// </remarks> /// <exception cref="ArgumentException"> /// thrown if no constructor to the class can be found with a single IWebDriver argument /// <para>-or-</para> /// if a field or property decorated with the <see cref="FindsByAttribute"/> is not of type /// <see cref="IWebElement"/> or IList{IWebElement}. /// </exception> public static T InitElements<T>(IElementLocator locator) { T page = default(T); Type pageClassType = typeof(T); ConstructorInfo ctor = pageClassType.GetConstructor(new Type[] { typeof(IWebDriver) }); if (ctor == null) { throw new ArgumentException("No constructor for the specified class containing a single argument of type IWebDriver can be found"); } if (locator == null) { throw new ArgumentNullException("locator", "locator cannot be null"); } IWebDriver driver = locator.SearchContext as IWebDriver; if (driver == null) { throw new ArgumentException("The search context of the element locator must implement IWebDriver", "locator"); } page = (T)ctor.Invoke(new object[] { locator.SearchContext as IWebDriver }); InitElements(page, locator); return page; } /// <summary> /// Initializes the elements in the Page Object. /// </summary> /// <param name="driver">The driver used to find elements on the page.</param> /// <param name="page">The Page Object to be populated with elements.</param> /// <exception cref="ArgumentException"> /// thrown if a field or property decorated with the <see cref="FindsByAttribute"/> is not of type /// <see cref="IWebElement"/> or IList{IWebElement}. /// </exception> public static void InitElements(ISearchContext driver, object page) { InitElements(page, new DefaultElementLocator(driver)); } /// <summary> /// Initializes the elements in the Page Object. /// </summary> /// <param name="driver">The driver used to find elements on the page.</param> /// <param name="page">The Page Object to be populated with elements.</param> /// <param name="decorator">The <see cref="IPageObjectMemberDecorator"/> implementation that /// determines how Page Object members representing elements are discovered and populated.</param> /// <exception cref="ArgumentException"> /// thrown if a field or property decorated with the <see cref="FindsByAttribute"/> is not of type /// <see cref="IWebElement"/> or IList{IWebElement}. /// </exception> public static void InitElements(ISearchContext driver, object page, IPageObjectMemberDecorator decorator) { InitElements(page, new DefaultElementLocator(driver), decorator); } /// <summary> /// Initializes the elements in the Page Object. /// </summary> /// <param name="page">The Page Object to be populated with elements.</param> /// <param name="locator">The <see cref="IElementLocator"/> implementation that /// determines how elements are located.</param> /// <exception cref="ArgumentException"> /// thrown if a field or property decorated with the <see cref="FindsByAttribute"/> is not of type /// <see cref="IWebElement"/> or IList{IWebElement}. /// </exception> public static void InitElements(object page, IElementLocator locator) { InitElements(page, locator, new DefaultPageObjectMemberDecorator()); } /// <summary> /// Initializes the elements in the Page Object. /// </summary> /// <param name="page">The Page Object to be populated with elements.</param> /// <param name="locator">The <see cref="IElementLocator"/> implementation that /// determines how elements are located.</param> /// <param name="decorator">The <see cref="IPageObjectMemberDecorator"/> implementation that /// determines how Page Object members representing elements are discovered and populated.</param> /// <exception cref="ArgumentException"> /// thrown if a field or property decorated with the <see cref="FindsByAttribute"/> is not of type /// <see cref="IWebElement"/> or IList{IWebElement}. /// </exception> public static void InitElements(object page, IElementLocator locator, IPageObjectMemberDecorator decorator) { if (page == null) { throw new ArgumentNullException("page", "page cannot be null"); } if (locator == null) { throw new ArgumentNullException("locator", "locator cannot be null"); } if (decorator == null) { throw new ArgumentNullException("locator", "decorator cannot be null"); } if (locator.SearchContext == null) { throw new ArgumentException("The SearchContext of the locator object cannot be null", "locator"); } const BindingFlags PublicBindingOptions = BindingFlags.Instance | BindingFlags.Public; const BindingFlags NonPublicBindingOptions = BindingFlags.Instance | BindingFlags.NonPublic; // Get a list of all of the fields and properties (public and non-public [private, protected, etc.]) // in the passed-in page object. Note that we walk the inheritance tree to get superclass members. var type = page.GetType(); var members = new List<MemberInfo>(); members.AddRange(type.GetFields(PublicBindingOptions)); members.AddRange(type.GetProperties(PublicBindingOptions)); while (type != null) { members.AddRange(type.GetFields(NonPublicBindingOptions)); members.AddRange(type.GetProperties(NonPublicBindingOptions)); type = type.BaseType; } foreach (var member in members) { // Examine each member, and if the decorator returns a non-null object, // set the value of that member to the decorated object. object decoratedValue = decorator.Decorate(member, locator); if (decoratedValue == null) { continue; } var field = member as FieldInfo; var property = member as PropertyInfo; if (field != null) { field.SetValue(page, decoratedValue); } else if (property != null) { property.SetValue(page, decoratedValue, null); } } } } } #endif
using UnityEngine; using System.Collections; using UnityEngine.UI.Windows; using UnityEngine.UI; using UnityEngine.Events; using System; using UnityEngine.UI.Windows.Components.Events; using UnityEngine.EventSystems; using UnityEngine.UI.Windows.Extensions; using UnityEngine.UI.Windows.Components.Modules; namespace UnityEngine.UI.Windows.Components { public enum ColorState : byte { Normal, Highlighted, Pressed, Disabled, }; public static class ButtonComponentUtils { public static bool IsInteractableAndActive(this IComponent item) { if (item == null) return false; IInteractableComponent button = null; if (item is LinkerComponent) { button = (item as LinkerComponent).Get<IInteractableComponent>(); } else { button = item as IInteractableComponent; } if (button != null && button.IsVisible() == true && button.IsInteractable() == true) return true; return false; } }; public class ButtonComponent : WindowComponentNavigation, IButtonComponent, IEventSystemHandler { public override void Setup(IComponentParameters parameters) { base.Setup(parameters); var inputParameters = parameters as ButtonComponentParameters; { if (inputParameters != null) inputParameters.Setup(this as IButtonComponent); } #region macros UI.Windows.Initialization.TextComponent /* * This code is auto-generated by Macros Module * Do not change anything */ { if (inputParameters != null) inputParameters.Setup(this as ITextComponent); } #endregion #region macros UI.Windows.Initialization.ImageComponent /* * This code is auto-generated by Macros Module * Do not change anything */ { if (inputParameters != null) inputParameters.Setup(this as IImageComponent); } #endregion } public override void OnWindowInactive() { base.OnWindowInactive(); #region macros UI.Windows.OnWindowInactive.TextComponent #endregion #region macros UI.Windows.OnWindowInactive.ImageComponent /* * This code is auto-generated by Macros Module * Do not change anything */ { this.tempMovieIsPlaying = this.IsPlaying(); this.Pause(); } #endregion } public override void OnWindowActive() { base.OnWindowActive(); #region macros UI.Windows.OnWindowActive.TextComponent #endregion #region macros UI.Windows.OnWindowActive.ImageComponent /* * This code is auto-generated by Macros Module * Do not change anything */ { if (this.tempMovieIsPlaying == true) { this.Play(); this.tempMovieIsPlaying = false; } } #endregion } public override void OnLocalizationChanged() { base.OnLocalizationChanged(); #region macros UI.Windows.OnLocalizationChanged.TextComponent /* * This code is auto-generated by Macros Module * Do not change anything */ { if (this.lastTextLocalization == true) { this.SetText(this.lastTextLocalizationKey, this.lastTextLocalizationParameters); } else { if (this.text is UnityEngine.UI.Windows.Plugins.Localization.UI.LocalizationText) { (this.text as UnityEngine.UI.Windows.Plugins.Localization.UI.LocalizationText).OnLocalizationChanged(); } } } #endregion #region macros UI.Windows.OnLocalizationChanged.ImageComponent /* * This code is auto-generated by Macros Module * Do not change anything */ { if (this.lastImageLocalization == true) { this.SetImage(this.lastImageLocalizationKey, this.lastImageLocalizationParameters); } else { if (this.image is UnityEngine.UI.Windows.Plugins.Localization.UI.LocalizationImage) { (this.image as UnityEngine.UI.Windows.Plugins.Localization.UI.LocalizationImage).OnLocalizationChanged(); } } } #endregion } public override void OnInit() { base.OnInit(); if (this.button != null) { this.button.onClick.AddListener(this.OnClick); if (this.button is ButtonExtended) { (this.button as ButtonExtended).Setup(this); } } if (this.setDefaultNavigationModeOnStart == true) { this.SetNavigationMode(this.defaultNavigationMode); } #region macros UI.Windows.OnInit.TextComponent /* * This code is auto-generated by Macros Module * Do not change anything */ { this.textCrossFadeModule.Init(this); if (this.textLocalizationKey.IsNone() == false) { this.SetText(this.textLocalizationKey); } } #endregion #region macros UI.Windows.OnInit.ImageComponent /* * This code is auto-generated by Macros Module * Do not change anything */ { this.tempImagePlayOnShow = false; if (this.imageLocalizationKey.IsNone() == false) { if ((this.imageResource.controlType & ResourceAuto.ControlType.Init) != 0) { this.SetImage(this.imageLocalizationKey); } } else { WindowSystemResources.LoadAuto(this, onDataLoaded: () => { this.tempImagePlayOnShow = true; if (this.IsVisible() == true) { if (this.playOnShow == true) { this.Play(); } } }, onComplete: null, onShowHide: false); } this.imageCrossFadeModule.Init(this); } #endregion } #region WindowComponent events public override void OnDeinit(System.Action callback) { base.OnDeinit(callback); #region macros UI.Windows.OnDeinit.TextComponent #endregion #region macros UI.Windows.OnDeinit.ImageComponent /* * This code is auto-generated by Macros Module * Do not change anything */ { this.Stop(); WindowSystemResources.UnloadAuto(this, onShowHide: false); } #endregion //this.onState = null; //this.onStateActive = false; if (this.button != null) { this.button.onClick.RemoveListener(this.OnClick); } this.callback.RemoveAllListeners(); this.callbackButton.RemoveAllListeners(); } public override void DoShowBegin(AppearanceParameters parameters) { #region macros UI.Windows.DoShowBegin.TextComponent #endregion #region macros UI.Windows.DoShowBegin.ImageComponent /* * This code is auto-generated by Macros Module * Do not change anything */ { if (this.imageResourceWait == true && this.imageResource.IsValid() == true) { WindowSystemResources.LoadAuto(this, onDataLoaded: () => { this.tempImagePlayOnShow = true; if (this.playOnShow == true) { this.Play(); } }, onComplete: () => { base.DoShowBegin(parameters); }, onShowHide: true, onFailed: () => { base.DoShowBegin(parameters); }); } else { base.DoShowBegin(parameters); } } #endregion } public override void OnShowBegin() { base.OnShowBegin(); //this.onStateActive = true; if (this.selectByDefault == true) { this.Select(); } #region macros UI.Windows.OnShowBegin.TextComponent #endregion #region macros UI.Windows.OnShowBegin.ImageComponent /* * This code is auto-generated by Macros Module * Do not change anything */ { if (this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.Prepare(this); } if (this.imageLocalizationKey.IsNone() == false) { if ((this.imageResource.controlType & ResourceAuto.ControlType.Show) != 0) { this.SetImage(this.imageLocalizationKey); } } else { WindowSystemResources.LoadAuto(this, onDataLoaded: () => { if (this.playOnShow == true) { this.Play(); } }, onComplete: null, onShowHide: true); } if (this.tempImagePlayOnShow == true) { if (this.playOnShow == true) { this.Play(); } } } #endregion } public override void OnHideEnd() { base.OnHideEnd(); #region macros UI.Windows.OnHideEnd.TextComponent #endregion #region macros UI.Windows.OnHideEnd.ImageComponent /* * This code is auto-generated by Macros Module * Do not change anything */ { //this.Stop(); WindowSystemResources.UnloadAuto(this, onShowHide: true); } #endregion //this.onStateActive = false; } public override void OnHideBegin() { base.OnHideBegin(); #region macros UI.Windows.OnHideBegin.TextComponent #endregion #region macros UI.Windows.OnHideBegin.ImageComponent #endregion this.OnPointerExit(null); } #endregion #region Button Base [Header("Button Component")] private ComponentEvent callback = new ComponentEvent(); private ComponentEvent<ButtonComponent> callbackButton = new ComponentEvent<ButtonComponent>(); [SerializeField] [BeginGroup("button")] protected Button button; [SerializeField] private bool setDefaultNavigationModeOnStart = true; [SerializeField][ReadOnly("setDefaultNavigationModeOnStart", state: false)] private Navigation.Mode defaultNavigationMode = Navigation.Mode.None; [SerializeField][EndGroup] protected bool selectByDefault; public virtual IButtonComponent SetSelectByDefault(bool state) { this.selectByDefault = state; return this; } public IButtonComponent SetNavigationMode(Navigation.Mode mode) { if (this.button != null) { var nav = this.button.navigation; nav.mode = mode; this.button.navigation = nav; } return this; } public void SetLabelStateColor(ColorState state, Color color) { if (this.button.IsDestroyed() == true) return; var button = this.button as ButtonWithLabel; if (button == null) return; var colors = button.labelColor; if (state == ColorState.Normal) colors.normalColor = color; if (state == ColorState.Highlighted) colors.highlightedColor = color; if (state == ColorState.Pressed) colors.pressedColor = color; if (state == ColorState.Disabled) colors.disabledColor = color; button.labelColor = colors; this.Refresh(); } public Color GetLabelStateColor(ColorState state) { var button = this.button as ButtonWithLabel; if (button == null) return default(Color); var colors = button.labelColor; if (state == ColorState.Normal) return colors.normalColor; if (state == ColorState.Highlighted) return colors.highlightedColor; if (state == ColorState.Pressed) return colors.pressedColor; if (state == ColorState.Disabled) return colors.disabledColor; return default(Color); } public void SetStateColor(ColorState state, Color color) { if (this.button.IsDestroyed() == true) return; var colors = this.button.colors; if (state == ColorState.Normal) colors.normalColor = color; if (state == ColorState.Highlighted) colors.highlightedColor = color; if (state == ColorState.Pressed) colors.pressedColor = color; if (state == ColorState.Disabled) colors.disabledColor = color; this.button.colors = colors; this.Refresh(); } public Color GetStateColor(ColorState state) { var colors = this.button.colors; if (state == ColorState.Normal) return colors.normalColor; if (state == ColorState.Highlighted) return colors.highlightedColor; if (state == ColorState.Pressed) return colors.pressedColor; if (state == ColorState.Disabled) return colors.disabledColor; return default(Color); } public void Refresh() { if (this.button.IsDestroyed() == true) return; ColorBlock colors; var labelFadeDuration = 0f; var buttonLabel = this.button as ButtonWithLabel; if (buttonLabel != null) { colors = buttonLabel.labelColor; labelFadeDuration = colors.fadeDuration; colors.fadeDuration = 0f; buttonLabel.labelColor = colors; } colors = this.button.colors; var fadeDuration = colors.fadeDuration; colors.fadeDuration = 0f; this.button.colors = colors; this.button.interactable = !this.button.interactable; this.button.interactable = !this.button.interactable; colors = this.button.colors; colors.fadeDuration = fadeDuration; this.button.colors = colors; if (buttonLabel != null) { colors = buttonLabel.labelColor; colors.fadeDuration = labelFadeDuration; buttonLabel.labelColor = colors; } } public virtual Selectable GetSelectable() { return this.button; } #region source macros UI.Windows.ButtonComponent.States [SerializeField][ReadOnly("hoverIsActive", state: false)] private bool hoverOnAnyButtonState = false; [SerializeField][ReadOnly("hoverIsActive", state: false)] private bool hoverCursorDefaultOnInactive = false; public bool IsHoverCursorDefaultOnInactive() { return this.IsInteractable() == false && this.hoverCursorDefaultOnInactive == true; } public void Select() { this.GetSelectable().Select(); } public virtual IInteractableComponent SetEnabledState(bool state) { if (state == true) { this.SetEnabled(); } else { this.SetDisabled(); } return this; } public virtual IInteractableComponent SetDisabled() { var sel = this.GetSelectable(); if (sel != null) { if (sel.interactable != false) { sel.interactable = false; this.OnInteractableChanged(); } } return this; } public virtual IInteractableComponent SetEnabled() { var sel = this.GetSelectable(); if (sel != null) { if (sel.interactable != true) { sel.interactable = true; this.OnInteractableChanged(); } } return this; } public IInteractableComponent SetHoverOnAnyButtonState(bool state) { this.hoverOnAnyButtonState = state; return this; } protected override bool ValidateHoverPointer() { if (this.hoverOnAnyButtonState == false && this.IsInteractable() == false) return false; return base.ValidateHoverPointer(); } public bool IsInteractable() { var sel = this.GetSelectable(); return (sel != null ? sel.IsInteractable() : false); } public virtual void OnInteractableChanged() { } #endregion public bool IsInteractableAndHasEvents() { return this.IsInteractable() == true /*&& ( this.callback.GetPersistentEventCount() > 0 || this.callbackButton.GetPersistentEventCount() > 0 || this.button.onClick.GetPersistentEventCount() > 0 )*/; } /* public IButtonComponent SetEnabledState(System.Func<bool> onState) { this.onState = onState; this.oldState = this.onState(); this.onStateActive = true; return this; } public virtual void LateUpdate() { if (this.onStateActive == true && this.onState != null) { var newState = this.onState(); if (newState != this.oldState) this.SetEnabledState(newState); this.oldState = newState; } }*/ public virtual IButtonComponent SetButtonColor(Color color) { if (this.button != null && this.button.targetGraphic != null) { this.button.targetGraphic.color = color; } return this; } public virtual IButtonComponent RemoveAllCallbacks() { if (this.button == null) return this; this.callback.RemoveAllListeners(); this.callbackButton.RemoveAllListeners(); return this; } public virtual IButtonComponent RemoveCallback(System.Action callback) { if (this.button == null) return this; this.callback.RemoveListener(callback); return this; } public virtual IButtonComponent RemoveCallback(System.Action<ButtonComponent> callback) { if (this.button == null) return this; this.callbackButton.RemoveListener(callback); return this; } public virtual IButtonComponent SetCallback(System.Action callback) { if (this.button == null) return this; this.callback.RemoveAllListeners(); this.callback.AddListenerDistinct(callback); this.callbackButton.RemoveAllListeners(); return this; } public virtual IButtonComponent SetCallback(System.Action<ButtonComponent> callback) { if (this.button == null) return this; this.callbackButton.RemoveAllListeners(); this.callbackButton.AddListenerDistinct(callback); this.callback.RemoveAllListeners(); return this; } public virtual IButtonComponent AddCallback(System.Action callback) { if (this.button == null) return this; this.callback.AddListenerDistinct(callback); return this; } public virtual IButtonComponent AddCallback(System.Action<ButtonComponent> callback) { if (this.button == null) return this; this.callbackButton.AddListenerDistinct(callback); return this; } public IInteractableControllerComponent Click() { var sel = this.GetSelectable(); if (sel != null) { var pointer = new PointerEventData(EventSystem.current); ExecuteEvents.Execute(sel.gameObject, pointer, ExecuteEvents.submitHandler); } return this; } public virtual void OnClick() { if (this.GetWindow() != null && this.GetWindow().GetState() != WindowObjectState.Shown && this.GetWindow().GetState() != WindowObjectState.Showing) { #if UNITY_EDITOR || DEBUGBUILD Debug.LogWarningFormat("Can't send click on `{0}` state. Be sure `{1}` window has the `Shown` or `Showing` state.", this.GetWindow().GetState(), this.GetWindow().name); #endif return; } this.sfxOnClick.Play(); if (this.callback != null) this.callback.Invoke(); if (this.callbackButton != null) this.callbackButton.Invoke(this); } #endregion #region macros UI.Windows.ImageComponent (overrideColor:override) /* * This code is auto-generated by Macros Module * Do not change anything */ [Header("Image Component")] [SerializeField] private Image image; [BeginGroup("image")][SerializeField] private RawImage rawImage; [SerializeField] private bool flipHorizontal; [SerializeField] private bool flipVertical; private bool flipHorizontalInternal; private bool flipVerticalInternal; [SerializeField] private bool preserveAspect; [HideInInspector][SerializeField] private UIFlippable flippableEffect; [HideInInspector][SerializeField] private UIPreserveAspect preserveAspectEffect; public UnityEngine.UI.Windows.Plugins.Localization.LocalizationKey imageLocalizationKey; [ReadOnly("rawImage", null)] [SerializeField][UnityEngine.Serialization.FormerlySerializedAs("playOnStart")] private bool playOnShow; [ReadOnly("rawImage", null)] [SerializeField] private bool loop; [SerializeField] private bool imageResourceWait = false; [SerializeField] private ResourceAuto imageResource = new ResourceAuto(); [EndGroup][SerializeField] private ImageCrossFadeModule imageCrossFadeModule = new ImageCrossFadeModule(); private bool tempImagePlayOnShow = false; private bool tempMovieIsPlaying = false; public ResourceBase GetResource() { return this.imageResource; } public IImageComponent SetPreserveAspectState(bool state) { this.preserveAspect = state; return this; } public IImageComponent SetLoop(bool state) { this.loop = state; return this; } public bool IsLoop() { return this.loop; } public bool IsMovie() { var image = this.GetRawImageSource(); if (image == null) return false; return MovieSystem.IsMovie(image.mainTexture); } public IImageComponent Unload(ResourceBase resource) { WindowSystemResources.Unload(this, resource); return this; } public void SetVerticesDirty() { if (this.image != null) this.image.SetVerticesDirty(); if (this.rawImage != null) this.rawImage.SetVerticesDirty(); } public IImageComponent SetImageLocalizationKey(UnityEngine.UI.Windows.Plugins.Localization.LocalizationKey key) { this.imageLocalizationKey = key; return this; } public IImageComponent SetMovieTexture(ResourceAuto resource, System.Action onDataLoaded, System.Action onComplete = null, System.Action onFailed = null) { this.flipVerticalInternal = MovieSystem.IsVerticalFlipped(); this.SetVerticesDirty(); this.Stop(); this.SetImage(resource, onDataLoaded: () => { if (onDataLoaded != null) onDataLoaded.Invoke(); }, onComplete: () => { //Debug.Log("SetMovieTexture: " + this.name); MovieSystem.UnregisterOnUpdateTexture(this.ValidateTexture); MovieSystem.RegisterOnUpdateTexture(this.ValidateTexture); if (onComplete != null) onComplete.Invoke(); }, onFailed: onFailed); return this; } private void ValidateTexture(IImageComponent component, Texture texture) { //Debug.Log("ValidateTexture: " + (component as MonoBehaviour) + ", tex: " + texture, component as MonoBehaviour); if (this as IImageComponent == component) { if (this.rawImage != null) { if (this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.ValidateTexture(texture); } else { this.rawImage.texture = texture; } } } } public bool GetPlayOnShow() { return this.playOnShow; } public IImageComponent SetPlayOnShow(bool state) { this.playOnShow = state; return this; } public virtual bool IsPlaying() { return MovieSystem.IsPlaying(this); } public virtual IImageComponent PlayAndPause() { MovieSystem.PlayAndPause(this, this.loop); return this; } public virtual IImageComponent Rewind(bool pause = true) { MovieSystem.Rewind(this, pause); return this; } public virtual IImageComponent Play() { return this.Play(this.loop); } public virtual IImageComponent Play(bool loop) { MovieSystem.Play(this, loop); return this; } public virtual IImageComponent Play(bool loop, System.Action onComplete) { MovieSystem.Play(this, loop, onComplete); return this; } public virtual IImageComponent Stop() { MovieSystem.UnregisterOnUpdateMaterial(this.ValidateMaterial); MovieSystem.UnregisterOnUpdateTexture(this.ValidateTexture); MovieSystem.Stop(this); return this; } public virtual IImageComponent Pause() { MovieSystem.Pause(this); return this; } public Texture GetTexture() { if (this.image != null) { return (this.image.sprite != null ? this.image.sprite.texture : null); } if (this.rawImage != null) { return this.rawImage.texture; } return null; } public IImageComponent ResetImage() { if (this.image != null) { this.image.sprite = null; } if (this.rawImage != null) { this.Stop(); this.rawImage.texture = null; } this.flipHorizontalInternal = false; this.flipVerticalInternal = false; return this; } Graphic IImageComponent.GetGraphicSource() { if (this.image != null) return this.image; return this.rawImage; } public Image GetImageSource() { return this.image; } public RawImage GetRawImageSource() { return this.rawImage; } public bool IsHorizontalFlip() { return this.flipHorizontal == true || this.flipHorizontalInternal == true; } public bool IsVerticalFlip() { return this.flipVertical == true || this.flipVerticalInternal == true; } public bool IsPreserveAspect() { return this.preserveAspect; } public IImageComponent SetImage(ImageComponent source) { if (source.GetImageSource() != null) this.SetImage(source.GetImageSource().sprite); if (source.GetRawImageSource() != null) this.SetImage(source.GetRawImageSource().texture); return this; } public IImageComponent SetImage(ResourceAuto resource, System.Action onDataLoaded = null, System.Action onComplete = null, System.Action onFailed = null) { ME.Coroutines.Run(this.SetImage_INTERNAL(resource, onDataLoaded, onComplete, onFailed)); return this; } private System.Collections.Generic.IEnumerator<byte> SetImage_INTERNAL(ResourceAuto resource, System.Action onDataLoaded = null, System.Action onComplete = null, System.Action onFailed = null) { yield return 0; if (this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.Prepare(this); } var oldResource = this.imageResource; var newResource = resource; this.imageResource = resource; // Debug.Log("Loading resource: " + this.imageResource.GetId()); WindowSystemResources.Load(this, onDataLoaded: onDataLoaded, onComplete: () => { //Debug.Log("Resource loaded: " + newResource.GetId() + " :: " + this.name, this); if (newResource.GetId() != oldResource.GetId()) { // Debug.Log("Unloading: " + newResource.GetId() + " != " + oldResource.GetId() + " :: " + this.name, this); WindowSystemResources.Unload(this, oldResource, resetController: false); } if (onComplete != null) onComplete.Invoke(); }, onFailed: () => { //Debug.Log("Resource loading failed: " + newResource.GetId() + " :: " + this.name, this); if (newResource.GetId() != oldResource.GetId()) { //Debug.Log("Failed, Unloading: " + this.imageResource.GetId() + " != " + oldResource.GetId() + " :: " + this.name, this); WindowSystemResources.Unload(this, oldResource, resetController: false); } if (onFailed != null) onFailed.Invoke(); } ); } private bool lastImageLocalization = false; private Plugins.Localization.LocalizationKey lastImageLocalizationKey; private object[] lastImageLocalizationParameters; public IImageComponent SetImage(UnityEngine.UI.Windows.Plugins.Localization.LocalizationKey key, params object[] parameters) { if (this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.Prepare(this); } this.lastImageLocalization = true; this.lastImageLocalizationKey = key; this.lastImageLocalizationParameters = parameters; this.SetImage(ResourceAuto.CreateResourceRequest(UnityEngine.UI.Windows.Plugins.Localization.LocalizationSystem.GetSpritePath(key, parameters))); //this.SetImage(UnityEngine.UI.Windows.Plugins.Localization.LocalizationSystem.GetSprite(key, parameters)); //WindowSystemResources.Unload(this, this.GetResource()); //WindowSystemResources.Load(this, onDataLoaded: null, onComplete: null, customResourcePath: UnityEngine.UI.Windows.Plugins.Localization.LocalizationSystem.GetSpritePath(key, parameters)); return this; } public IImageComponent SetImage(Sprite sprite) { return this.SetImage(sprite, this.preserveAspect, false, null, false); } public IImageComponent SetImage(Sprite sprite, bool immediately) { return this.SetImage(sprite, this.preserveAspect, false, null, immediately); } public IImageComponent SetImage(Sprite sprite, System.Action onComplete) { return this.SetImage(sprite, this.preserveAspect, false, onComplete, false); } public IImageComponent SetImage(Sprite sprite, System.Action onComplete, bool immediately) { return this.SetImage(sprite, this.preserveAspect, false, onComplete, immediately); } public IImageComponent SetImage(Sprite sprite, bool preserveAspect, bool withPivotsAndSize, System.Action onComplete) { return this.SetImage(sprite, preserveAspect, withPivotsAndSize, onComplete, false); } public IImageComponent SetImage(Sprite sprite, bool preserveAspect, bool withPivotsAndSize, System.Action onComplete = null, bool immediately = false) { if (this.image != null) { if (this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.Prepare(this); } this.image.preserveAspect = preserveAspect; if (withPivotsAndSize == true && sprite != null) { var rect = (this.transform as RectTransform); rect.sizeDelta = sprite.rect.size; rect.pivot = sprite.GetPivot(); rect.anchoredPosition = Vector2.zero; } if (immediately == false && this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.FadeTo(this, sprite, onComplete); } else { this.image.sprite = sprite; if (onComplete != null) onComplete.Invoke(); } } else { if (onComplete != null) onComplete.Invoke(); } return this; } public IImageComponent SetImage(Texture texture) { return this.SetImage(texture, this.preserveAspect, null, false); } public IImageComponent SetImage(Texture texture, bool immediately) { return this.SetImage(texture, this.preserveAspect, null, immediately); } public IImageComponent SetImage(Texture texture, System.Action onComplete) { return this.SetImage(texture, this.preserveAspect, onComplete, false); } public IImageComponent SetImage(Texture texture, System.Action onComplete, bool immediately) { return this.SetImage(texture, this.preserveAspect, onComplete, immediately); } public IImageComponent SetImage(Texture texture, bool preserveAspect, System.Action onComplete) { return this.SetImage(texture, preserveAspect, onComplete, false); } public IImageComponent SetImage(Texture texture, bool preserveAspect, System.Action onComplete, bool immediately) { //MovieSystem.UnregisterOnUpdateTexture(this.ValidateTexture); //MovieSystem.Stop(this, this.rawImage.texture.GetInstanceID()); if (this.rawImage != null) { if (this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.Prepare(this); } if (immediately == false && this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.FadeTo(this, texture, onComplete); } else { this.rawImage.texture = texture; if (onComplete != null) onComplete.Invoke(); } } else { if (onComplete != null) onComplete.Invoke(); } return this; } public override Color GetColor() { Color color = Color.white; if (this.image != null) { color = this.image.color; } else if (this.rawImage != null) { color = this.rawImage.color; } return color; } public override void SetColor(Color color) { if (this.image != null) { this.image.color = color; } if (this.rawImage != null) { this.rawImage.color = color; } } public IAlphaComponent SetAlpha(float value) { var color = this.GetColor(); color.a = value; this.SetColor(color); return this; } public IImageComponent SetMaterial(Material material, bool setMainTexture = false, System.Action onComplete = null) { MovieSystem.UnregisterOnUpdateMaterial(this.ValidateMaterial); if (material == null) { if (this.image != null) { this.image.material = null; this.image.SetMaterialDirty(); } else if (this.rawImage != null) { this.rawImage.material = null; this.rawImage.SetMaterialDirty(); } if (onComplete != null) onComplete.Invoke(); return this; } MovieSystem.RegisterOnUpdateMaterial(this.ValidateMaterial); if (this.image != null) { if (this.image.enabled == false) this.image.enabled = true; var tex = material.mainTexture; if (this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.FadeTo<Image>(this, material, () => { if (setMainTexture == true) { var sprite = Sprite.Create(tex as Texture2D, new Rect(0f, 0f, tex.width, tex.height), Vector2.one * 0.5f); this.image.sprite = sprite; } this.image.SetMaterialDirty(); if (onComplete != null) onComplete.Invoke(); }, ImageCrossFadeModule.DataType.Material); } else { if (setMainTexture == true) { var sprite = Sprite.Create(tex as Texture2D, new Rect(0f, 0f, tex.width, tex.height), Vector2.one * 0.5f); this.image.sprite = sprite; } this.image.material = material; this.image.SetMaterialDirty(); if (onComplete != null) onComplete.Invoke(); } } else if (this.rawImage != null) { if (this.rawImage.enabled == false) this.rawImage.enabled = true; var tex = material.mainTexture; if (this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.FadeTo<RawImage>(this, material, () => { if (setMainTexture == true) { this.rawImage.texture = tex; } this.rawImage.SetMaterialDirty(); if (onComplete != null) onComplete.Invoke(); }, ImageCrossFadeModule.DataType.Material); } else { if (setMainTexture == true) { this.rawImage.texture = tex; } this.rawImage.material = material; this.rawImage.SetMaterialDirty(); if (onComplete != null) onComplete.Invoke(); } } return this; } public void ValidateMaterial(Material material) { if (this.rawImage != null) { this.rawImage.texture = this.rawImage.material.mainTexture; if (this.imageCrossFadeModule.IsValid() == true) { this.imageCrossFadeModule.ValidateMaterial(material); } //Debug.Log("MATERIAL DIRTY: " + this.rawImage.texture, this); } } /* public void ModifyMesh(Mesh mesh) {} private System.Collections.Generic.List<UIVertex> modifyVertsTemp = new System.Collections.Generic.List<UIVertex>(); public void ModifyMesh(VertexHelper helper) { if (this.rawImage != null && this.preserveAspect == true) { var vh = helper; var drawingDimensions = ME.Utilities.GetDrawingDimensions(this.rawImage, this.preserveAspect, this.rawImage.texture == null ? Vector2.zero : new Vector2(this.rawImage.texture.width, this.rawImage.texture.height), Vector4.zero); var vector = new Vector4(this.rawImage.uvRect.x, this.rawImage.uvRect.y, this.rawImage.uvRect.width, this.rawImage.uvRect.height); var color = this.GetColor(); vh.Clear(); vh.AddVert(new Vector3(drawingDimensions.x, drawingDimensions.y), color, new Vector2(vector.x, vector.y)); vh.AddVert(new Vector3(drawingDimensions.x, drawingDimensions.w), color, new Vector2(vector.x, vector.w)); vh.AddVert(new Vector3(drawingDimensions.z, drawingDimensions.w), color, new Vector2(vector.z, vector.w)); vh.AddVert(new Vector3(drawingDimensions.z, drawingDimensions.y), color, new Vector2(vector.z, vector.y)); vh.AddTriangle(0, 1, 2); vh.AddTriangle(2, 3, 0); } if (this.flipHorizontal == true || this.flipVertical == true || this.flipHorizontalInternal == true || this.flipVerticalInternal == true) { this.modifyVertsTemp.Clear(); helper.GetUIVertexStream(this.modifyVertsTemp); this.ModifyVertices(this.modifyVertsTemp); helper.AddUIVertexTriangleStream(this.modifyVertsTemp); } } public void ModifyVertices(System.Collections.Generic.List<UIVertex> verts) { var rt = this.GetRectTransform(); var rectCenter = rt.rect.center; for (var i = 0; i < verts.Count; ++i) { var v = verts[i]; v.position = new Vector3( ((this.flipHorizontal == true || this.flipHorizontalInternal == true) ? (v.position.x + (rectCenter.x - v.position.x) * 2f) : v.position.x), ((this.flipVertical == true || this.flipVerticalInternal == true) ? (v.position.y + (rectCenter.y - v.position.y) * 2f) : v.position.y), v.position.z ); verts[i] = v; } }*/ #endregion #region macros UI.Windows.TextComponent /* * This code is auto-generated by Macros Module * Do not change anything */ [Header("Text Component")] [BeginGroup] [SerializeField] private MaskableGraphic text; [SerializeField] private TextValueFormat valueFormat; [SerializeField][BitMask(typeof(FullTextFormat))] private FullTextFormat fullTextFormat; [SerializeField][BitMask(typeof(RichTextFlags))] private RichTextFlags richTextFlags = RichTextFlags.Color | RichTextFlags.Bold | RichTextFlags.Italic | RichTextFlags.Size | RichTextFlags.Material | RichTextFlags.Quad; public UnityEngine.UI.Windows.Plugins.Localization.LocalizationKey textLocalizationKey; [SerializeField] private bool valueAnimate = false; [SerializeField][ReadOnly("valueAnimate", state: false)] private float valueAnimateDuration = 2f; [EndGroup][SerializeField] private TextCrossFadeModule textCrossFadeModule = new TextCrossFadeModule(); private long valueAnimateLastValue; private long tempLastValue = long.MinValue; private TextValueFormat tempLastFormat = TextValueFormat.None; Graphic ITextComponent.GetGraphicSource() { return this.text; } public ITextComponent SetBestFit(bool state, int minSize = 10, int maxSize = 40) { if (this.text != null) { this.SetBestFitState(state); this.SetBestFitMinSize(minSize); this.SetBestFitMaxSize(maxSize); } return this; } public ITextComponent SetTextLocalizationKey(UnityEngine.UI.Windows.Plugins.Localization.LocalizationKey key) { this.textLocalizationKey = key; return this; } public ITextComponent SetBestFitState(bool state) { if (TextComponentUGUIAddon.IsValid(this.text) == true) TextComponentUGUIAddon.SetBestFitState(this.text, state); if (TextComponentTMPAddon.IsValid(this.text) == true) TextComponentTMPAddon.SetBestFitState(this.text, state); return this; } public ITextComponent SetBestFitMinSize(int size) { if (TextComponentUGUIAddon.IsValid(this.text) == true) TextComponentUGUIAddon.SetBestFitMinSize(this.text, size); if (TextComponentTMPAddon.IsValid(this.text) == true) TextComponentTMPAddon.SetBestFitMinSize(this.text, size); return this; } public ITextComponent SetBestFitMaxSize(int size) { if (TextComponentUGUIAddon.IsValid(this.text) == true) TextComponentUGUIAddon.SetBestFitMaxSize(this.text, size); if (TextComponentTMPAddon.IsValid(this.text) == true) TextComponentTMPAddon.SetBestFitMaxSize(this.text, size); return this; } public int GetFontSize() { if (TextComponentUGUIAddon.IsValid(this.text) == true) return TextComponentUGUIAddon.GetFontSize(this.text); if (TextComponentTMPAddon.IsValid(this.text) == true) return TextComponentTMPAddon.GetFontSize(this.text); return 0; } public ITextComponent SetFontSize(int fontSize) { if (TextComponentUGUIAddon.IsValid(this.text) == true) TextComponentUGUIAddon.SetFontSize(this.text, fontSize); if (TextComponentTMPAddon.IsValid(this.text) == true) TextComponentTMPAddon.SetFontSize(this.text, fontSize); return this; } public ITextComponent SetLineSpacing(float value) { if (TextComponentUGUIAddon.IsValid(this.text) == true) TextComponentUGUIAddon.SetLineSpacing(this.text, value); if (TextComponentTMPAddon.IsValid(this.text) == true) TextComponentTMPAddon.SetLineSpacing(this.text, value); return this; } public ITextComponent SetRichText(bool state) { if (TextComponentUGUIAddon.IsValid(this.text) == true) TextComponentUGUIAddon.SetRichText(this.text, state); if (TextComponentTMPAddon.IsValid(this.text) == true) TextComponentTMPAddon.SetRichText(this.text, state); return this; } public float GetContentHeight(float heightPadding = 0f) { if (this.text == null) return 0f; return this.GetContentHeight(this.GetText(), heightPadding); } public float GetContentHeight(string text, float heightPadding = 0f) { if (this.text == null) return 0f; return this.GetContentHeight(text, (this.transform.root as RectTransform).rect.size) + heightPadding; } public float GetContentHeight(string text, Vector2 containerSize) { if (this.text == null) return 0f; if (TextComponentUGUIAddon.IsValid(this.text) == true) return TextComponentUGUIAddon.GetContentHeight(this.text, text, containerSize); if (TextComponentTMPAddon.IsValid(this.text) == true) return TextComponentTMPAddon.GetContentHeight(this.text, text, containerSize); return 0f; } public ITextComponent SetTextAlignByGeometry(bool state) { if (TextComponentUGUIAddon.IsValid(this.text) == true) TextComponentUGUIAddon.SetTextAlignByGeometry(this.text, state); if (TextComponentTMPAddon.IsValid(this.text) == true) TextComponentTMPAddon.SetTextAlignByGeometry(this.text, state); return this; } public ITextComponent SetTextVerticalOverflow(VerticalWrapMode mode) { if (TextComponentUGUIAddon.IsValid(this.text) == true) TextComponentUGUIAddon.SetTextVerticalOverflow(this.text, mode); if (TextComponentTMPAddon.IsValid(this.text) == true) TextComponentTMPAddon.SetTextVerticalOverflow(this.text, mode); return this; } public ITextComponent SetTextHorizontalOverflow(HorizontalWrapMode mode) { if (TextComponentUGUIAddon.IsValid(this.text) == true) TextComponentUGUIAddon.SetTextHorizontalOverflow(this.text, mode); if (TextComponentTMPAddon.IsValid(this.text) == true) TextComponentTMPAddon.SetTextHorizontalOverflow(this.text, mode); return this; } public ITextComponent SetTextAlignment(TextAnchor anchor) { if (TextComponentUGUIAddon.IsValid(this.text) == true) TextComponentUGUIAddon.SetTextAlignment(this.text, anchor); if (TextComponentTMPAddon.IsValid(this.text) == true) TextComponentTMPAddon.SetTextAlignment(this.text, anchor); return this; } public string GetText() { if (TextComponentUGUIAddon.IsValid(this.text) == true) return TextComponentUGUIAddon.GetText(this.text); if (TextComponentTMPAddon.IsValid(this.text) == true) return TextComponentTMPAddon.GetText(this.text); return string.Empty; } public ITextComponent SetValueAnimate(bool state) { this.valueAnimate = state; return this; } public ITextComponent SetValueAnimateDuration(float duration) { this.valueAnimateDuration = duration; return this; } public ITextComponent SetFullTextFormat(FullTextFormat format) { this.fullTextFormat = format; return this; } public ITextComponent SetValueFormat(TextValueFormat format) { this.valueFormat = format; return this; } public ITextComponent SetValue(int value) { this.SetValue(value, this.valueFormat); return this; } public ITextComponent SetValue(int value, TextValueFormat format) { return this.SetValue(value, format, this.valueAnimate); } public ITextComponent SetValue(int value, TextValueFormat format, bool animate) { return this.SetValue((long)value, format, animate); } public ITextComponent SetValue(long value) { this.SetValue(value, this.valueFormat); return this; } public ITextComponent SetValue(long value, TextValueFormat format) { return this.SetValue(value, format, this.valueAnimate); } public ITextComponent SetValue(long value, TextValueFormat format, bool animate) { return this.SetValue_INTERNAL(value, format, animate, fromTweener: false); } private ITextComponent SetValue_INTERNAL(long value, TextValueFormat format, bool animate, bool fromTweener) { if (fromTweener == true && this.tempLastValue == value && this.tempLastFormat == format) return this; this.tempLastValue = value; this.tempLastFormat = format; var tag = this.GetCustomTag(this.text); if (fromTweener == false && TweenerGlobal.instance != null) TweenerGlobal.instance.removeTweens(tag); if (animate == true && TweenerGlobal.instance != null) { this.tempLastValue = value - 1L; var duration = this.valueAnimateDuration; if (Mathf.Abs(this.valueAnimateLastValue - value) < 2) duration = 0.2f; TweenerGlobal.instance.addTweenCount(this, duration, this.valueAnimateLastValue, value, format, (v) => { this.SetValue_INTERNAL(v, format, animate: false, fromTweener: true); }).tag(tag); } else { this.valueAnimateLastValue = value; this.SetText_INTERNAL(TextComponent.FormatValue(value, format)); } return this; } public ITextComponent SetHyphenSymbol() { return this.SetText("\u2014"); } private bool lastTextLocalization = false; private Plugins.Localization.LocalizationKey lastTextLocalizationKey; private object[] lastTextLocalizationParameters; public ITextComponent SetText(Plugins.Localization.LocalizationKey key, params object[] parameters) { this.lastTextLocalization = true; this.lastTextLocalizationKey = key; this.lastTextLocalizationParameters = parameters; return this.SetText(Plugins.Localization.LocalizationSystem.Get(key, parameters)); } public ITextComponent SetText(string text) { if (TweenerGlobal.instance != null) TweenerGlobal.instance.removeTweens(this); this.SetText_INTERNAL(text); return this; } private void SetText_INTERNAL(string text) { if (text == null) text = string.Empty; if (this.text != null) { System.Action onComplete = () => { bool supportRichText = false; if (TextComponentUGUIAddon.IsValid(this.text) == true) supportRichText = TextComponentUGUIAddon.IsRichtextSupported(this.text); if (TextComponentTMPAddon.IsValid(this.text) == true) supportRichText = TextComponentTMPAddon.IsRichtextSupported(this.text); if (supportRichText == true) { text = TextComponent.ParseRichText(text, this.GetFontSize(), this.richTextFlags); } text = TextComponent.FullTextFormat(text, this.fullTextFormat); if (TextComponentUGUIAddon.IsValid(this.text) == true) TextComponentUGUIAddon.SetText(this.text, text); if (TextComponentTMPAddon.IsValid(this.text) == true) TextComponentTMPAddon.SetText(this.text, text); }; if (this.textCrossFadeModule.IsValid() == true && TextComponentUGUIAddon.IsValid(this.text) == true) { this.textCrossFadeModule.Prepare(this); this.textCrossFadeModule.FadeTo(this, text, onComplete); } else { onComplete.Invoke(); } } } public virtual ITextComponent SetTextAlpha(float value) { var color = this.GetTextColor(); color.a = value; this.SetTextColor(color); return this; } public virtual ITextComponent SetTextColor(Color color) { if (this.text != null) this.text.color = color; return this; } public virtual Color GetTextColor() { if (this.text == null) return Color.white; return this.text.color; } #endregion #if UNITY_EDITOR public override void OnValidateEditor() { base.OnValidateEditor(); if (this.button == null) { var buttons = this.GetComponentsInChildren<Button>(true); if (buttons.Length == 1) this.button = buttons[0]; } #region macros UI.Windows.Editor.TextComponent /* * This code is auto-generated by Macros Module * Do not change anything */ if (this.text == null) this.text = ME.Utilities.FindReferenceChildren<Text>(this); #endregion #region macros UI.Windows.Editor.ImageComponent /* * This code is auto-generated by Macros Module * Do not change anything */ { //if (this.image == null) this.image = this.GetComponent<Image>(); //if (this.rawImage == null) this.rawImage = this.GetComponent<RawImage>(); WindowSystemResources.Validate(this); this.imageCrossFadeModule.Init(this); this.imageCrossFadeModule.OnValidateEditor(); /*if (this.image == null || this.image.GetComponent<UIFlippable>() == null || this.rawImage == null || this.rawImage.GetComponent<UIFlippable>() == null) { if (this.flippableEffect != null) ME.EditorUtilities.Destroy(this.flippableEffect, () => { this.flippableEffect = null; }); } if (this.rawImage == null || this.rawImage.GetComponent<UIPreserveAspect>() == null) { if (this.preserveAspectEffect != null) ME.EditorUtilities.Destroy(this.preserveAspectEffect, () => { this.preserveAspectEffect = null; }); }*/ var gr = (this.rawImage as Graphic ?? this.image as Graphic); if (gr != null) { this.flippableEffect = gr.GetComponent<UIFlippable>(); if (this.flippableEffect == null) this.flippableEffect = gr.gameObject.AddComponent<UIFlippable>(); if (this.flippableEffect != null) { this.flippableEffect.horizontal = this.flipHorizontal; this.flippableEffect.vertical = this.flipVertical; } } if (this.rawImage != null) { this.preserveAspectEffect = this.rawImage.GetComponent<UIPreserveAspect>(); if (this.preserveAspectEffect == null) this.preserveAspectEffect = this.rawImage.gameObject.AddComponent<UIPreserveAspect>(); if (this.preserveAspectEffect != null) { this.preserveAspectEffect.preserveAspect = this.preserveAspect; this.preserveAspectEffect.rawImage = this.rawImage; } } } #endregion } #endif } }
/* ==================================================================== */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Xml; namespace Macrosys.ReportDesigner { /// <summary> /// Summary description for ChartCtl. /// </summary> internal class ChartCtl : System.Windows.Forms.UserControl, IProperty { private List<XmlNode> _ReportItems; private DesignXmlDraw _Draw; //AJM GJL 14082008 Adding more flags bool fChartType, fVector, fSubtype, fPalette, fRenderElement, fPercentWidth; bool fNoRows, fDataSet, fPageBreakStart, fPageBreakEnd; bool fChartData; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.ComboBox cbChartType; private System.Windows.Forms.ComboBox cbSubType; private System.Windows.Forms.ComboBox cbPalette; private System.Windows.Forms.ComboBox cbRenderElement; private System.Windows.Forms.Label label5; private System.Windows.Forms.NumericUpDown tbPercentWidth; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox tbNoRows; private System.Windows.Forms.Label label7; private System.Windows.Forms.ComboBox cbDataSet; private System.Windows.Forms.CheckBox chkPageBreakStart; private System.Windows.Forms.CheckBox chkPageBreakEnd; private System.Windows.Forms.ComboBox cbChartData; private ComboBox cbDataLabel; private CheckBox chkDataLabel; private Button bDataLabelExpr; private System.Windows.Forms.Label lData1; private ComboBox cbChartData2; private Label lData2; private ComboBox cbChartData3; private Label lData3; private Button bDataExpr; private Button bDataExpr3; private Button bDataExpr2; private ComboBox cbVector; private Button btnVectorExp; private Label label8; private Button button1; private Button button2; private Button button3; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal ChartCtl(DesignXmlDraw dxDraw, List<XmlNode> ris) { _ReportItems = ris; _Draw = dxDraw; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize form using the style node values InitValues(); } private void InitValues() { XmlNode node = _ReportItems[0]; string type = _Draw.GetElementValue(node, "Type", "Column"); this.cbChartType.Text = type; type = type.ToLowerInvariant(); lData2.Enabled = cbChartData2.Enabled = bDataExpr2.Enabled = (type == "scatter" || type == "bubble"); lData3.Enabled = cbChartData3.Enabled = bDataExpr3.Enabled = (type == "bubble"); //AJM GJL 14082008 this.cbVector.Text = _Draw.GetElementValue(node, "fyi:RenderAsVector", "False"); this.cbSubType.Text = _Draw.GetElementValue(node, "Subtype", "Plain"); this.cbPalette.Text = _Draw.GetElementValue(node, "Palette", "Default"); this.cbRenderElement.Text = _Draw.GetElementValue(node, "ChartElementOutput", "Output"); this.tbPercentWidth.Text = _Draw.GetElementValue(node, "PointWidth", "0"); this.tbNoRows.Text = _Draw.GetElementValue(node, "NoRows", ""); // Handle the dataset for this dataregion object[] dsNames = _Draw.DataSetNames; string defName=""; if (dsNames != null && dsNames.Length > 0) { this.cbDataSet.Items.AddRange(_Draw.DataSetNames); defName = (string) dsNames[0]; } cbDataSet.Text = _Draw.GetDataSetNameValue(node); if (_Draw.GetReportItemDataRegionContainer(node) != null) cbDataSet.Enabled = false; // page breaks this.chkPageBreakStart.Checked = _Draw.GetElementValue(node, "PageBreakAtStart", "false").ToLower() == "true"? true: false; this.chkPageBreakEnd.Checked = _Draw.GetElementValue(node, "PageBreakAtEnd", "false").ToLower() == "true"? true: false; // Chart data-- this is a simplification of what is possible (TODO) string cdata=string.Empty; string cdata2 = string.Empty; string cdata3 = string.Empty; // <ChartData> // <ChartSeries> // <DataPoints> // <DataPoint> //<DataValues> // <DataValue> // <Value>=Sum(Fields!Sales.Value)</Value> // </DataValue> // <DataValue> // <Value>=Fields!Year.Value</Value> ----- only scatter and bubble // </DataValue> // <DataValue> // <Value>=Sum(Fields!Sales.Value)</Value> ----- only bubble // </DataValue> // </DataValues> // <DataLabel> // <Style> // <Format>c</Format> // </Style> // </DataLabel> // <Marker /> // </DataPoint> // </DataPoints> // </ChartSeries> // </ChartData> //Determine if we have a static series or not... We are not allowing this to be changed here. That decision is taken when creating the chart. 05122007GJL XmlNode ss = DesignXmlDraw.FindNextInHierarchy(node, "SeriesGroupings", "SeriesGrouping", "StaticSeries"); bool StaticSeries = ss != null; XmlNode dvs = DesignXmlDraw.FindNextInHierarchy(node, "ChartData", "ChartSeries", "DataPoints", "DataPoint", "DataValues"); int iter = 0; XmlNode cnode; foreach (XmlNode dv in dvs.ChildNodes) { if (dv.Name != "DataValue") continue; iter++; cnode = DesignXmlDraw.FindNextInHierarchy(dv, "Value"); if (cnode == null) continue; switch (iter) { case 1: cdata = cnode.InnerText; break; case 2: cdata2 = cnode.InnerText; break; case 3: cdata3 = cnode.InnerText; break; default: break; } } this.cbChartData.Text = cdata; this.cbChartData2.Text = cdata2; this.cbChartData3.Text = cdata3; //If the chart doesn't have a static series then dont show the datalabel values. 05122007GJL if (!StaticSeries) { //GJL 131107 Added data labels XmlNode labelExprNode = DesignXmlDraw.FindNextInHierarchy(node, "ChartData", "ChartSeries", "DataPoints", "DataPoint", "DataLabel", "Value"); if (labelExprNode != null) this.cbDataLabel.Text = labelExprNode.InnerText; XmlNode labelVisNode = DesignXmlDraw.FindNextInHierarchy(node, "ChartData", "ChartSeries", "DataPoints", "DataPoint", "DataLabel", "Visible"); if (labelVisNode != null) this.chkDataLabel.Checked = labelVisNode.InnerText.ToUpper().Equals("TRUE"); } chkDataLabel.Enabled = bDataLabelExpr.Enabled = cbDataLabel.Enabled = bDataExpr.Enabled = cbChartData.Enabled = !StaticSeries; // Don't allow the datalabel OR datavalues to be changed here if we have a static series GJL fChartType = fSubtype = fPalette = fRenderElement = fPercentWidth = fNoRows = fDataSet = fPageBreakStart = fPageBreakEnd = fChartData = false; } /// <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 Component 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.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.cbChartType = new System.Windows.Forms.ComboBox(); this.cbSubType = new System.Windows.Forms.ComboBox(); this.cbPalette = new System.Windows.Forms.ComboBox(); this.cbRenderElement = new System.Windows.Forms.ComboBox(); this.label5 = new System.Windows.Forms.Label(); this.tbPercentWidth = new System.Windows.Forms.NumericUpDown(); this.label6 = new System.Windows.Forms.Label(); this.tbNoRows = new System.Windows.Forms.TextBox(); this.label7 = new System.Windows.Forms.Label(); this.cbDataSet = new System.Windows.Forms.ComboBox(); this.chkPageBreakStart = new System.Windows.Forms.CheckBox(); this.chkPageBreakEnd = new System.Windows.Forms.CheckBox(); this.cbChartData = new System.Windows.Forms.ComboBox(); this.cbDataLabel = new System.Windows.Forms.ComboBox(); this.chkDataLabel = new System.Windows.Forms.CheckBox(); this.bDataLabelExpr = new System.Windows.Forms.Button(); this.lData1 = new System.Windows.Forms.Label(); this.cbChartData2 = new System.Windows.Forms.ComboBox(); this.lData2 = new System.Windows.Forms.Label(); this.cbChartData3 = new System.Windows.Forms.ComboBox(); this.lData3 = new System.Windows.Forms.Label(); this.bDataExpr = new System.Windows.Forms.Button(); this.bDataExpr3 = new System.Windows.Forms.Button(); this.bDataExpr2 = new System.Windows.Forms.Button(); this.cbVector = new System.Windows.Forms.ComboBox(); this.btnVectorExp = new System.Windows.Forms.Button(); this.label8 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.tbPercentWidth)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.Location = new System.Drawing.Point(16, 12); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(72, 16); this.label1.TabIndex = 0; this.label1.Text = "Chart Type"; // // label2 // this.label2.Location = new System.Drawing.Point(16, 37); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(72, 16); this.label2.TabIndex = 1; this.label2.Text = "Palette"; // // label3 // this.label3.Location = new System.Drawing.Point(16, 62); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(128, 16); this.label3.TabIndex = 2; this.label3.Text = "Render XML Element"; // // label4 // this.label4.Location = new System.Drawing.Point(16, 84); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(340, 19); this.label4.TabIndex = 3; this.label4.Text = "Percent width for Bars/Columns (>100% will cause overlap of columns)"; // // cbChartType // this.cbChartType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbChartType.Items.AddRange(new object[] { "Area", "Bar", "Column", "Doughnut", "Line", "Map", "Pie", "Bubble", "Scatter"}); this.cbChartType.Location = new System.Drawing.Point(126, 9); this.cbChartType.Name = "cbChartType"; this.cbChartType.Size = new System.Drawing.Size(121, 21); this.cbChartType.TabIndex = 0; this.cbChartType.SelectedIndexChanged += new System.EventHandler(this.cbChartType_SelectedIndexChanged); // // cbSubType // this.cbSubType.Location = new System.Drawing.Point(331, 9); this.cbSubType.Name = "cbSubType"; this.cbSubType.Size = new System.Drawing.Size(80, 21); this.cbSubType.TabIndex = 1; this.cbSubType.SelectedIndexChanged += new System.EventHandler(this.cbSubType_SelectedIndexChanged); this.cbSubType.TextUpdate += new System.EventHandler(this.cbSubType_SelectedIndexChanged); this.cbSubType.TextChanged += new System.EventHandler(this.cbSubType_SelectedIndexChanged); // // cbPalette // this.cbPalette.Items.AddRange(new object[] { "Default", "EarthTones", "Excel", "GrayScale", "Light", "Pastel", "SemiTransparent", "Patterned", "PatternedBlack"}); this.cbPalette.Location = new System.Drawing.Point(126, 34); this.cbPalette.Name = "cbPalette"; this.cbPalette.Size = new System.Drawing.Size(121, 21); this.cbPalette.TabIndex = 2; this.cbPalette.SelectedIndexChanged += new System.EventHandler(this.cbPalette_SelectedIndexChanged); // // cbRenderElement // this.cbRenderElement.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbRenderElement.Items.AddRange(new object[] { "Output", "NoOutput"}); this.cbRenderElement.Location = new System.Drawing.Point(126, 59); this.cbRenderElement.Name = "cbRenderElement"; this.cbRenderElement.Size = new System.Drawing.Size(121, 21); this.cbRenderElement.TabIndex = 3; this.cbRenderElement.SelectedIndexChanged += new System.EventHandler(this.cbRenderElement_SelectedIndexChanged); // // label5 // this.label5.Location = new System.Drawing.Point(275, 12); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(53, 23); this.label5.TabIndex = 8; this.label5.Text = "Sub-type"; // // tbPercentWidth // this.tbPercentWidth.Location = new System.Drawing.Point(363, 80); this.tbPercentWidth.Name = "tbPercentWidth"; this.tbPercentWidth.Size = new System.Drawing.Size(48, 20); this.tbPercentWidth.TabIndex = 4; this.tbPercentWidth.ValueChanged += new System.EventHandler(this.tbPercentWidth_ValueChanged); // // label6 // this.label6.Location = new System.Drawing.Point(16, 106); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(100, 23); this.label6.TabIndex = 10; this.label6.Text = "No Rows Message"; // // tbNoRows // this.tbNoRows.Location = new System.Drawing.Point(156, 106); this.tbNoRows.Name = "tbNoRows"; this.tbNoRows.Size = new System.Drawing.Size(255, 20); this.tbNoRows.TabIndex = 5; this.tbNoRows.TextChanged += new System.EventHandler(this.tbNoRows_TextChanged); // // label7 // this.label7.Location = new System.Drawing.Point(16, 135); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(100, 23); this.label7.TabIndex = 12; this.label7.Text = "Data Set Name"; // // cbDataSet // this.cbDataSet.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbDataSet.Location = new System.Drawing.Point(156, 133); this.cbDataSet.Name = "cbDataSet"; this.cbDataSet.Size = new System.Drawing.Size(255, 21); this.cbDataSet.TabIndex = 6; this.cbDataSet.SelectedIndexChanged += new System.EventHandler(this.cbDataSet_SelectedIndexChanged); // // chkPageBreakStart // this.chkPageBreakStart.Location = new System.Drawing.Point(20, 260); this.chkPageBreakStart.Name = "chkPageBreakStart"; this.chkPageBreakStart.Size = new System.Drawing.Size(136, 24); this.chkPageBreakStart.TabIndex = 13; this.chkPageBreakStart.Text = "Page Break at Start"; this.chkPageBreakStart.CheckedChanged += new System.EventHandler(this.chkPageBreakStart_CheckedChanged); // // chkPageBreakEnd // this.chkPageBreakEnd.Location = new System.Drawing.Point(280, 260); this.chkPageBreakEnd.Name = "chkPageBreakEnd"; this.chkPageBreakEnd.Size = new System.Drawing.Size(136, 24); this.chkPageBreakEnd.TabIndex = 14; this.chkPageBreakEnd.Text = "Page Break at End"; this.chkPageBreakEnd.CheckedChanged += new System.EventHandler(this.chkPageBreakEnd_CheckedChanged); // // cbChartData // this.cbChartData.Location = new System.Drawing.Point(156, 157); this.cbChartData.Name = "cbChartData"; this.cbChartData.Size = new System.Drawing.Size(255, 21); this.cbChartData.TabIndex = 7; this.cbChartData.TextChanged += new System.EventHandler(this.cbChartData_Changed); // // cbDataLabel // this.cbDataLabel.Enabled = false; this.cbDataLabel.Location = new System.Drawing.Point(156, 237); this.cbDataLabel.Name = "cbDataLabel"; this.cbDataLabel.Size = new System.Drawing.Size(254, 21); this.cbDataLabel.TabIndex = 17; this.cbDataLabel.TextChanged += new System.EventHandler(this.cbChartData_Changed); // // chkDataLabel // this.chkDataLabel.AutoSize = true; this.chkDataLabel.Location = new System.Drawing.Point(20, 240); this.chkDataLabel.Name = "chkDataLabel"; this.chkDataLabel.Size = new System.Drawing.Size(75, 17); this.chkDataLabel.TabIndex = 19; this.chkDataLabel.Text = "DataLabel"; this.chkDataLabel.UseVisualStyleBackColor = true; this.chkDataLabel.CheckedChanged += new System.EventHandler(this.chkDataLabel_CheckedChanged); // // bDataLabelExpr // this.bDataLabelExpr.Enabled = false; this.bDataLabelExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic)))); this.bDataLabelExpr.Location = new System.Drawing.Point(415, 237); this.bDataLabelExpr.Name = "bDataLabelExpr"; this.bDataLabelExpr.Size = new System.Drawing.Size(22, 21); this.bDataLabelExpr.TabIndex = 20; this.bDataLabelExpr.Text = "fx"; this.bDataLabelExpr.UseVisualStyleBackColor = true; this.bDataLabelExpr.Click += new System.EventHandler(this.bDataLabelExpr_Click); // // lData1 // this.lData1.Location = new System.Drawing.Point(16, 157); this.lData1.Name = "lData1"; this.lData1.Size = new System.Drawing.Size(137, 23); this.lData1.TabIndex = 16; this.lData1.Text = "Chart Data (X Coordinate)"; // // cbChartData2 // this.cbChartData2.Location = new System.Drawing.Point(156, 182); this.cbChartData2.Name = "cbChartData2"; this.cbChartData2.Size = new System.Drawing.Size(255, 21); this.cbChartData2.TabIndex = 9; this.cbChartData2.TextChanged += new System.EventHandler(this.cbChartData_Changed); // // lData2 // this.lData2.Location = new System.Drawing.Point(16, 182); this.lData2.Name = "lData2"; this.lData2.Size = new System.Drawing.Size(100, 23); this.lData2.TabIndex = 18; this.lData2.Text = "Y Coordinate"; // // cbChartData3 // this.cbChartData3.Location = new System.Drawing.Point(156, 207); this.cbChartData3.Name = "cbChartData3"; this.cbChartData3.Size = new System.Drawing.Size(255, 21); this.cbChartData3.TabIndex = 11; this.cbChartData3.TextChanged += new System.EventHandler(this.cbChartData_Changed); // // lData3 // this.lData3.Location = new System.Drawing.Point(16, 207); this.lData3.Name = "lData3"; this.lData3.Size = new System.Drawing.Size(100, 23); this.lData3.TabIndex = 20; this.lData3.Text = "Bubble Size"; // // bDataExpr // this.bDataExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bDataExpr.Location = new System.Drawing.Point(415, 157); this.bDataExpr.Name = "bDataExpr"; this.bDataExpr.Size = new System.Drawing.Size(22, 21); this.bDataExpr.TabIndex = 8; this.bDataExpr.Tag = "d1"; this.bDataExpr.Text = "fx"; this.bDataExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bDataExpr.Click += new System.EventHandler(this.bDataExpr_Click); // // bDataExpr3 // this.bDataExpr3.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bDataExpr3.Location = new System.Drawing.Point(415, 207); this.bDataExpr3.Name = "bDataExpr3"; this.bDataExpr3.Size = new System.Drawing.Size(22, 21); this.bDataExpr3.TabIndex = 12; this.bDataExpr3.Tag = "d3"; this.bDataExpr3.Text = "fx"; this.bDataExpr3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bDataExpr3.Click += new System.EventHandler(this.bDataExpr_Click); // // bDataExpr2 // this.bDataExpr2.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bDataExpr2.Location = new System.Drawing.Point(415, 182); this.bDataExpr2.Name = "bDataExpr2"; this.bDataExpr2.Size = new System.Drawing.Size(22, 21); this.bDataExpr2.TabIndex = 10; this.bDataExpr2.Tag = "d2"; this.bDataExpr2.Text = "fx"; this.bDataExpr2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bDataExpr2.Click += new System.EventHandler(this.bDataExpr_Click); // // cbVector // this.cbVector.Items.AddRange(new object[] { "False", "True"}); this.cbVector.Location = new System.Drawing.Point(330, 36); this.cbVector.Name = "cbVector"; this.cbVector.Size = new System.Drawing.Size(80, 21); this.cbVector.TabIndex = 21; this.cbVector.SelectedIndexChanged += new System.EventHandler(this.cbVector_SelectedIndexChanged); // // btnVectorExp // this.btnVectorExp.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnVectorExp.Location = new System.Drawing.Point(415, 36); this.btnVectorExp.Name = "btnVectorExp"; this.btnVectorExp.Size = new System.Drawing.Size(22, 21); this.btnVectorExp.TabIndex = 22; this.btnVectorExp.Tag = "d4"; this.btnVectorExp.Text = "fx"; this.btnVectorExp.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnVectorExp.Click += new System.EventHandler(this.bDataExpr_Click); // // label8 // this.label8.Location = new System.Drawing.Point(275, 32); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(53, 27); this.label8.TabIndex = 23; this.label8.Text = "Render As Vector"; // // button1 // this.button1.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button1.Location = new System.Drawing.Point(415, 9); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(22, 21); this.button1.TabIndex = 24; this.button1.Tag = "d7"; this.button1.Text = "fx"; this.button1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button1.Click += new System.EventHandler(this.bDataExpr_Click); // // button2 // this.button2.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button2.Location = new System.Drawing.Point(251, 9); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(22, 21); this.button2.TabIndex = 25; this.button2.Tag = "d5"; this.button2.Text = "fx"; this.button2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button2.Visible = false; this.button2.Click += new System.EventHandler(this.bDataExpr_Click); // // button3 // this.button3.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button3.Location = new System.Drawing.Point(251, 32); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(22, 21); this.button3.TabIndex = 26; this.button3.Tag = "d6"; this.button3.Text = "fx"; this.button3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button3.Click += new System.EventHandler(this.bDataExpr_Click); // // ChartCtl // this.Controls.Add(this.button3); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.label8); this.Controls.Add(this.btnVectorExp); this.Controls.Add(this.cbVector); this.Controls.Add(this.bDataExpr2); this.Controls.Add(this.bDataExpr3); this.Controls.Add(this.bDataExpr); this.Controls.Add(this.cbChartData3); this.Controls.Add(this.lData3); this.Controls.Add(this.cbChartData2); this.Controls.Add(this.lData2); this.Controls.Add(this.bDataLabelExpr); this.Controls.Add(this.chkDataLabel); this.Controls.Add(this.cbDataLabel); this.Controls.Add(this.cbChartData); this.Controls.Add(this.lData1); this.Controls.Add(this.chkPageBreakEnd); this.Controls.Add(this.chkPageBreakStart); this.Controls.Add(this.cbDataSet); this.Controls.Add(this.label7); this.Controls.Add(this.tbNoRows); this.Controls.Add(this.label6); this.Controls.Add(this.tbPercentWidth); this.Controls.Add(this.label5); this.Controls.Add(this.cbRenderElement); this.Controls.Add(this.cbPalette); this.Controls.Add(this.cbSubType); this.Controls.Add(this.cbChartType); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Name = "ChartCtl"; this.Size = new System.Drawing.Size(440, 288); ((System.ComponentModel.ISupportInitialize)(this.tbPercentWidth)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion public bool IsValid() { return true; } public void Apply() { // take information in control and apply to all the style nodes // Only change information that has been marked as modified; // this way when group is selected it is possible to change just // the items you want and keep the rest the same. foreach (XmlNode riNode in this._ReportItems) ApplyChanges(riNode); // No more changes //AJM GJL 14082008 fChartType = fVector = fSubtype = fPalette = fRenderElement = fPercentWidth = fNoRows = fDataSet = fPageBreakStart = fPageBreakEnd = fChartData = false; } public void ApplyChanges(XmlNode node) { if (fChartType) { _Draw.SetElement(node, "Type", this.cbChartType.Text); } if (fVector) //AJM GJL 14082008 { _Draw.SetElement(node, "fyi:RenderAsVector", this.cbVector.Text); } if (fSubtype) { _Draw.SetElement(node, "Subtype", this.cbSubType.Text); } if (fPalette) { _Draw.SetElement(node, "Palette", this.cbPalette.Text); } if (fRenderElement) { _Draw.SetElement(node, "ChartElementOutput", this.cbRenderElement.Text); } if (fPercentWidth) { _Draw.SetElement(node, "PointWidth", this.tbPercentWidth.Text); } if (fNoRows) { _Draw.SetElement(node, "NoRows", this.tbNoRows.Text); } if (fDataSet) { _Draw.SetElement(node, "DataSetName", this.cbDataSet.Text); } if (fPageBreakStart) { _Draw.SetElement(node, "PageBreakAtStart", this.chkPageBreakStart.Checked? "true": "false"); } if (fPageBreakEnd) { _Draw.SetElement(node, "PageBreakAtEnd", this.chkPageBreakEnd.Checked? "true": "false"); } if (fChartData) { // <ChartData> // <ChartSeries> // <DataPoints> // <DataPoint> // <DataValues> // <DataValue> // <Value>=Sum(Fields!Sales.Value)</Value> // </DataValue> --- you can have up to 3 DataValue elements // </DataValues> // <DataLabel> // <Style> // <Format>c</Format> // </Style> // </DataLabel> // <Marker /> // </DataPoint> // </DataPoints> // </ChartSeries> // </ChartData> XmlNode chartdata = _Draw.SetElement(node, "ChartData", null); XmlNode chartseries = _Draw.SetElement(chartdata, "ChartSeries", null); XmlNode datapoints = _Draw.SetElement(chartseries, "DataPoints", null); XmlNode datapoint = _Draw.SetElement(datapoints, "DataPoint", null); XmlNode datavalues = _Draw.SetElement(datapoint, "DataValues", null); _Draw.RemoveElementAll(datavalues, "DataValue"); XmlNode datalabel = _Draw.SetElement(datapoint, "DataLabel", null); XmlNode datavalue = _Draw.SetElement(datavalues, "DataValue", null); _Draw.SetElement(datavalue, "Value", this.cbChartData.Text); string type = cbChartType.Text.ToLowerInvariant(); if (type == "scatter" || type == "bubble") { datavalue = _Draw.CreateElement(datavalues, "DataValue", null); _Draw.SetElement(datavalue, "Value", this.cbChartData2.Text); if (type == "bubble") { datavalue = _Draw.CreateElement(datavalues, "DataValue", null); _Draw.SetElement(datavalue, "Value", this.cbChartData3.Text); } } _Draw.SetElement(datalabel, "Value", this.cbDataLabel.Text); _Draw.SetElement(datalabel, "Visible", this.chkDataLabel.Checked.ToString()); } } private void cbChartType_SelectedIndexChanged(object sender, System.EventArgs e) { fChartType = true; // Change the potential sub-types string savesub = cbSubType.Text; string[] subItems = new string [] {"Plain"}; bool bEnableY = false; bool bEnableBubble = false; switch (cbChartType.Text) { case "Column": subItems = new string [] {"Plain", "Stacked", "PercentStacked"}; break; case "Bar": subItems = new string [] {"Plain", "Stacked", "PercentStacked"}; break; case "Line": subItems = new string [] {"Plain", "Smooth"}; break; case "Pie": subItems = new string [] {"Plain", "Exploded"}; break; case "Area": subItems = new string [] {"Plain", "Stacked"}; break; case "Doughnut": break; case "Map": subItems = RdlDesigner.MapSubtypes; break; case "Scatter": subItems = new string [] {"Plain", "Line", "SmoothLine"}; bEnableY = true; break; case "Stock": break; case "Bubble": bEnableY = bEnableBubble = true; break; default: break; } cbSubType.Items.Clear(); cbSubType.Items.AddRange(subItems); lData2.Enabled = cbChartData2.Enabled = bDataExpr2.Enabled = bEnableY; lData3.Enabled = cbChartData3.Enabled = bDataExpr3.Enabled = bEnableBubble; int i=0; foreach (string s in subItems) { if (s == savesub) { cbSubType.SelectedIndex = i; return; } i++; } // Didn't match old style cbSubType.SelectedIndex = 0; } //AJM GJL 14082008 private void cbVector_SelectedIndexChanged(object sender, EventArgs e) { fVector = true; } private void cbSubType_SelectedIndexChanged(object sender, System.EventArgs e) { fSubtype = true; } private void cbPalette_SelectedIndexChanged(object sender, System.EventArgs e) { fPalette = true; } private void cbRenderElement_SelectedIndexChanged(object sender, System.EventArgs e) { fRenderElement = true; } private void tbPercentWidth_ValueChanged(object sender, System.EventArgs e) { fPercentWidth = true; } private void tbNoRows_TextChanged(object sender, System.EventArgs e) { fNoRows = true; } private void cbDataSet_SelectedIndexChanged(object sender, System.EventArgs e) { fDataSet = true; } private void chkPageBreakStart_CheckedChanged(object sender, System.EventArgs e) { fPageBreakStart = true; } private void chkPageBreakEnd_CheckedChanged(object sender, System.EventArgs e) { fPageBreakEnd = true; } private void cbChartData_Changed(object sender, System.EventArgs e) { fChartData = true; } private void bDataExpr_Click(object sender, System.EventArgs e) { Button bs = sender as Button; if (bs == null) return; Control ctl = null; switch (bs.Tag as string) { case "d1": ctl = cbChartData; break; case "d2": ctl = cbChartData2; break; case "d3": ctl = cbChartData3; break; //AJM GJL 14082008 case "d4": ctl = cbVector; fVector = true; break; case "d5": ctl = cbChartType; fChartType = true; break; case "d6": ctl = cbPalette; fPalette = true; break; case "d7": ctl = cbSubType; fSubtype = true; break; default: return; } DialogExprEditor ee = new DialogExprEditor(_Draw, ctl.Text, _ReportItems[0], false); try { DialogResult dlgr = ee.ShowDialog(); if (dlgr == DialogResult.OK) { ctl.Text = ee.Expression; fChartData = true; } } finally { ee.Dispose(); } } private void chkDataLabel_CheckedChanged(object sender, EventArgs e) { cbDataLabel.Enabled = bDataLabelExpr.Enabled = chkDataLabel.Checked; } private void bDataLabelExpr_Click(object sender, EventArgs e) { DialogExprEditor ee = new DialogExprEditor(_Draw, cbDataLabel.Text,_ReportItems[0] , false); try { if (ee.ShowDialog() == DialogResult.OK) { cbDataLabel.Text = ee.Expression; } } finally { ee.Dispose(); } return; } } }
using System; using System.Collections.Generic; using CellStore.Excel.Client; using CellStore.Excel.Tools; using System.Text; namespace CellStore.Excel.Tasks { public class ListFactsTask { CellStore.Api.DataApi api; string basePath_casted; string token_casted; string eid_casted; string ticker_casted; string tag_casted; string aid_casted; string fiscalYear_casted; string concept_casted; string fiscalPeriod_casted; string fiscalPeriodType_casted; string report_casted; string additionalRules_casted; bool open_casted; string aggregationFunction_casted; string profileName_casted; Dictionary<string, string> dimensions_casted; Dictionary<string, string> dimensionDefaults_casted; Dictionary<string, string> dimensionTypes_casted; /*Dictionary<string, bool?> dimensionSlicers_casted;*/ Dictionary<string, string> dimensionAggregation_casted; bool count_casted; int? top_casted; //int? skip_casted; bool debugInfo_casted; public ListFactsTask( Object basePath, Object token, Parameters parameters, Object debugInfo ) { basePath_casted = Utils.castParamString(basePath, "basePath", false, "http://secxbrl.28.io/v1/_queries/public"); api = ApiClients.getDataApiClient(basePath_casted); token_casted = Utils.castParamString(token, "token", true); eid_casted = Utils.castParamString(parameters.getParamValue("eid"), "eid", false); ticker_casted = Utils.castParamString(parameters.getParamValue("ticker"), "ticker", false); tag_casted = Utils.castParamString(parameters.getParamValue("tag"), "tag", false); aid_casted = Utils.castParamString(parameters.getParamValue("aid"), "aid", false); fiscalYear_casted = Utils.castParamString(parameters.getParamValue("fiscalYear"), "fiscalYear", false); concept_casted = Utils.castParamString(parameters.getParamValue("concept"), "concept", false); fiscalPeriod_casted = Utils.castParamString(parameters.getParamValue("fiscalPeriod"), "fiscalPeriod", false); fiscalPeriodType_casted = Utils.castParamString(parameters.getParamValue("fiscalPeriodType"), "fiscalPeriodType", false); report_casted = Utils.castParamString(parameters.getParamValue("report"), "report", false); additionalRules_casted = Utils.castParamString(parameters.getParamValue("additionalRules"), "additionalRules", false); open_casted = Utils.castParamBool(parameters.getParamValue("open"), "open", false); aggregationFunction_casted = Utils.castParamString(parameters.getParamValue("aggregation-function"), "aggregationFunction", false); profileName_casted = Utils.castParamString(parameters.getParamValue("profile-name"), "profileName", false); dimensions_casted = parameters.getDimensionsValues(); dimensionDefaults_casted = parameters.getDimensionDefaultsValues(); dimensionTypes_casted = parameters.getDimensionTypesValues(); dimensionAggregation_casted = parameters.getDimensionAggregationsValues(); count_casted = Utils.castParamBool(parameters.getParamValue("count"), "count", false); top_casted = Utils.castParamInt(parameters.getParamValue("top"), "top", 100); //skip_casted = Utils.castParamInt(skip, "skip", 0); debugInfo_casted = Utils.castParamBool(debugInfo, "debugInfo", false); if (!(Utils.hasEntityFilter(eid_casted, ticker_casted, tag_casted, dimensions_casted) && Utils.hasConceptFilter(concept_casted, dimensions_casted) && Utils.hasAdditionalFilter(fiscalYear_casted, fiscalPeriod_casted, dimensions_casted))) { throw new Exception("Too generic filter."); } //Utils.log("Created Task " + ToString()); } private void appendRequest(ref StringBuilder sb, String key, String value, bool last = false) { if (value != null) { sb.Append(key); sb.Append("="); sb.Append(value); if (!last) sb.Append("&"); } } private void appendRequest(ref StringBuilder sb, Dictionary<string, string> dict) { foreach (KeyValuePair<string, string> entry in dict) { appendRequest(ref sb, entry.Key, entry.Value); } } public string request() { StringBuilder sb = new StringBuilder(); sb.Append(basePath_casted + "/api/facts?"); appendRequest(ref sb, "eid", eid_casted); appendRequest(ref sb, "ticker", ticker_casted); appendRequest(ref sb, "tag", tag_casted); appendRequest(ref sb, "aid", aid_casted); appendRequest(ref sb, "fiscalYear", fiscalYear_casted); appendRequest(ref sb, "concept", concept_casted); appendRequest(ref sb, "fiscalPeriod", fiscalPeriod_casted); appendRequest(ref sb, "report", report_casted); appendRequest(ref sb, "additional-rules", additionalRules_casted); appendRequest(ref sb, "open", open_casted ? "true" : "false" ); appendRequest(ref sb, "aggregation-function", aggregationFunction_casted); appendRequest(ref sb, "profile-name", profileName_casted); appendRequest(ref sb, "fiscalPeriodType", fiscalPeriodType_casted); appendRequest(ref sb, "count", count_casted ? "true" : "false" ); appendRequest(ref sb, "top", Convert.ToString(top_casted)); appendRequest(ref sb, dimensions_casted); appendRequest(ref sb, dimensionDefaults_casted); appendRequest(ref sb, dimensionTypes_casted); appendRequest(ref sb, dimensionAggregation_casted); //append(ref sb, "skip", Convert.ToString(skip_casted)); appendRequest(ref sb, "token", token_casted, true); return sb.ToString(); } private void append(ref StringBuilder sb, String key, String value, bool last = false) { if (value != null) { sb.Append(key); sb.Append("="); sb.Append(value); if (!last) sb.Append(" | "); } } private void append(ref StringBuilder sb, Dictionary<string, string> dict, string prefix) { sb.Append(prefix); foreach (KeyValuePair<string, string> entry in dict) { append(ref sb, entry.Key, entry.Value); } } public string id() { StringBuilder sb = new StringBuilder(); append(ref sb, "basePath", basePath_casted); //append(ref sb, "token", token_casted); append(ref sb, "eid", eid_casted); append(ref sb, "ticker", ticker_casted); append(ref sb, "tag", tag_casted); append(ref sb, "aid", aid_casted); append(ref sb, "fiscalYear", fiscalYear_casted); append(ref sb, "concept", concept_casted); append(ref sb, "fiscalPeriod", fiscalPeriod_casted); append(ref sb, "report", report_casted); append(ref sb, "additionalRules", additionalRules_casted); append(ref sb, "open", Convert.ToString(open_casted)); append(ref sb, "aggregationFunction", aggregationFunction_casted); append(ref sb, "profileName", profileName_casted); append(ref sb, "fiscalPeriodType", fiscalPeriodType_casted); append(ref sb, "count", Convert.ToString(count_casted)); append(ref sb, "top", Convert.ToString(top_casted)); append(ref sb, dimensions_casted, "[Dimensions:] "); append(ref sb, dimensionDefaults_casted, "[Defaults:] "); append(ref sb, dimensionTypes_casted, "[Types:] "); append(ref sb, dimensionAggregation_casted,"[Aggregations:] "); //append(ref sb, "skip", Convert.ToString(skip_casted)); return sb.ToString(); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("ListFactsTask: "); sb.Append(id()); return sb.ToString(); } public Object run() { dynamic response = api.ListFacts( token: token_casted, eid: eid_casted, ticker: ticker_casted, tag: tag_casted, aid: aid_casted, fiscalYear: fiscalYear_casted, concept: concept_casted, fiscalPeriod: fiscalPeriod_casted, fiscalPeriodType: fiscalPeriodType_casted, report: report_casted, additionalRules: additionalRules_casted, open: open_casted, aggregationFunction: aggregationFunction_casted, profileName: profileName_casted, dimensions: dimensions_casted, defaultDimensionValues: dimensionDefaults_casted, dimensionTypes: dimensionTypes_casted, dimensionAggregation: dimensionAggregation_casted, count: count_casted, top: top_casted); //skip: skip_casted); Object result = Utils.getFactTableResult(response, debugInfo_casted); Utils.log("Received '" + string.Join(", ", (Object[])result) + "' as response for " + ToString()); return result; } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; public class Player : MonoBehaviour { public const float RIGHT = 1.0f; public const float LEFT = -1.0f; public const float UP = 1.0f; public const float DOWN = -1.0f; public float speed = 36.0f; private float maxSpeed = 36.0f; public float speedSliding = 20.0f; private float maxSpeedSliding = 20.0f; public float jumpSpeed = 19.0f; private float jumpDownSpeed = 8.0f; private float doubleJumpSpeed = 15.0f; private float doubleJumpDownSpeed = 4.0f; public float gravity = 27.0f; public float direction = RIGHT; private int collectedCoins = 0; private bool isDead = false; private bool finishedLevel; public Vector3 playerSpeed = new Vector3(0.0f, 0.0f, 0.0f); private int jumpCounter = 0; public bool isGrounded = false; public bool isOnWallUp = false; public bool isOnWallDown = false; public bool isSliding = false; public float rayDistance; public float lastJumpTime; public Vector3 impact = Vector3.zero; private SceneManager sceneManager; private CharacterController controller; private PlayerFSM fsm; private InputManager inputManager; private Zone01Attributes zone01; void Start () { sceneManager = GameObject.Find("SceneManager").GetComponent<SceneManager>(); controller = GetComponent<CharacterController>(); fsm = GetComponent<PlayerFSM>(); zone01 = sceneManager.getLevelsAttributes().getZone01(); rayDistance = controller.height * .7f + controller.radius; } void Update () { Vector3 velocity = transform.forward * direction * speed; isGrounded = checkGroundCollision(); checkForwardCollision(); changeState(); applyPhysics(ref velocity); CollisionFlags collisionFlags = movePlayer(velocity); if ( (collisionFlags & CollisionFlags.CollidedAbove) != 0 ) { if (playerSpeed.y > 0) { playerSpeed.y = -playerSpeed.y; } } if (transform.position.x != 0) { Vector3 newPosition = transform.position; newPosition.x = 0; transform.position = newPosition; } checkIsDead(); } void changeState() { checkSlidingState(); if(inputManager.getKeyDown(PlayerKeys.JUMP)) { if(isGrounded) { if(fsm.validateNewAction(PlayerActions.JUMP_INPUT)) { jump(jumpSpeed, UP); } } else if(isOnWallUp || isOnWallDown) { if(fsm.validateNewAction(PlayerActions.JUMP_INPUT)) { float jumpDirection = isOnWallUp ? UP : DOWN ; float jumpSpeedWall = isOnWallUp ? jumpSpeed : jumpDownSpeed ; direction = (direction == RIGHT) ? LEFT : RIGHT; jump(jumpSpeedWall, jumpDirection); } } else { doubleJump(); } } else if (isOnWallUp && !isGrounded) { fsm.validateNewAction(PlayerActions.WALL_SLIDE); } else if (!isGrounded) { fsm.validateNewAction(PlayerActions.FALL); } else if (isGrounded) { fsm.validateNewAction(PlayerActions.RUN); } } void OnControllerColliderHit(ControllerColliderHit hit) { String colliderName = hit.collider.name; if (colliderName.Equals(zone01.BAD_TREE)) { zone01.actBadTree(ref isDead); } if (colliderName.Equals(zone01.CHUZOS)) { zone01.actChuzos(ref isDead); } if (colliderName.Equals(zone01.INCLINATE)) { zone01.actInclinate(ref isSliding); } if (colliderName.Contains(zone01.DIRECTION_CHANGER) ) { if ( colliderName.Substring(zone01.DIRECTION_CHANGER.Length).Equals(zone01.LEFT) ) { direction = (direction == RIGHT) ? LEFT : RIGHT; } if ( colliderName.Substring(zone01.DIRECTION_CHANGER.Length).Equals(zone01.RIGHT) ) { direction = (direction == LEFT) ? RIGHT : LEFT; } } } private bool checkGroundCollision() { RaycastHit hitInfo; Debug.DrawRay(transform.position, -transform.up, Color.red); bool isOnGround = false; if( Physics.Raycast(transform.position, -transform.up , out hitInfo, rayDistance) ) { string colliderName = hitInfo.collider.name; if ( colliderName.Equals(zone01.INCLINATE) || colliderName.Equals("Cube") ) { Vector3 axis = Vector3.Cross(-transform.up, -hitInfo.normal); float angle = 0.0f; if(axis != Vector3.zero) { angle = Mathf.Atan2(Vector3.Magnitude(axis), Vector3.Dot(-transform.up, -hitInfo.normal)); transform.RotateAround(axis, angle); } } isOnGround = colliderName.Equals(zone01.WALL_UP) ? false : true; isOnGround = colliderName.Equals(zone01.WALL_DOWN) ? false : true; } isSliding = isOnGround ? isSliding : false; return isOnGround; } private void checkForwardCollision() { RaycastHit hitInfo; Debug.DrawRay(transform.position, transform.forward * direction, Color.green); isOnWallUp = false; isOnWallDown = false; if(Physics.Raycast(transform.position, transform.forward * direction , out hitInfo, rayDistance) ) { String colliderName = hitInfo.collider.name; if ( colliderName.Equals(zone01.WALL_UP) || colliderName.Equals(zone01.WALL_DOWN) ) { Vector3 axis = Vector3.Cross(direction*transform.forward, -hitInfo.normal); float angle = 0.0f; if(axis != Vector3.zero) { angle = Mathf.Atan2(Vector3.Magnitude(axis), Vector3.Dot(direction*transform.forward, -hitInfo.normal)); transform.RotateAround(axis, angle); } isOnWallUp = colliderName.Equals(zone01.WALL_UP) ? true : false; isOnWallDown = colliderName.Equals(zone01.WALL_DOWN) ? true : false; jumpCounter = 0; } } } private void jump(float jumpTempSpeed, float direction) { playerSpeed.y = jumpTempSpeed*direction; isSliding = false; jumpCounter += 1; lastJumpTime = Time.time; } private bool doubleJump() { if ( jumpCounter > 0 && Time.time > lastJumpTime + 0.25f ) { playerSpeed.y += doubleJumpSpeed; lastJumpTime = Time.time; jumpCounter = 0; return true; } return false; } private void applyPhysics(ref Vector3 velocity) { if (!isSliding) { playerSpeed.y -= gravity * Time.deltaTime; velocity.y = playerSpeed.y; } } private CollisionFlags movePlayer(Vector3 velocity) { CollisionFlags collisionFlags = CollisionFlags.None; if (impact.sqrMagnitude > 0.2f) { impact.y -= gravity * Time.deltaTime; collisionFlags = controller.Move(impact * Time.deltaTime); impact = Vector3.Lerp(impact, Vector3.zero, 5*Time.deltaTime); speed = 0.0f; } else { collisionFlags = controller.Move(velocity * Time.deltaTime); speed = Mathf.Lerp(speed, maxSpeed, 2*Time.deltaTime); speedSliding = Mathf.Lerp(speedSliding, maxSpeedSliding, 2*Time.deltaTime); } playerSpeed.z = velocity.z; return collisionFlags; } private void checkSlidingState() { if (isSliding || controller.isGrounded) { impact.y = 0.0f; playerSpeed.y = 0.0f; } } private void checkIsDead() { if( isDead ) { sceneManager.restartLevel(); } if( finishedLevel ) { sceneManager.advanceLevel(); } } public void initializeInputManager(string id, List<KeyCode> keys) { switch ( id ) { case "Android": { inputManager = GetComponent<ControllerAndroid>(); GetComponent<ControllerAndroid>().enabled = true; break; } default: { inputManager = GetComponent<InputManager>(); break; } } inputManager.setController(id); inputManager.setKeys(keys); } #if UNITY_ANDROID public void initializeButtonsAndroid(List<Button> buttons) { inputManager.addButtons(buttons); } #endif public bool isPlayerDead() { return isDead; } public PlayerFSM getFSM() { return fsm; } public void addCoins(int number = 1) { collectedCoins += number; } public int getCollectedCoins() { return collectedCoins; } public void setFinishedLevel(bool finished = true) { finishedLevel = finished; } }
// // Copyright (c) 2004-2018 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. // #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD namespace NLog.LayoutRenderers { using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Text; using Microsoft.Win32; using NLog.Common; using NLog.Internal; using NLog.Config; using NLog.Layouts; /// <summary> /// A value from the Registry. /// </summary> [LayoutRenderer("registry")] public class RegistryLayoutRenderer : LayoutRenderer { /// <summary> /// Create new renderer /// </summary> public RegistryLayoutRenderer() { RequireEscapingSlashesInDefaultValue = true; } /// <summary> /// Gets or sets the registry value name. /// </summary> /// <docgen category='Registry Options' order='10' /> public Layout Value { get; set; } /// <summary> /// Gets or sets the value to be output when the specified registry key or value is not found. /// </summary> /// <docgen category='Registry Options' order='10' /> public Layout DefaultValue { get; set; } /// <summary> /// Require escaping backward slashes in <see cref="DefaultValue"/>. Need to be backwardscompatible. /// /// When true: /// /// `\` in value should be configured as `\\` /// `\\` in value should be configured as `\\\\`. /// </summary> /// <remarks>Default value wasn't a Layout before and needed an escape of the slash</remarks> /// <docgen category='Registry Options' order='50' /> [DefaultValue(true)] public bool RequireEscapingSlashesInDefaultValue { get; set; } #if !NET3_5 /// <summary> /// Gets or sets the registry view (see: https://msdn.microsoft.com/de-de/library/microsoft.win32.registryview.aspx). /// Allowed values: Registry32, Registry64, Default /// </summary> /// <docgen category='Registry Options' order='10' /> [DefaultValue("Default")] public RegistryView View { get; set; } #endif /// <summary> /// Gets or sets the registry key. /// </summary> /// <example> /// HKCU\Software\NLogTest /// </example> /// <remarks> /// Possible keys: /// <ul> ///<li>HKEY_LOCAL_MACHINE</li> ///<li>HKLM</li> ///<li>HKEY_CURRENT_USER</li> ///<li>HKCU</li> ///<li>HKEY_CLASSES_ROOT</li> ///<li>HKEY_USERS</li> ///<li>HKEY_CURRENT_CONFIG</li> ///<li>HKEY_DYN_DATA</li> ///<li>HKEY_PERFORMANCE_DATA</li> /// </ul> /// </remarks> /// <docgen category='Registry Options' order='10' /> [RequiredParameter] public Layout Key { get; set; } /// <summary> /// Reads the specified registry key and value and appends it to /// the passed <see cref="StringBuilder"/>. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event. Ignored.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { object registryValue = null; // Value = null is necessary for querying "unnamed values" string renderedValue = Value?.Render(logEvent); var parseResult = ParseKey(Key.Render(logEvent)); try { #if !NET3_5 using (RegistryKey rootKey = RegistryKey.OpenBaseKey(parseResult.Hive, View)) #else var rootKey = MapHiveToKey(parseResult.Hive); #endif { if (parseResult.HasSubKey) { using (RegistryKey registryKey = rootKey.OpenSubKey(parseResult.SubKey)) { if (registryKey != null) registryValue = registryKey.GetValue(renderedValue); } } else { registryValue = rootKey.GetValue(renderedValue); } } } catch (Exception ex) { InternalLogger.Error("Error when writing to registry"); if (ex.MustBeRethrown()) { throw; } } string value = null; if (registryValue != null) // valid value returned from registry will never be null { value = Convert.ToString(registryValue, CultureInfo.InvariantCulture); } else if (DefaultValue != null) { value = DefaultValue.Render(logEvent); if (RequireEscapingSlashesInDefaultValue) { //remove escape slash value = value.Replace("\\\\", "\\"); } } builder.Append(value); } private class ParseResult { public string SubKey { get; set; } public RegistryHive Hive { get; set; } /// <summary> /// Has <see cref="SubKey"/>? /// </summary> public bool HasSubKey => !string.IsNullOrEmpty(SubKey); } /// <summary> /// Parse key to <see cref="RegistryHive"/> and subkey. /// </summary> /// <param name="key">full registry key name</param> /// <returns>Result of parsing, never <c>null</c>.</returns> private static ParseResult ParseKey(string key) { string hiveName; int pos = key.IndexOfAny(new char[] { '\\', '/' }); string subkey = null; if (pos >= 0) { hiveName = key.Substring(0, pos); //normalize slashes subkey = key.Substring(pos + 1).Replace('/', '\\'); //remove starting slashes subkey = subkey.TrimStart('\\'); //replace double slashes from pre-layout times subkey = subkey.Replace("\\\\", "\\"); } else { hiveName = key; } var hive = ParseHiveName(hiveName); return new ParseResult { SubKey = subkey, Hive = hive, }; } /// <summary> /// Aliases for the hives. See https://msdn.microsoft.com/en-us/library/ctb3kd86(v=vs.110).aspx /// </summary> private static readonly Dictionary<string, RegistryHive> HiveAliases = new Dictionary<string, RegistryHive>(StringComparer.InvariantCultureIgnoreCase) { {"HKEY_LOCAL_MACHINE", RegistryHive.LocalMachine}, {"HKLM", RegistryHive.LocalMachine}, {"HKEY_CURRENT_USER", RegistryHive.CurrentUser}, {"HKCU", RegistryHive.CurrentUser}, {"HKEY_CLASSES_ROOT", RegistryHive.ClassesRoot}, {"HKEY_USERS", RegistryHive.Users}, {"HKEY_CURRENT_CONFIG", RegistryHive.CurrentConfig}, {"HKEY_DYN_DATA", RegistryHive.DynData}, {"HKEY_PERFORMANCE_DATA", RegistryHive.PerformanceData}, }; private static RegistryHive ParseHiveName(string hiveName) { RegistryHive hive; if (HiveAliases.TryGetValue(hiveName, out hive)) { return hive; } //ArgumentException is consistent throw new ArgumentException($"Key name is not supported. Root hive '{hiveName}' not recognized."); } #if NET3_5 private static RegistryKey MapHiveToKey(RegistryHive hive) { switch (hive) { case RegistryHive.LocalMachine: return Registry.LocalMachine; case RegistryHive.CurrentUser: return Registry.CurrentUser; default: throw new ArgumentException("Only RegistryHive.LocalMachine and RegistryHive.CurrentUser are supported.", nameof(hive)); } } #endif } } #endif
// Copyright (c) Microsoft Corporation // Licensed under the MIT license. See LICENSE file in the project root for full license information. // namespace Microsoft.Xbox.Services { using global::System; using global::System.Diagnostics; using global::System.Collections.Generic; using global::System.Globalization; using global::System.IO; using global::System.Net; using global::System.Reflection; using global::System.Runtime.InteropServices; using global::System.Text; using global::System.Threading; using global::System.Threading.Tasks; public class XboxLiveHttpRequest { private const string AuthorizationHeaderName = "Authorization"; private const string SignatureHeaderName = "Signature"; private const string RangeHeaderName = "Range"; private const string ContentLengthHeaderName = "Content-Length"; private const double DefaultHttpTimeoutSeconds = 30.0; private const double MinHttpTimeoutSeconds = 5.0; private const int HttpStatusCodeTooManyRequests = 429; private const double MaxDelayTimeInSec = 60.0; private const int MinDelayForHttpInternalErrorInSec = 10; private static string userAgentVersion; internal XboxLiveHttpRequest(string method, string serverName, string pathQueryFragment) { this.iterationNumber = 0; this.Method = method; this.Url = serverName + pathQueryFragment; this.contextSettings = XboxLive.Instance.Settings; this.webRequest = (HttpWebRequest)WebRequest.Create(new Uri(this.Url)); this.webRequest.Method = method; this.ResponseBodyType = HttpCallResponseBodyType.StringBody; this.RetryAllowed = true; this.SetCustomHeader("Accept-Language", CultureInfo.CurrentUICulture + "," + CultureInfo.CurrentUICulture.TwoLetterISOLanguageName); #if WINDOWS_UWP this.SetCustomHeader("Accept", "*/*"); #else this.webRequest.Accept = "*/*"; #endif this.SetCustomHeader("Cache-Control", "no-cache"); this.ContentType = "application/json; charset=utf-8"; } internal readonly XboxLiveSettings contextSettings; internal HttpWebRequest webRequest; internal readonly Dictionary<string, string> customHeaders = new Dictionary<string, string>(); internal bool hasPerformedRetryOn401 { get; set; } internal uint iterationNumber { get; set; } internal DateTime firstCallStartTime { get; set; } internal TimeSpan delayBeforeRetry { get; set; } public bool LongHttpCall { get; set; } public string Method { get; private set; } public string Url { get; private set; } public string ContractVersion { get; set; } public bool RetryAllowed { get; set; } public string ContentType { get; set; } public string RequestBody { get; set; } public HttpCallResponseBodyType ResponseBodyType { get; set; } public XboxLiveUser User { get; private set; } public XboxLiveAPIName XboxLiveAPI { get; set; } public string CallerContext { get; set; } private string Headers { get { StringBuilder sb = new StringBuilder(); bool isFirstVal = true; foreach (var header in this.customHeaders) { if (isFirstVal) { isFirstVal = false; } else { sb.AppendLine(); } sb.AppendFormat("{0}: {1}", header.Key, header.Value); } return sb.ToString(); } } public Task<XboxLiveHttpResponse> GetResponseWithAuth(XboxLiveUser user) { TaskCompletionSource<XboxLiveHttpResponse> taskCompletionSource = new TaskCompletionSource<XboxLiveHttpResponse>(); this.User = user; user.GetTokenAndSignatureAsync(this.Method, this.Url, this.Headers).ContinueWith( tokenTask => { if (tokenTask.IsFaulted) { taskCompletionSource.SetException(tokenTask.Exception); return; } try { this.SetAuthHeaders(tokenTask.Result); this.SetRequestHeaders(); this.InternalGetResponse().ContinueWith(getResponseTask => { if (getResponseTask.IsFaulted) { taskCompletionSource.SetException(getResponseTask.Exception); } else { taskCompletionSource.SetResult(getResponseTask.Result); } }); } catch (Exception e) { taskCompletionSource.SetException(e); } }); return taskCompletionSource.Task; } private void SetAuthHeaders(TokenAndSignatureResult result) { #if !WINDOWS_UWP this.SetCustomHeader(AuthorizationHeaderName, string.Format("XBL3.0 x={0};{1}", result.XboxUserHash, result.Token)); #else this.SetCustomHeader(AuthorizationHeaderName, string.Format("{0}", result.Token)); #endif this.SetCustomHeader(SignatureHeaderName, result.Signature); } private void SetRequestHeaders() { if (!string.IsNullOrEmpty(this.ContractVersion)) { this.SetCustomHeader("x-xbl-contract-version", this.ContractVersion); } foreach (KeyValuePair<string, string> customHeader in this.customHeaders) { this.webRequest.Headers[customHeader.Key] = customHeader.Value; } } public virtual Task<XboxLiveHttpResponse> GetResponseWithoutAuth() { this.SetRequestHeaders(); return this.InternalGetResponse(); } private void HandleThrottledCalls(XboxLiveHttpResponse httpCallResponse) { if (string.Equals(XboxLiveAppConfiguration.Instance.Sandbox, "RETAIL", StringComparison.Ordinal) || this.contextSettings.AreAssertsForThrottlingInDevSandboxesDisabled) return; #if DEBUG string msg; msg = "Xbox Live service call to " + httpCallResponse.Url.ToString() + " was throttled\r\n"; msg += httpCallResponse.RequestBody; msg += "\r\n"; msg += "You can temporarily disable the assert by calling\r\n"; msg += "XboxLive.Instance.Settings.DisableAssertsForXboxLiveThrottlingInDevSandboxes()\r\n"; msg += "Note that this will only disable this assert. You will still be throttled in all sandboxes.\r\n"; Debug.WriteLine(msg); #endif throw new XboxException("Xbox Live service call was throttled. See Output for more detail"); } private Task<XboxLiveHttpResponse> InternalGetResponse() { DateTime requestStartTime = DateTime.UtcNow; if (this.iterationNumber == 0) { this.firstCallStartTime = requestStartTime; } this.iterationNumber++; HttpRetryAfterApiState apiState; if (HttpRetryAfterManager.Instance.GetState(this.XboxLiveAPI, out apiState)) { if (this.ShouldFastFail(apiState, requestStartTime)) { return this.HandleFastFail(apiState); } else { HttpRetryAfterManager.Instance.ClearState(this.XboxLiveAPI); } } this.SetUserAgent(); TaskCompletionSource<XboxLiveHttpResponse> taskCompletionSource = new TaskCompletionSource<XboxLiveHttpResponse>(); this.WriteRequestBodyAsync().ContinueWith(writeBodyTask => { // The explicit cast in the next method should not be necessary, but Visual Studio is complaining // that the call is ambiguous. This removes that in-editor error. Task.Factory.FromAsync(this.webRequest.BeginGetResponse, (Func<IAsyncResult, WebResponse>)this.webRequest.EndGetResponse, null) .ContinueWith(getResponseTask => { var httpWebResponse = ExtractHttpWebResponse(getResponseTask); int httpStatusCode = 0; bool networkFailure = false; if (httpWebResponse != null) { httpStatusCode = (int)httpWebResponse.StatusCode; } else { // classify as network failure if there's no HTTP status code and didn't get response networkFailure = getResponseTask.IsFaulted || getResponseTask.IsCanceled; } var httpCallResponse = new XboxLiveHttpResponse( httpStatusCode, networkFailure, httpWebResponse, DateTime.UtcNow, requestStartTime, this.User != null ? this.User.XboxUserId : "", this.contextSettings, this.Url, this.XboxLiveAPI, this.Method, this.RequestBody, this.ResponseBodyType ); if (this.ShouldRetry(httpCallResponse)) { // Wait and retry call this.RecordServiceResult(httpCallResponse, getResponseTask.Exception); this.RouteServiceCall(httpCallResponse); Sleep(this.delayBeforeRetry); this.webRequest = CloneHttpWebRequest(this.webRequest); this.InternalGetResponse().ContinueWith(retryGetResponseTask => { if (retryGetResponseTask.IsFaulted) { taskCompletionSource.SetException(retryGetResponseTask.Exception); } else { taskCompletionSource.SetResult(retryGetResponseTask.Result); } }); } else if (!networkFailure) // Got HTTP status code { // HTTP 429: TOO MANY REQUESTS errors should return a JSON debug payload // describing the details about why the call was throttled this.RecordServiceResult(httpCallResponse, getResponseTask.Exception); this.RouteServiceCall(httpCallResponse); if (httpCallResponse.HttpStatus == HttpStatusCodeTooManyRequests) { this.HandleThrottledCalls(httpCallResponse); } if (getResponseTask.IsFaulted) { taskCompletionSource.SetException(getResponseTask.Exception); } else { taskCompletionSource.SetResult(httpCallResponse); } } else { // Handle network errors // HandleResponseError(); // TODO: extract error from JSON this.RecordServiceResult(httpCallResponse, getResponseTask.Exception); this.RouteServiceCall(httpCallResponse); taskCompletionSource.SetException(getResponseTask.Exception); } }); }); return taskCompletionSource.Task; } private bool ShouldFastFail( HttpRetryAfterApiState apiState, DateTime currentTime ) { if (apiState.Exception == null) { return false; } TimeSpan remainingTimeBeforeRetryAfter = apiState.RetryAfterTime - currentTime; if (remainingTimeBeforeRetryAfter.Ticks <= 0) { return false; } DateTime timeoutTime = this.firstCallStartTime + this.contextSettings.HttpTimeoutWindow; // If the Retry-After will happen first, just wait till Retry-After is done, and don't fast fail if (apiState.RetryAfterTime < timeoutTime) { Sleep(remainingTimeBeforeRetryAfter); return false; } else { return true; } } private Task<XboxLiveHttpResponse> HandleFastFail(HttpRetryAfterApiState apiState) { XboxLiveHttpResponse httpCallResponse = apiState.HttpCallResponse; this.RouteServiceCall(httpCallResponse); TaskCompletionSource<XboxLiveHttpResponse> taskCompletionSource = new TaskCompletionSource<XboxLiveHttpResponse>(); taskCompletionSource.SetException(apiState.Exception); return taskCompletionSource.Task; } private void SetUserAgent() { const string userAgentType = "XboxServicesAPICSharp"; lock (XboxLive.Instance) { if (string.IsNullOrEmpty(userAgentVersion)) { #if !WINDOWS_UWP userAgentVersion = typeof(XboxLiveHttpRequest).Assembly.GetName().Version.ToString(); #else userAgentVersion = typeof(XboxLiveHttpRequest).GetTypeInfo().Assembly.GetName().Version.ToString(); #endif } } string userAgent = userAgentType + "/" + userAgentVersion; if (!string.IsNullOrEmpty(this.CallerContext)) { userAgent += " " + this.CallerContext; } this.SetCustomHeader("UserAgent", userAgent); } private bool ShouldRetry(XboxLiveHttpResponse httpCallResponse) { int httpStatus = httpCallResponse.HttpStatus; if (!this.RetryAllowed && !(httpStatus == (int)HttpStatusCode.Unauthorized && this.User != null)) { return false; } if ((httpStatus == (int)HttpStatusCode.Unauthorized && !this.hasPerformedRetryOn401) || httpStatus == (int)HttpStatusCode.RequestTimeout || httpStatus == HttpStatusCodeTooManyRequests || httpStatus == (int)HttpStatusCode.InternalServerError || httpStatus == (int)HttpStatusCode.BadGateway || httpStatus == (int)HttpStatusCode.ServiceUnavailable || httpStatus == (int)HttpStatusCode.GatewayTimeout || httpCallResponse.NetworkFailure ) { TimeSpan retryAfter = httpCallResponse.RetryAfter; // Compute how much time left before hitting the HttpTimeoutWindow setting. TimeSpan timeElapsedSinceFirstCall = httpCallResponse.ResponseReceivedTime - this.firstCallStartTime; TimeSpan remainingTimeBeforeTimeout = this.contextSettings.HttpTimeoutWindow - timeElapsedSinceFirstCall; if (remainingTimeBeforeTimeout.TotalSeconds <= MinHttpTimeoutSeconds) // Need at least 5 seconds to bother making a call { return false; } // Based on the retry iteration, delay 2,4,8,16,etc seconds by default between retries // Jitter the response between the current and next delay based on system clock // Max wait time is 1 minute double secondsToWaitMin = Math.Pow(this.contextSettings.HttpRetryDelay.TotalSeconds, this.iterationNumber); double secondsToWaitMax = Math.Pow(this.contextSettings.HttpRetryDelay.TotalSeconds, this.iterationNumber + 1); double secondsToWaitDelta = secondsToWaitMax - secondsToWaitMin; DateTime responseDate = httpCallResponse.ResponseReceivedTime; double randTime = (httpCallResponse.ResponseReceivedTime.Minute * 60.0 * 1000.0) + (httpCallResponse.ResponseReceivedTime.Second * 1000.0) + httpCallResponse.ResponseReceivedTime.Millisecond; double lerpScaler = (randTime % 10000) / 10000.0; // from 0 to 1 based on clock if (XboxLive.UseMockHttp) { lerpScaler = 0; // make tests deterministic } double secondsToWaitUncapped = secondsToWaitMin + secondsToWaitDelta * lerpScaler; // lerp between min & max wait double secondsToWait = Math.Min(secondsToWaitUncapped, MaxDelayTimeInSec); // cap max wait to 1 min TimeSpan waitTime = TimeSpan.FromSeconds(secondsToWait); if (retryAfter.TotalMilliseconds > 0) { // Use either the waitTime or Retry-After header, whichever is bigger this.delayBeforeRetry = (waitTime > retryAfter) ? waitTime : retryAfter; } else { this.delayBeforeRetry = waitTime; } if (remainingTimeBeforeTimeout < this.delayBeforeRetry + TimeSpan.FromSeconds(MinHttpTimeoutSeconds)) { // Don't bother retrying when out of time return false; } if (httpStatus == (int)HttpStatusCode.InternalServerError) { // For 500 - Internal Error, wait at least 10 seconds before retrying. TimeSpan minDelayForHttpInternalError = TimeSpan.FromSeconds(MinDelayForHttpInternalErrorInSec); if (this.delayBeforeRetry < minDelayForHttpInternalError) { this.delayBeforeRetry = minDelayForHttpInternalError; } } else if (httpStatus == (int)HttpStatusCode.Unauthorized) { return this.HandleUnauthorizedError(); } return true; } return false; } private bool HandleUnauthorizedError() { if (this.User != null) // if this is null, it does not need a valid token anyways { try { Task task = this.User.RefreshToken(); task.Wait(); this.hasPerformedRetryOn401 = true; } catch (Exception) { return false; // if getting a new token failed, then we need to just return the 401 upwards } } else { this.hasPerformedRetryOn401 = true; } return true; } /// <summary> /// If a request body has been provided, this will write it to the stream. If there is no request body a completed task /// will be returned. /// </summary> /// <returns>A task that represents to request body write work.</returns> /// <remarks>This is used to make request chaining a little bit easier.</remarks> private Task WriteRequestBodyAsync() { if (string.IsNullOrEmpty(this.RequestBody)) { return Task.FromResult(true); } this.webRequest.ContentType = this.ContentType; #if !WINDOWS_UWP this.webRequest.ContentLength = this.RequestBody.Length; #else this.webRequest.Headers[ContentLengthHeaderName] = this.RequestBody.Length.ToString(); #endif // The explicit cast in the next method should not be necessary, but Visual Studio is complaining // that the call is ambiguous. This removes that in-editor error. return Task.Factory.FromAsync(this.webRequest.BeginGetRequestStream, (Func<IAsyncResult, Stream>)this.webRequest.EndGetRequestStream, null) .ContinueWith(t => { using (Stream body = t.Result) { using (StreamWriter sw = new StreamWriter(body)) { sw.Write(this.RequestBody); sw.Flush(); } } }); } public void SetCustomHeader(string headerName, string headerValue) { if (!this.customHeaders.ContainsKey(headerName)) { this.customHeaders.Add(headerName, headerValue); } else { this.customHeaders[headerName] = headerValue; } } public static XboxLiveHttpRequest Create(string httpMethod, string serverName, string pathQueryFragment) { return XboxLive.UseMockHttp ? new MockXboxLiveHttpRequest(httpMethod, serverName, pathQueryFragment) : new XboxLiveHttpRequest(httpMethod, serverName, pathQueryFragment); } public void SetRangeHeader(uint startByte, uint endByte) { var byteRange = "bytes=" + startByte + "-" + endByte; #if !WINDOWS_UWP this.webRequest.AddRange((int)startByte, (int)endByte); #else this.webRequest.Headers[RangeHeaderName] = byteRange; #endif } /// <summary> /// Creates a query string out of a list of parameters /// </summary> /// <param name="paramDictionary">List of Parameters to be added to the query</param> /// <returns>a query string that should be appended to the request</returns> public static string GetQueryFromParams(Dictionary<string, string> paramDictionary) { var queryString = new StringBuilder(); if (paramDictionary.Count > 0) { queryString.Append("?"); const string queryDelimiter = "&"; var firstParameter = true; foreach (var paramPair in paramDictionary) { if (firstParameter) firstParameter = false; else queryString.Append(queryDelimiter); queryString.Append(string.Format("{0}={1}", paramPair.Key, paramPair.Value)); } } return queryString.ToString(); } private void RecordServiceResult(XboxLiveHttpResponse httpCallResponse, Exception exception) { // Only remember result if there was an error and there was a Retry-After header if (this.XboxLiveAPI != XboxLiveAPIName.Unspecified && httpCallResponse.HttpStatus >= 400 //&& //httpCallResponse.RetryAfter.TotalSeconds > 0 ) { DateTime currentTime = DateTime.UtcNow; HttpRetryAfterApiState state = new HttpRetryAfterApiState(); state.RetryAfterTime = currentTime + httpCallResponse.RetryAfter; state.HttpCallResponse = httpCallResponse; state.Exception = exception; HttpRetryAfterManager.Instance.SetState(this.XboxLiveAPI, state); } } private void RouteServiceCall(XboxLiveHttpResponse httpCallResponse) { // TODO: port route logic } public static void Sleep(TimeSpan timeSpan) { // WinRT doesn't have Thread.Sleep, so using ManualResetEvent new ManualResetEvent(false).WaitOne(timeSpan); } private HttpWebResponse ExtractHttpWebResponse(Task<WebResponse> getResponseTask) { if (getResponseTask.IsFaulted && getResponseTask.Exception != null) { if (getResponseTask.Exception.InnerException is WebException) { WebException e = (WebException)getResponseTask.Exception.InnerException; if (e.Response is HttpWebResponse) { HttpWebResponse w = (HttpWebResponse)e.Response; return w; } } return null; } else { return (HttpWebResponse)getResponseTask.Result; } } public static HttpWebRequest CloneHttpWebRequest(HttpWebRequest original) { HttpWebRequest clone = (HttpWebRequest)WebRequest.Create(original.RequestUri.AbsoluteUri); PropertyInfo[] properties = original.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (property.Name != "ContentLength" && property.Name != "Headers") { object value = property.GetValue(original, null); if (property.CanWrite) { property.SetValue(clone, value, null); } } } foreach (var item in original.Headers.AllKeys) { clone.Headers[item] = original.Headers[item]; } return clone; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; public struct ValX0 { } public struct ValY0 { } public struct ValX1<T> { } public struct ValY1<T> { } public struct ValX2<T, U> { } public struct ValY2<T, U> { } public struct ValX3<T, U, V> { } public struct ValY3<T, U, V> { } public class RefX0 { } public class RefY0 { } public class RefX1<T> { } public class RefY1<T> { } public class RefX2<T, U> { } public class RefY2<T, U> { } public class RefX3<T, U, V> { } public class RefY3<T, U, V> { } public interface IGen<T> { void _Init(T fld1); bool InstVerify(System.Type t1); } public interface IGenSubInt : IGen<int> { } public interface IGenSubDouble : IGen<double> { } public interface IGenSubString : IGen<string> { } public interface IGenSubObject : IGen<object> { } public interface IGenSubGuid : IGen<Guid> { } public interface IGenSubConstructedReference : IGen<RefX1<int>> { } public interface IGenSubConstructedValue : IGen<ValX1<string>> { } public interface IGenSub1DIntArray : IGen<int[]> { } public interface IGenSub2DStringArray : IGen<string[,]> { } public interface IGenSubJaggedObjectArray : IGen<object[][]> { } public struct GenInt : IGenSubInt { int Fld1; public void _Init(int fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<int>)); } return result; } } public struct GenDouble : IGenSubDouble { double Fld1; public void _Init(double fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<double>)); } return result; } } public struct GenString : IGenSubString { string Fld1; public void _Init(string fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<string>)); } return result; } } public struct GenObject : IGenSubObject { object Fld1; public void _Init(object fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<object>)); } return result; } } public struct GenGuid : IGenSubGuid { Guid Fld1; public void _Init(Guid fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<Guid>)); } return result; } } public struct GenConstructedReference : IGenSubConstructedReference { RefX1<int> Fld1; public void _Init(RefX1<int> fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<RefX1<int>>)); } return result; } } public struct GenConstructedValue : IGenSubConstructedValue { ValX1<string> Fld1; public void _Init(ValX1<string> fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<ValX1<string>>)); } return result; } } public struct Gen1DIntArray : IGenSub1DIntArray { int[] Fld1; public void _Init(int[] fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<int[]>)); } return result; } } public struct Gen2DStringArray : IGenSub2DStringArray { string[,] Fld1; public void _Init(string[,] fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<string[,]>)); } return result; } } public struct GenJaggedObjectArray : IGenSubJaggedObjectArray { object[][] Fld1; public void _Init(object[][] fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(IGen<object[][]>)); } return result; } } public class Test { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { IGen<int> IGenInt = new GenInt(); IGenInt._Init(new int()); Eval(IGenInt.InstVerify(typeof(int))); IGen<double> IGenDouble = new GenDouble(); IGenDouble._Init(new double()); Eval(IGenDouble.InstVerify(typeof(double))); IGen<string> IGenString = new GenString(); IGenString._Init("string"); Eval(IGenString.InstVerify(typeof(string))); IGen<object> IGenObject = new GenObject(); IGenObject._Init(new object()); Eval(IGenObject.InstVerify(typeof(object))); IGen<Guid> IGenGuid = new GenGuid(); IGenGuid._Init(new Guid()); Eval(IGenGuid.InstVerify(typeof(Guid))); IGen<RefX1<int>> IGenConstructedReference = new GenConstructedReference(); IGenConstructedReference._Init(new RefX1<int>()); Eval(IGenConstructedReference.InstVerify(typeof(RefX1<int>))); IGen<ValX1<string>> IGenConstructedValue = new GenConstructedValue(); IGenConstructedValue._Init(new ValX1<string>()); Eval(IGenConstructedValue.InstVerify(typeof(ValX1<string>))); IGen<int[]> IGen1DIntArray = new Gen1DIntArray(); IGen1DIntArray._Init(new int[1]); Eval(IGen1DIntArray.InstVerify(typeof(int[]))); IGen<string[,]> IGen2DStringArray = new Gen2DStringArray(); IGen2DStringArray._Init(new string[1, 1]); Eval(IGen2DStringArray.InstVerify(typeof(string[,]))); IGen<object[][]> IGenJaggedObjectArray = new GenJaggedObjectArray(); IGenJaggedObjectArray._Init(new object[1][]); Eval(IGenJaggedObjectArray.InstVerify(typeof(object[][]))); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
// <copyright file="SparseVectorTest.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2013 Math.NET // // 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. // </copyright> using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Complex; using MathNet.Numerics.LinearAlgebra.Storage; using NUnit.Framework; using System; using System.Collections.Generic; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex { #if NOSYSNUMERICS using Complex = Numerics.Complex; #else using Complex = System.Numerics.Complex; #endif /// <summary> /// Sparse vector tests. /// </summary> public class SparseVectorTest : VectorTests { /// <summary> /// Creates a new instance of the Vector class. /// </summary> /// <param name="size">The size of the <strong>Vector</strong> to construct.</param> /// <returns>The new <c>Vector</c>.</returns> protected override Vector<Complex> CreateVector(int size) { return new SparseVector(size); } /// <summary> /// Creates a new instance of the Vector class. /// </summary> /// <param name="data">The array to create this vector from.</param> /// <returns>The new <c>Vector</c>.</returns> protected override Vector<Complex> CreateVector(IList<Complex> data) { var vector = new SparseVector(data.Count); for (var index = 0; index < data.Count; index++) { vector[index] = data[index]; } return vector; } /// <summary> /// Can create a sparse vector form array. /// </summary> [Test] public void CanCreateSparseVectorFromArray() { var data = new Complex[Data.Length]; Array.Copy(Data, data, Data.Length); var vector = SparseVector.OfEnumerable(data); for (var i = 0; i < data.Length; i++) { Assert.AreEqual(data[i], vector[i]); } } /// <summary> /// Can create a sparse vector from another sparse vector. /// </summary> [Test] public void CanCreateSparseVectorFromAnotherSparseVector() { var vector = SparseVector.OfEnumerable(Data); var other = SparseVector.OfVector(vector); Assert.AreNotSame(vector, other); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(vector[i], other[i]); } } /// <summary> /// Can create a sparse vector from another vector. /// </summary> [Test] public void CanCreateSparseVectorFromAnotherVector() { var vector = (Vector<Complex>)SparseVector.OfEnumerable(Data); var other = SparseVector.OfVector(vector); Assert.AreNotSame(vector, other); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(vector[i], other[i]); } } /// <summary> /// Can create a sparse vector from user defined vector. /// </summary> [Test] public void CanCreateSparseVectorFromUserDefinedVector() { var vector = new UserDefinedVector(Data); var other = SparseVector.OfVector(vector); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(vector[i], other[i]); } } /// <summary> /// Can create a sparse matrix. /// </summary> [Test] public void CanCreateSparseMatrix() { var vector = new SparseVector(3); var matrix = Matrix<Complex>.Build.SameAs(vector, 2, 3); Assert.IsInstanceOf<SparseMatrix>(matrix); Assert.AreEqual(2, matrix.RowCount); Assert.AreEqual(3, matrix.ColumnCount); } /// <summary> /// Can convert a sparse vector to an array. /// </summary> [Test] public void CanConvertSparseVectorToArray() { var vector = SparseVector.OfEnumerable(Data); var array = vector.ToArray(); Assert.IsInstanceOf(typeof (Complex[]), array); CollectionAssert.AreEqual(vector, array); } /// <summary> /// Can convert an array to a sparse vector. /// </summary> [Test] public void CanConvertArrayToSparseVector() { var array = new[] {new Complex(1, 1), new Complex(2, 1), new Complex(3, 1), new Complex(4, 1)}; var vector = SparseVector.OfEnumerable(array); Assert.IsInstanceOf(typeof (SparseVector), vector); CollectionAssert.AreEqual(array, array); } /// <summary> /// Can multiply a sparse vector by a scalar using "*" operator. /// </summary> [Test] public void CanMultiplySparseVectorByScalarUsingOperators() { var vector = SparseVector.OfEnumerable(Data); vector = vector*new Complex(2.0, 1); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*new Complex(2.0, 1), vector[i]); } vector = vector*1.0; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*new Complex(2.0, 1), vector[i]); } vector = SparseVector.OfEnumerable(Data); vector = new Complex(2.0, 1)*vector; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*new Complex(2.0, 1), vector[i]); } vector = 1.0*vector; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*new Complex(2.0, 1), vector[i]); } } /// <summary> /// Can divide a sparse vector by a scalar using "/" operator. /// </summary> [Test] public void CanDivideSparseVectorByScalarUsingOperators() { var vector = SparseVector.OfEnumerable(Data); vector = vector/new Complex(2.0, 1); for (var i = 0; i < Data.Length; i++) { AssertHelpers.AlmostEqualRelative(Data[i]/new Complex(2.0, 1), vector[i], 14); } vector = vector/1.0; for (var i = 0; i < Data.Length; i++) { AssertHelpers.AlmostEqualRelative(Data[i]/new Complex(2.0, 1), vector[i], 14); } } /// <summary> /// Can calculate an outer product for a sparse vector. /// </summary> [Test] public void CanCalculateOuterProductForSparseVector() { var vector1 = CreateVector(Data); var vector2 = CreateVector(Data); var m = Vector<Complex>.OuterProduct(vector1, vector2); for (var i = 0; i < vector1.Count; i++) { for (var j = 0; j < vector2.Count; j++) { Assert.AreEqual(m[i, j], vector1[i]*vector2[j]); } } } /// <summary> /// Check sparse mechanism by setting values. /// </summary> [Test] public void CheckSparseMechanismBySettingValues() { var vector = new SparseVector(10000); var storage = (SparseVectorStorage<Complex>) vector.Storage; // Add non-zero elements vector[200] = new Complex(1.5, 1); Assert.AreEqual(new Complex(1.5, 1), vector[200]); Assert.AreEqual(1, storage.ValueCount); vector[500] = new Complex(3.5, 1); Assert.AreEqual(new Complex(3.5, 1), vector[500]); Assert.AreEqual(2, storage.ValueCount); vector[800] = new Complex(5.5, 1); Assert.AreEqual(new Complex(5.5, 1), vector[800]); Assert.AreEqual(3, storage.ValueCount); vector[0] = new Complex(7.5, 1); Assert.AreEqual(new Complex(7.5, 1), vector[0]); Assert.AreEqual(4, storage.ValueCount); // Remove non-zero elements vector[200] = Complex.Zero; Assert.AreEqual(Complex.Zero, vector[200]); Assert.AreEqual(3, storage.ValueCount); vector[500] = Complex.Zero; Assert.AreEqual(Complex.Zero, vector[500]); Assert.AreEqual(2, storage.ValueCount); vector[800] = Complex.Zero; Assert.AreEqual(Complex.Zero, vector[800]); Assert.AreEqual(1, storage.ValueCount); vector[0] = Complex.Zero; Assert.AreEqual(Complex.Zero, vector[0]); Assert.AreEqual(0, storage.ValueCount); } /// <summary> /// Check sparse mechanism by zero multiply. /// </summary> [Test] public void CheckSparseMechanismByZeroMultiply() { var vector = new SparseVector(10000); // Add non-zero elements vector[200] = new Complex(1.5, 1); vector[500] = new Complex(3.5, 1); vector[800] = new Complex(5.5, 1); vector[0] = new Complex(7.5, 1); // Multiply by 0 vector *= 0; var storage = (SparseVectorStorage<Complex>) vector.Storage; Assert.AreEqual(Complex.Zero, vector[200]); Assert.AreEqual(Complex.Zero, vector[500]); Assert.AreEqual(Complex.Zero, vector[800]); Assert.AreEqual(Complex.Zero, vector[0]); Assert.AreEqual(0, storage.ValueCount); } /// <summary> /// Can calculate a dot product of two sparse vectors. /// </summary> [Test] public void CanDotProductOfTwoSparseVectors() { var vectorA = new SparseVector(10000); vectorA[200] = 1; vectorA[500] = 3; vectorA[800] = 5; vectorA[100] = 7; vectorA[900] = 9; var vectorB = new SparseVector(10000); vectorB[300] = 3; vectorB[500] = 5; vectorB[800] = 7; Assert.AreEqual(new Complex(50.0, 0), vectorA.DotProduct(vectorB)); } /// <summary> /// Can pointwise multiple a sparse vector. /// </summary> [Test] public void CanPointwiseMultiplySparseVector() { var zeroArray = new[] {Complex.Zero, new Complex(1.0, 1), Complex.Zero, new Complex(1.0, 1), Complex.Zero}; var vector1 = SparseVector.OfEnumerable(Data); var vector2 = SparseVector.OfEnumerable(zeroArray); var result = new SparseVector(vector1.Count); vector1.PointwiseMultiply(vector2, result); for (var i = 0; i < vector1.Count; i++) { Assert.AreEqual(Data[i]*zeroArray[i], result[i]); } var resultStorage = (SparseVectorStorage<Complex>) result.Storage; Assert.AreEqual(2, resultStorage.ValueCount); } /// <summary> /// Test for issues #52. When setting previous non-zero values to zero, /// DoMultiply would copy non-zero values to the result, but use the /// length of nonzerovalues instead of NonZerosCount. /// </summary> [Test] public void CanScaleAVectorWhenSettingPreviousNonzeroElementsToZero() { var vector = new SparseVector(20); vector[10] = 1.0; vector[11] = 2.0; vector[11] = 0.0; var scaled = new SparseVector(20); vector.Multiply(3.0, scaled); Assert.AreEqual(3.0, scaled[10].Real); Assert.AreEqual(0.0, scaled[11].Real); } } }
using NUnit.Framework; using RefactoringEssentials.CSharp.Diagnostics; class TestClass2 { } class TestClass { void TestMethod<T>(T x) where T : TestClass2 { if (x is TestClass) ; } } namespace RefactoringEssentials.Tests.CSharp.Diagnostics { [TestFixture] [Ignore("TODO: Issue not ported yet")] public class ExpressionIsNeverOfProvidedTypeTests : CSharpDiagnosticTestBase { [Test] public void TestClass() { var input = @" class AnotherClass { } class TestClass { void TestMethod (AnotherClass x) { if (x is TestClass) ; } }"; Test<ExpressionIsNeverOfProvidedTypeAnalyzer>(input, 1); } [Test] public void TestClassNoIssue() { var input = @" interface ITest { } class TestClass { void TestMethod (object x) { if (x is ITest) ; if (x is TestClass) ; } }"; Test<ExpressionIsNeverOfProvidedTypeAnalyzer>(input, 0); } [Test] public void TestSealedClass() { var input = @" interface ITest { } sealed class TestClass { void TestMethod (TestClass x) { if (x is ITest) ; } }"; Test<ExpressionIsNeverOfProvidedTypeAnalyzer>(input, 1); } [Test] public void TestNull() { var input = @" class TestClass { void TestMethod () { if (null is object) ; } }"; Test<ExpressionIsNeverOfProvidedTypeAnalyzer>(input, 1); } [Test] public void TestObjectToInt() { var input = @" sealed class TestClass { void TestMethod (object x) { if (x is int) ; } }"; Test<ExpressionIsNeverOfProvidedTypeAnalyzer>(input, 0); } [Test] public void TestClassIsTypeParameter() { var input = @" class TestClass2 { } class TestClass { void TestMethod<T, T2> (TestClass x) where T : TestClass2 where T2 : struct { if (x is T) ; if (x is T2) ; } }"; Test<ExpressionIsNeverOfProvidedTypeAnalyzer>(input, 2); } [Test] public void TestClassIsTypeParameter2() { var input = @" interface ITest { } class TestBase { } class TestClass2 : TestClass { } class TestClass : TestBase { void TestMethod<T, T2, T3> (TestClass x) where T : TestBase where T2 : ITest where T3 : TestClass2 { if (x is T3) ; } }"; Test<ExpressionIsNeverOfProvidedTypeAnalyzer>(input, 0); } [Test] public void TestStructIsTypeParameter() { var input = @" interface ITest { } struct TestStruct : ITest { } class TestClass { void TestMethod<T> (TestStruct x) where T : ITest { if (x is T) ; } }"; Test<ExpressionIsNeverOfProvidedTypeAnalyzer>(input, 0); } [Test] public void TestStructIsTypeParameter2() { var input = @" struct TestStruct { } class TestClass { void TestMethod<T> (TestStruct x) where T : class { if (x is T) ; } }"; // this is possible with T==object Test<ExpressionIsNeverOfProvidedTypeAnalyzer>(input, 0); } [Test] public void TestTypeParameter() { var input = @" class TestClass2 { } class TestClass { void TestMethod<T> (T x) where T : TestClass2 { if (x is TestClass) ; } }"; Test<ExpressionIsNeverOfProvidedTypeAnalyzer>(input, 1); } [Test] public void TestTypeParameter2() { var input = @" class TestClass { void TestMethod<T> (T x) where T : struct { if (x is TestClass) ; } }"; Test<ExpressionIsNeverOfProvidedTypeAnalyzer>(input, 1); } [Test] public void TestTypeParameter3() { var input = @" interface ITest { } class TestClass { void TestMethod<T> (T x) where T : ITest, new() { if (x is TestClass) ; } }"; Test<ExpressionIsNeverOfProvidedTypeAnalyzer>(input, 0); } [Test] public void TestTypeParameter4() { var input = @" interface ITest { } sealed class TestClass { void TestMethod<T> (T x) where T : ITest { if (x is TestClass) ; } }"; Test<ExpressionIsNeverOfProvidedTypeAnalyzer>(input, 1); } [Test] public void TestTypeParameterIsTypeParameter() { var input = @" class TestClass2 { } class TestClass { void TestMethod<T, T2> (T x) where T : TestClass where T2 : TestClass2 { if (x is T2) ; } }"; Test<ExpressionIsNeverOfProvidedTypeAnalyzer>(input, 1); } [Test] public void TestTypeParameterIsTypeParameter2() { var input = @" interface ITest { } class TestClass { void TestMethod<T, T2> (T x) where T : TestClass where T2 : ITest, new() { if (x is T2) ; } }"; Test<ExpressionIsNeverOfProvidedTypeAnalyzer>(input, 0); } [Test] public void TestObjectArrayToStringArray() { var input = @" sealed class TestClass { void TestMethod (object[] x) { if (x is string[]) ; } }"; Test<ExpressionIsNeverOfProvidedTypeAnalyzer>(input, 0); } [Test] public void UnknownExpression() { var input = @" sealed class TestClass { void TestMethod () { if (unknown is string) ; } }"; Test<ExpressionIsNeverOfProvidedTypeAnalyzer>(input, 0); } [Test] public void UnknownType() { var input = @" sealed class TestClass { void TestMethod (int x) { if (x is unknown) ; } }"; Test<ExpressionIsNeverOfProvidedTypeAnalyzer>(input, 0); } } }
using System; using System.Collections.Generic; using System.Text; using com.calitha.goldparser; using Epi.Core.AnalysisInterpreter; namespace Epi.Core.AnalysisInterpreter.Rules { /* <FuncName1> ::= ABS |COS |DAY|DAYS |ENVIRON|EXISTS|EXP |FILEDATE|FINDTEXT|FORMAT |HOUR|HOURS |LN|LOG |MINUTES|Month|MONTHS |NUMTODATE|NUMTOTIME |RECORDCOUNT|RND|ROUND |SECOND|SECONDS|STEP|SUBSTRING|SIN |TRUNC|TXTTODATE|TXTTONUM|TAN |UPPERCASE |YEAR|YEARS <FuncName2> ::= SYSTEMTIME|SYSTEMDATE <FunctionCall> ::= <FuncName1> '(' <FunctionParameterList> ')' | <FuncName1> '(' <FunctionCall> ')' | <FuncName2> <FunctionParameterList> ::= <EmptyFunctionParameterList> | <NonEmptyFunctionParameterList> <NonEmptyFunctionParameterList> ::= <MultipleFunctionParameterList> | <SingleFunctionParameterList> <MultipleFunctionParameterList> ::= <NonEmptyFunctionParameterList> ',' <Expression> <SingleFunctionParameterList> ::= <Expression> <EmptyFunctionParameterList> ::= */ /// <summary> /// Class for executing FunctionCall reductions. /// </summary> public partial class Rule_FunctionCall : AnalysisRule { private string functionName = null; private AnalysisRule functionCall = null; private string ClassName = null; private string MethodName = null; private List<AnalysisRule> ParameterList = new List<AnalysisRule>(); #region Constructors /// <summary> /// Constructor for Rule_FunctionCall /// </summary> /// <param name="pToken">The token to build the reduction with.</param> public Rule_FunctionCall(Rule_Context pContext, NonterminalToken pToken) : base(pContext) { /* <FunctionCall> ::= <FuncName1> '(' <FunctionParameterList> ')' | <FuncName1> '(' <FunctionCall> ')' | <FuncName2> */ NonterminalToken T; if (pToken.Tokens.Length == 1) { if (pToken.Rule.ToString().Equals("<FunctionCall>")) { T = (NonterminalToken)pToken.Tokens[0]; } else { T = pToken; } } else { T = (NonterminalToken)pToken.Tokens[2]; } string temp = null; string[] temp2 = null; if (pToken.Tokens[0] is NonterminalToken) { temp = this.ExtractTokens(((NonterminalToken)pToken.Tokens[0]).Tokens).Replace(" . ", "."); temp2 = temp.Split('.'); } else { temp = ((TerminalToken)pToken.Tokens[0]).Text.Replace(" . ", "."); } if(temp2 != null && temp2.Length > 1) { this.ClassName = temp2[0].Trim(); this.MethodName = temp2[1].Trim(); this.ParameterList = AnalysisRule.GetFunctionParameters(pContext, (NonterminalToken)pToken.Tokens[2]); } else { functionName = this.GetCommandElement(pToken.Tokens, 0).ToString(); switch (functionName.ToUpperInvariant()) { case "ABS": functionCall = new Rule_Abs(pContext, T); break; case "COS": functionCall = new Rule_Cos(pContext, T); break; case "DAY": functionCall = new Rule_Day(pContext, T); break; case "DAYS": functionCall = new Rule_Days(pContext, T); break; case "FORMAT": functionCall = new Rule_Format(pContext, T); break; case "HOUR": functionCall = new Rule_Hour(pContext, T); break; case "HOURS": functionCall = new Rule_Hours(pContext, T); break; case "MINUTE": functionCall = new Rule_Minute(pContext, T); break; case "MINUTES": functionCall = new Rule_Minutes(pContext, T); break; case "MONTH": functionCall = new Rule_Month(pContext, T); break; case "MONTHS": functionCall = new Rule_Months(pContext, T); break; case "NUMTODATE": functionCall = new Rule_NumToDate(pContext, T); break; case "NUMTOTIME": functionCall = new Rule_NumToTime(pContext, T); break; case "RECORDCOUNT": functionCall = new Rule_RecordCount(pContext, T); break; case "SECOND": functionCall = new Rule_Second(pContext, T); break; case "SECONDS": functionCall = new Rule_Seconds(pContext, T); break; case "SYSTEMDATE": functionCall = new Rule_SystemDate(pContext, T); break; case "SYSTEMTIME": functionCall = new Rule_SystemTime(pContext, T); break; case "TXTTODATE": functionCall = new Rule_TxtToDate(pContext, T); break; case "TXTTONUM": functionCall = new Rule_TxtToNum(pContext, T); break; case "YEAR": functionCall = new Rule_Year(pContext, T); break; case "YEARS": functionCall = new Rule_Years(pContext, T); break; case "STRLEN": functionCall = new Rule_STRLEN(pContext, T); break; case "SUBSTRING": functionCall = new Rule_Substring(pContext, T); break; case "RND": functionCall = new Rule_Rnd(pContext, T); break; case "EXP": functionCall = new Rule_Exp_Func(pContext, T); break; case "LN": functionCall = new Rule_LN_Func(pContext, T); break; case "ROUND": functionCall = new Rule_Round(pContext, T); break; case "LOG": functionCall = new Rule_LOG_Func(pContext, T); break; case "SQRT": functionCall = new Rule_SQRT_Func(pContext, T); break; case "POISSONLCL": functionCall = new Rule_POISSONLCL_Func(pContext, T); break; case "POISSONUCL": functionCall = new Rule_POISSONUCL_Func(pContext, T); break; case "SIN": functionCall = new Rule_Sin(pContext, T); break; case "TAN": functionCall = new Rule_Tan(pContext, T); break; case "TRUNC": functionCall = new Rule_TRUNC(pContext, T); break; case "STEP": functionCall = new Rule_Step(pContext, T); break; case "UPPERCASE": functionCall = new Rule_UpperCase(pContext, T); break; case "FINDTEXT": functionCall = new Rule_FindText(pContext, T); break; case "ENVIRON": functionCall = new Rule_Environ(pContext, T); break; case "EXISTS": functionCall = new Rule_Exists(pContext, T); break; case "FILEDATE": functionCall = new Rule_FileDate(pContext, T); break; case "ZSCORE": functionCall = new Rule_ZSCORE(pContext, T); break; case "PFROMZ": functionCall = new Rule_PFROMZ(pContext, T); break; case "EPIWEEK": functionCall = new Rule_EPIWEEK(pContext, T); break; default: throw new Exception("Function name " + functionName.ToUpperInvariant() + " is not a recognized function."); } } } #endregion #region Public Methods /// <summary> /// Executes the reduction. /// </summary> /// <returns>Returns the result of executing the reduction.</returns> public override object Execute() { object result = null; if (string.IsNullOrEmpty(this.functionName)) { if (this.Context.DLLClassList.ContainsKey(this.ClassName.ToLowerInvariant())) { object[] args = this.ParameterList.ToArray(); if (this.ParameterList.Count > 0) { args = new object[this.ParameterList.Count]; for (int i = 0; i < this.ParameterList.Count; i++) { args[i] = this.ParameterList[i].Execute(); } } else { args = new object[0]; } result = this.Context.DLLClassList[this.ClassName].Execute(this.MethodName, args); } } else { if (this.functionCall != null) { result = this.functionCall.Execute(); } } return result; } #endregion } /// <summary> /// Class for the FunctionParameterList reduction /// </summary> public partial class Rule_FunctionParameterList : AnalysisRule { public Stack<AnalysisRule> paramList = null; #region Constructors /// <summary> /// Constructor for Rule_FunctionParameterList /// </summary> /// <param name="pToken">The token to build the reduction with.</param> public Rule_FunctionParameterList(Rule_Context pContext, NonterminalToken pToken) : base(pContext) { //<FunctionParameterList> ::= <EmptyFunctionParameterList> //<FunctionParameterList> ::= <NonEmptyFunctionParameterList> NonterminalToken T = (NonterminalToken)pToken.Tokens[0]; switch (T.Rule.Lhs.ToString()) { case "<NonEmptyFunctionParameterList>": this.paramList = new Stack<AnalysisRule>(); //this.paramList.Push(new Rule_NonEmptyFunctionParameterList(T, this.paramList)); new Rule_NonEmptyFunctionParameterList(pContext, T, this.paramList); break; case "<SingleFunctionParameterList>": this.paramList = new Stack<AnalysisRule>(); new Rule_SingleFunctionParameterList(pContext, T, this.paramList); break; case "<EmptyFunctionParameterList>": //this.paramList = new Rule_EmptyFunctionParameterList(T); // do nothing the parameterlist is empty break; case "<MultipleFunctionParameterList>": this.paramList = new Stack<AnalysisRule>(); //this.MultipleParameterList = new Rule_MultipleFunctionParameterList(pToken); new Rule_MultipleFunctionParameterList(pContext, T, this.paramList); break; } } #endregion #region Public Methods /// <summary> /// rule to build zero or more funtion parameters builds parameters and allows the associated function to call the parameters when needed /// </summary> /// <returns>object</returns> public override object Execute() { object result = null; return result; } #endregion } /// <summary> /// Class for the Rule_EmptyFunctionParameterList reduction /// </summary> public partial class Rule_EmptyFunctionParameterList : AnalysisRule { #region Constructors public Rule_EmptyFunctionParameterList(Rule_Context pContext, NonterminalToken pToken) : base(pContext) { //<EmptyFunctionParameterList> ::= } #endregion #region Public Methods /// <summary> /// rule to return an empty parameter /// </summary> /// <returns>object</returns> public override object Execute() { return String.Empty; } #endregion } /// <summary> /// Class for the Rule_NonEmptyFunctionParameterList reduction. /// </summary> public partial class Rule_NonEmptyFunctionParameterList : AnalysisRule { protected Stack<AnalysisRule> MultipleParameterList = null; //private Reduction SingleParameterList = null; #region Constructors public Rule_NonEmptyFunctionParameterList(Rule_Context pContext, NonterminalToken pToken) : base(pContext) { //<NonEmptyFunctionParameterList> ::= <MultipleFunctionParameterList> //<NonEmptyFunctionParameterList> ::= <SingleFunctionParameterList> NonterminalToken T = (NonterminalToken) pToken.Tokens[0]; switch (T.Rule.Lhs.ToString()) { case "<MultipleFunctionParameterList>": this.MultipleParameterList = new Stack<AnalysisRule>(); //this.MultipleParameterList = new Rule_MultipleFunctionParameterList(pToken); new Rule_MultipleFunctionParameterList(pContext, T, this.MultipleParameterList); break; case "<SingleFunctionParameterList>": //this.SingleParameterList = new Rule_SingleFunctionParameterList(pToken); new Rule_SingleFunctionParameterList(pContext, T, this.MultipleParameterList); break; } } public Rule_NonEmptyFunctionParameterList(Rule_Context pContext, NonterminalToken pToken, Stack<AnalysisRule> pList) : base(pContext) { //<NonEmptyFunctionParameterList> ::= <MultipleFunctionParameterList> //<NonEmptyFunctionParameterList> ::= <SingleFunctionParameterList> NonterminalToken T = (NonterminalToken) pToken.Tokens[0]; switch (T.Rule.Lhs.ToString()) { case "<MultipleFunctionParameterList>": new Rule_MultipleFunctionParameterList(pContext, T, pList); break; case "<SingleFunctionParameterList>": new Rule_SingleFunctionParameterList(pContext, T, pList); break; default: break; } if (pToken.Tokens.Length > 2) { Rule_Expression Expression = new Rule_Expression(pContext, (NonterminalToken)pToken.Tokens[2]); pList.Push(Expression); } } #endregion #region Public Methods /// <summary> /// builds a multi parameters list which is executed in the calling function's execute method. /// </summary> /// <returns>object</returns> public override object Execute() { return null; } #endregion } /// <summary> /// Class for the Rule_MultipleFunctionParameterList reduction. /// </summary> public partial class Rule_MultipleFunctionParameterList : AnalysisRule { private AnalysisRule Expression = null; private AnalysisRule nonEmptyList = null; #region Constructors public Rule_MultipleFunctionParameterList(Rule_Context pContext, NonterminalToken pToken, Stack<AnalysisRule> pList) : base(pContext) { //<MultipleFunctionParameterList> ::= <NonEmptyFunctionParameterList> ',' <Expression> NonterminalToken nonEmptyToken = (NonterminalToken)pToken.Tokens[0]; NonterminalToken ExpressionToken = (NonterminalToken)pToken.Tokens[2]; // nonEmptyList = new Rule_NonEmptyFunctionParameterList(pContext, nonEmptyToken, pList); //this.Expression = new Rule_Expression(pContext, ExpressionToken); pList.Push(AnalysisRule.BuildStatments(pContext, nonEmptyToken)); pList.Push(AnalysisRule.BuildStatments(pContext, ExpressionToken)); //pList.Push(this.Expression); } #endregion #region Public Methods /// <summary> /// assists in building a multi parameters list which is executed in the calling function's execute method. /// </summary> /// <returns>object</returns> public override object Execute() { object result = null; //nonEmptyList.Execute(); //result = Expression.Execute(); return result; } #endregion } /// <summary> /// Class for the Rule_SingleFunctionParameterList reduction. /// </summary> public partial class Rule_SingleFunctionParameterList : AnalysisRule { private AnalysisRule Expression = null; #region Constructors public Rule_SingleFunctionParameterList(Rule_Context pContext, NonterminalToken pToken, Stack<AnalysisRule> pList) : base(pContext) { //<SingleFunctionParameterList> ::= <Expression> this.Expression = new Rule_Expression(pContext, (NonterminalToken)pToken.Tokens[0]); pList.Push(this.Expression); } #endregion #region Public Methods /// <summary> /// executes the parameter expression of a function. /// </summary> /// <returns>object</returns> public override object Execute() { object result = null; result = this.Expression.Execute(); return result; } #endregion } //**** //**** Not implemented yet, but on the list of features //**** //public partial class Rule_Uppercase : Reduction //{ // private Reduction functionCallOrParamList = null; // private string type; // private List<Reduction> reductions = new List<Reduction>(); // private List<object> reducedValues = null; // private string fullString = null; // public Rule_Uppercase(Rule_Context pContext, NonterminalToken pToken) : base(pContext) // { // //UPPERCASE(fullString) // NonterminalToken T = (NonterminalToken)pToken.Tokens[0]; // type = pToken.Rule.Lhs.ToString(); // switch (type) // { // case "<FunctionParameterList>": // this.functionCallOrParamList = new Rule_FunctionParameterList(T); // string tmp = this.GetCommandElement(pToken.Tokens, 0); // reductions.Add(new Rule_Value(tmp)); // break; // case "<FunctionCall>": // this.functionCallOrParamList = new Rule_FunctionCall(T); // break; // default: // break; // } // } // public override object Execute() // { // object result = null; // reducedValues = new List<object>(); // reducedValues.Add(FunctionUtils.StripQuotes(reductions[0].Execute().ToString())); // fullString = (string)reducedValues[0]; // result = fullString.ToUpperInvariant(); // return result; // } //} /// <summary> /// Utility class for helper methods for the Epi Functions. /// </summary> public static class FunctionUtils { public enum DateInterval { Second, Minute, Hour, Day, Month, Year } /// <summary> /// Gets the appropriate date value based on the date and interval. /// </summary> /// <param name="interval">The interval to retrieve from the date.</param> /// <param name="date">The date to get the value from.</param> /// <returns></returns> public static object GetDatePart(DateInterval interval, DateTime date) { object returnValue = null; switch (interval) { case DateInterval.Second: returnValue = date.Second; break; case DateInterval.Minute: returnValue = date.Minute; break; case DateInterval.Hour: returnValue = date.Hour; break; case DateInterval.Day: returnValue = date.Day; break; case DateInterval.Month: returnValue = date.Month; break; case DateInterval.Year: returnValue = date.Year; break; } return returnValue; } /// <summary> /// Gets the difference between two dates based on an interval. /// </summary> /// <param name="interval">The interval to use (seconds, minutes, hours, days, months, years)</param> /// <param name="date1">The date to use for comparison.</param> /// <param name="date2">The date to compare against the first date.</param> /// <returns></returns> public static object GetDateDiff(DateInterval interval, DateTime date1, DateTime date2) { object returnValue = null; TimeSpan t; object diff = 0.0; //returns negative value if date1 is more recent t = date2 - date1; switch (interval) { case DateInterval.Second: diff = t.TotalSeconds; break; case DateInterval.Minute: diff = t.TotalMinutes; break; case DateInterval.Hour: diff = t.TotalHours; break; case DateInterval.Day: diff = t.TotalDays; break; case DateInterval.Month: diff = t.TotalDays / 365.25 * 12.0; break; case DateInterval.Year: diff = t.TotalDays / 365.25; break; } returnValue = Convert.ToInt32(diff); return returnValue; } /// <summary> /// Removes all double quotes from a string. /// </summary> /// <param name="s">The string to remove quotes from.</param> /// <returns>Returns the modified string with no double quotes.</returns> public static string StripQuotes(string s) { return s.Trim(new char[] { '\"' }); } } }
// 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.Numerics; using NUnit.Framework; using osu.Framework.Graphics; namespace osu.Framework.Tests.Graphics { [TestFixture] public class ColourTest { [Test] public void TestFromHSL() { // test FromHSL that black and white are only affected by luminance testConvertFromHSL(Colour4.White, (0f, 0.5f, 1f, 1f)); testConvertFromHSL(Colour4.White, (1f, 1f, 1f, 1f)); testConvertFromHSL(Colour4.White, (0.5f, 0.75f, 1f, 1f)); testConvertFromHSL(Colour4.Black, (0f, 0.5f, 0f, 1f)); testConvertFromHSL(Colour4.Black, (1f, 1f, 0f, 1f)); testConvertFromHSL(Colour4.Black, (0.5f, 0.75f, 0f, 1f)); // test FromHSL that grey is not affected by hue testConvertFromHSL(Colour4.Gray, (0f, 0f, 0.5f, 1f)); testConvertFromHSL(Colour4.Gray, (0.5f, 0f, 0.5f, 1f)); testConvertFromHSL(Colour4.Gray, (1f, 0f, 0.5f, 1f)); // test FromHSL that alpha is being passed through testConvertFromHSL(Colour4.Black.Opacity(0.5f), (0f, 0f, 0f, 0.5f)); // test FromHSL with primaries testConvertFromHSL(Colour4.Red, (0, 1f, 0.5f, 1f)); testConvertFromHSL(Colour4.Yellow, (1f / 6f, 1f, 0.5f, 1f)); testConvertFromHSL(Colour4.Lime, (2f / 6f, 1f, 0.5f, 1f)); testConvertFromHSL(Colour4.Cyan, (3f / 6f, 1f, 0.5f, 1f)); testConvertFromHSL(Colour4.Blue, (4f / 6f, 1f, 0.5f, 1f)); testConvertFromHSL(Colour4.Magenta, (5f / 6f, 1f, 0.5f, 1f)); testConvertFromHSL(Colour4.Red, (1f, 1f, 0.5f, 1f)); // test FromHSL with some other knowns testConvertFromHSL(Colour4.CornflowerBlue, (219f / 360f, 0.792f, 0.661f, 1f)); testConvertFromHSL(Colour4.Tan.Opacity(0.5f), (34f / 360f, 0.437f, 0.686f, 0.5f)); } [Test] public void TestToHSL() { // test ToHSL that black, white, and grey always return constant 0f for hue and saturation testConvertToHSL((0f, 0f, 1f, 1f), Colour4.White); testConvertToHSL((0f, 0f, 0f, 1f), Colour4.Black); testConvertToHSL((0f, 0f, 0.5f, 1f), Colour4.Gray); // test ToHSL that alpha is being passed through testConvertToHSL((0f, 0f, 0f, 0.5f), Colour4.Black.Opacity(0.5f)); // test ToHSL with primaries testConvertToHSL((0, 1f, 0.5f, 1f), Colour4.Red); testConvertToHSL((1f / 6f, 1f, 0.5f, 1f), Colour4.Yellow); testConvertToHSL((2f / 6f, 1f, 0.5f, 1f), Colour4.Lime); testConvertToHSL((3f / 6f, 1f, 0.5f, 1f), Colour4.Cyan); testConvertToHSL((4f / 6f, 1f, 0.5f, 1f), Colour4.Blue); testConvertToHSL((5f / 6f, 1f, 0.5f, 1f), Colour4.Magenta); // test ToHSL with some other knowns testConvertToHSL((219f / 360f, 0.792f, 0.661f, 1f), Colour4.CornflowerBlue); testConvertToHSL((34f / 360f, 0.437f, 0.686f, 0.5f), Colour4.Tan.Opacity(0.5f)); } private void testConvertFromHSL(Colour4 expected, (float, float, float, float) convert) => assertAlmostEqual(expected.Vector, Colour4.FromHSL(convert.Item1, convert.Item2, convert.Item3, convert.Item4).Vector); private void testConvertToHSL((float, float, float, float) expected, Colour4 convert) => assertAlmostEqual(new Vector4(expected.Item1, expected.Item2, expected.Item3, expected.Item4), convert.ToHSL(), "HSLA"); [Test] public void TestFromHSV() { // test FromHSV that black is only affected by luminance testConvertFromHSV(Colour4.Black, (0f, 0.5f, 0f, 1f)); testConvertFromHSV(Colour4.Black, (1f, 1f, 0f, 1f)); testConvertFromHSV(Colour4.Black, (0.5f, 0.75f, 0f, 1f)); // test FromHSV that white and grey are not affected by hue testConvertFromHSV(Colour4.White, (0f, 0f, 1f, 1f)); testConvertFromHSV(Colour4.White, (1f, 0f, 1f, 1f)); testConvertFromHSV(Colour4.White, (0.5f, 0f, 1f, 1f)); testConvertFromHSV(Colour4.Gray, (0f, 0f, 0.5f, 1f)); testConvertFromHSV(Colour4.Gray, (0.5f, 0f, 0.5f, 1f)); testConvertFromHSV(Colour4.Gray, (1f, 0f, 0.5f, 1f)); // test FromHSV that alpha is being passed through testConvertFromHSV(Colour4.Black.Opacity(0.5f), (0f, 0f, 0f, 0.5f)); // test FromHSV with primaries testConvertFromHSV(Colour4.Red, (0, 1f, 1f, 1f)); testConvertFromHSV(Colour4.Yellow, (1f / 6f, 1f, 1f, 1f)); testConvertFromHSV(Colour4.Lime, (2f / 6f, 1f, 1f, 1f)); testConvertFromHSV(Colour4.Cyan, (3f / 6f, 1f, 1f, 1f)); testConvertFromHSV(Colour4.Blue, (4f / 6f, 1f, 1f, 1f)); testConvertFromHSV(Colour4.Magenta, (5f / 6f, 1f, 1f, 1f)); testConvertFromHSV(Colour4.Red, (1f, 1f, 1f, 1f)); // test FromHSV with some other knowns testConvertFromHSV(Colour4.CornflowerBlue, (219f / 360f, 0.578f, 0.929f, 1f)); testConvertFromHSV(Colour4.Tan.Opacity(0.5f), (34f / 360f, 0.333f, 0.824f, 0.5f)); } [Test] public void TestToHSV() { // test ToHSV that black, white, and grey always return constant 0f for hue and saturation testConvertToHSV((0f, 0f, 1f, 1f), Colour4.White); testConvertToHSV((0f, 0f, 0f, 1f), Colour4.Black); testConvertToHSV((0f, 0f, 0.5f, 1f), Colour4.Gray); // test ToHSV that alpha is being passed through testConvertToHSV((0f, 0f, 1f, 0.5f), Colour4.White.Opacity(0.5f)); // test ToHSV with primaries testConvertToHSV((0, 1f, 1f, 1f), Colour4.Red); testConvertToHSV((1f / 6f, 1f, 1f, 1f), Colour4.Yellow); testConvertToHSV((2f / 6f, 1f, 1f, 1f), Colour4.Lime); testConvertToHSV((3f / 6f, 1f, 1f, 1f), Colour4.Cyan); testConvertToHSV((4f / 6f, 1f, 1f, 1f), Colour4.Blue); testConvertToHSV((5f / 6f, 1f, 1f, 1f), Colour4.Magenta); // test ToHSV with some other knowns testConvertToHSV((219f / 360f, 0.578f, 0.929f, 1f), Colour4.CornflowerBlue); testConvertToHSV((34f / 360f, 0.333f, 0.824f, 0.5f), Colour4.Tan.Opacity(0.5f)); } private void testConvertFromHSV(Colour4 expected, (float, float, float, float) convert) => assertAlmostEqual(expected.Vector, Colour4.FromHSV(convert.Item1, convert.Item2, convert.Item3, convert.Item4).Vector); private void testConvertToHSV((float, float, float, float) expected, Colour4 convert) => assertAlmostEqual(new Vector4(expected.Item1, expected.Item2, expected.Item3, expected.Item4), convert.ToHSV(), "HSVA"); [Test] public void TestToHex() { Assert.AreEqual("#D2B48C", Colour4.Tan.ToHex()); Assert.AreEqual("#D2B48CFF", Colour4.Tan.ToHex(true)); Assert.AreEqual("#6495ED80", Colour4.CornflowerBlue.Opacity(half_alpha).ToHex()); } private static readonly object[][] valid_hex_colours = { new object[] { Colour4.White, "#fff" }, new object[] { Colour4.Red, "#ff0000" }, new object[] { Colour4.Yellow.Opacity(half_alpha), "ffff0080" }, new object[] { Colour4.Lime.Opacity(half_alpha), "00ff0080" }, new object[] { new Colour4(17, 34, 51, 255), "123" }, new object[] { new Colour4(17, 34, 51, 255), "#123" }, new object[] { new Colour4(17, 34, 51, 68), "1234" }, new object[] { new Colour4(17, 34, 51, 68), "#1234" }, new object[] { new Colour4(18, 52, 86, 255), "123456" }, new object[] { new Colour4(18, 52, 86, 255), "#123456" }, new object[] { new Colour4(18, 52, 86, 120), "12345678" }, new object[] { new Colour4(18, 52, 86, 120), "#12345678" } }; [TestCaseSource(nameof(valid_hex_colours))] public void TestFromHex(Colour4 expectedColour, string hexCode) { Assert.AreEqual(expectedColour, Colour4.FromHex(hexCode)); Assert.True(Colour4.TryParseHex(hexCode, out var actualColour)); Assert.AreEqual(expectedColour, actualColour); } [TestCase("1")] [TestCase("#1")] [TestCase("12")] [TestCase("#12")] [TestCase("12345")] [TestCase("#12345")] [TestCase("1234567")] [TestCase("#1234567")] [TestCase("123456789")] [TestCase("#123456789")] [TestCase("gg00zz")] public void TestFromHexFailsOnInvalidColours(string invalidColour) { // Assert.Catch allows any exception type, contrary to .Throws<T>() (which expects exactly T) Assert.Catch(() => Colour4.FromHex(invalidColour)); Assert.False(Colour4.TryParseHex(invalidColour, out _)); } [Test] public void TestChainingFunctions() { // test that Opacity replaces alpha channel rather than multiplying var expected1 = new Colour4(1f, 0f, 0f, 0.5f); Assert.AreEqual(expected1, Colour4.Red.Opacity(0.5f)); Assert.AreEqual(expected1, expected1.Opacity(0.5f)); // test that MultiplyAlpha multiplies existing alpha channel var expected2 = new Colour4(1f, 0f, 0f, 0.25f); Assert.AreEqual(expected2, expected1.MultiplyAlpha(0.5f)); Assert.Throws<ArgumentOutOfRangeException>(() => Colour4.White.MultiplyAlpha(-1f)); // test clamping all channels in either direction Assert.AreEqual(Colour4.White, new Colour4(1.1f, 1.1f, 1.1f, 1.1f).Clamped()); Assert.AreEqual(Colour4.Black.Opacity(0f), new Colour4(-1.1f, -1.1f, -1.1f, -1.1f).Clamped()); // test lighten and darken assertAlmostEqual(new Colour4(0.431f, 0.642f, 1f, 1f).Vector, Colour4.CornflowerBlue.Lighten(0.1f).Vector); assertAlmostEqual(new Colour4(0.356f, 0.531f, 0.845f, 1f).Vector, Colour4.CornflowerBlue.Darken(0.1f).Vector); } [Test] public void TestOperators() { var colour = new Colour4(0.5f, 0.5f, 0.5f, 0.5f); assertAlmostEqual(new Vector4(0.6f, 0.7f, 0.8f, 0.9f), (colour + new Colour4(0.1f, 0.2f, 0.3f, 0.4f)).Vector); assertAlmostEqual(new Vector4(0.4f, 0.3f, 0.2f, 0.1f), (colour - new Colour4(0.1f, 0.2f, 0.3f, 0.4f)).Vector); assertAlmostEqual(new Vector4(0.25f, 0.25f, 0.25f, 0.25f), (colour * colour).Vector); assertAlmostEqual(new Vector4(0.25f, 0.25f, 0.25f, 0.25f), (colour / 2f).Vector); assertAlmostEqual(Colour4.White.Vector, (colour * 2f).Vector); Assert.Throws<ArgumentOutOfRangeException>(() => _ = colour * -1f); Assert.Throws<ArgumentOutOfRangeException>(() => _ = colour / -1f); Assert.Throws<ArgumentOutOfRangeException>(() => _ = colour / 0f); } [Test] public void TestOtherConversions() { // test uint conversions Assert.AreEqual(0x6495ED80, Colour4.CornflowerBlue.Opacity(half_alpha).ToRGBA()); Assert.AreEqual(0x806495ED, Colour4.CornflowerBlue.Opacity(half_alpha).ToARGB()); Assert.AreEqual(Colour4.CornflowerBlue.Opacity(half_alpha), Colour4.FromRGBA(0x6495ED80)); Assert.AreEqual(Colour4.CornflowerBlue.Opacity(half_alpha), Colour4.FromARGB(0x806495ED)); // test SRGB var srgb = new Vector4(0.659f, 0.788f, 0.968f, 1f); assertAlmostEqual(srgb, Colour4.CornflowerBlue.ToSRGB().Vector); assertAlmostEqual(Colour4.CornflowerBlue.Vector, new Colour4(srgb).ToLinear().Vector); } private void assertAlmostEqual(Vector4 expected, Vector4 actual, string type = "RGBA") { // note that we use a fairly high delta since the test constants are approximations const float delta = 0.005f; var message = $"({type}) Expected: {expected}, Actual: {actual}"; Assert.AreEqual(expected.X, actual.X, delta, message); Assert.AreEqual(expected.Y, actual.Y, delta, message); Assert.AreEqual(expected.Z, actual.Z, delta, message); Assert.AreEqual(expected.W, actual.W, delta, message); } // 0x80 alpha is slightly more than half private const float half_alpha = 128f / 255f; } }
/* * 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.Reflection; using OpenSim.Data; using OpenSim.Framework; using MySql.Data.MySqlClient; using OpenMetaverse; using OpenMetaverse.StructuredData; using log4net; namespace OpenSim.Data.MySQL { public class UserProfilesData: IProfilesData { static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #region Properites string ConnectionString { get; set; } protected object Lock { get; set; } protected virtual Assembly Assembly { get { return GetType().Assembly; } } #endregion Properties #region class Member Functions public UserProfilesData(string connectionString) { ConnectionString = connectionString; Init(); } void Init() { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); Migration m = new Migration(dbcon, Assembly, "UserProfiles"); m.Update(); } } #endregion Member Functions #region Classifieds Queries /// <summary> /// Gets the classified records. /// </summary> /// <returns> /// Array of classified records /// </returns> /// <param name='creatorId'> /// Creator identifier. /// </param> public OSDArray GetClassifiedRecords(UUID creatorId) { OSDArray data = new OSDArray(); using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { string query = "SELECT classifieduuid, name FROM classifieds WHERE creatoruuid = ?Id"; dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?Id", creatorId); using( MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default)) { if(reader.HasRows) { while (reader.Read()) { OSDMap n = new OSDMap(); UUID Id = UUID.Zero; string Name = null; try { UUID.TryParse(Convert.ToString( reader["classifieduuid"]), out Id); Name = Convert.ToString(reader["name"]); } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": UserAccount exception {0}", e.Message); } n.Add("classifieduuid", OSD.FromUUID(Id)); n.Add("name", OSD.FromString(Name)); data.Add(n); } } } } } return data; } public bool UpdateClassifiedRecord(UserClassifiedAdd ad, ref string result) { string query = string.Empty; query += "INSERT INTO classifieds ("; query += "`classifieduuid`,"; query += "`creatoruuid`,"; query += "`creationdate`,"; query += "`expirationdate`,"; query += "`category`,"; query += "`name`,"; query += "`description`,"; query += "`parceluuid`,"; query += "`parentestate`,"; query += "`snapshotuuid`,"; query += "`simname`,"; query += "`posglobal`,"; query += "`parcelname`,"; query += "`classifiedflags`,"; query += "`priceforlisting`) "; query += "VALUES ("; query += "?ClassifiedId,"; query += "?CreatorId,"; query += "?CreatedDate,"; query += "?ExpirationDate,"; query += "?Category,"; query += "?Name,"; query += "?Description,"; query += "?ParcelId,"; query += "?ParentEstate,"; query += "?SnapshotId,"; query += "?SimName,"; query += "?GlobalPos,"; query += "?ParcelName,"; query += "?Flags,"; query += "?ListingPrice ) "; query += "ON DUPLICATE KEY UPDATE "; query += "category=?Category, "; query += "expirationdate=?ExpirationDate, "; query += "name=?Name, "; query += "description=?Description, "; query += "parentestate=?ParentEstate, "; query += "posglobal=?GlobalPos, "; query += "parcelname=?ParcelName, "; query += "classifiedflags=?Flags, "; query += "priceforlisting=?ListingPrice, "; query += "snapshotuuid=?SnapshotId"; if(string.IsNullOrEmpty(ad.ParcelName)) ad.ParcelName = "Unknown"; if(ad.ParcelId == null) ad.ParcelId = UUID.Zero; if(string.IsNullOrEmpty(ad.Description)) ad.Description = "No Description"; DateTime epoch = new DateTime(1970, 1, 1); DateTime now = DateTime.Now; TimeSpan epochnow = now - epoch; TimeSpan duration; DateTime expiration; TimeSpan epochexp; if(ad.Flags == 2) { duration = new TimeSpan(7,0,0,0); expiration = now.Add(duration); epochexp = expiration - epoch; } else { duration = new TimeSpan(365,0,0,0); expiration = now.Add(duration); epochexp = expiration - epoch; } ad.CreationDate = (int)epochnow.TotalSeconds; ad.ExpirationDate = (int)epochexp.TotalSeconds; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?ClassifiedId", ad.ClassifiedId.ToString()); cmd.Parameters.AddWithValue("?CreatorId", ad.CreatorId.ToString()); cmd.Parameters.AddWithValue("?CreatedDate", ad.CreationDate.ToString()); cmd.Parameters.AddWithValue("?ExpirationDate", ad.ExpirationDate.ToString()); cmd.Parameters.AddWithValue("?Category", ad.Category.ToString()); cmd.Parameters.AddWithValue("?Name", ad.Name.ToString()); cmd.Parameters.AddWithValue("?Description", ad.Description.ToString()); cmd.Parameters.AddWithValue("?ParcelId", ad.ParcelId.ToString()); cmd.Parameters.AddWithValue("?ParentEstate", ad.ParentEstate.ToString()); cmd.Parameters.AddWithValue("?SnapshotId", ad.SnapshotId.ToString ()); cmd.Parameters.AddWithValue("?SimName", ad.SimName.ToString()); cmd.Parameters.AddWithValue("?GlobalPos", ad.GlobalPos.ToString()); cmd.Parameters.AddWithValue("?ParcelName", ad.ParcelName.ToString()); cmd.Parameters.AddWithValue("?Flags", ad.Flags.ToString()); cmd.Parameters.AddWithValue("?ListingPrice", ad.Price.ToString ()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": ClassifiedesUpdate exception {0}", e.Message); result = e.Message; return false; } return true; } public bool DeleteClassifiedRecord(UUID recordId) { string query = string.Empty; query += "DELETE FROM classifieds WHERE "; query += "classifieduuid = ?ClasifiedId"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?ClassifiedId", recordId.ToString()); lock(Lock) { cmd.ExecuteNonQuery(); } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": DeleteClassifiedRecord exception {0}", e.Message); return false; } return true; } public bool GetClassifiedInfo(ref UserClassifiedAdd ad, ref string result) { string query = string.Empty; query += "SELECT * FROM classifieds WHERE "; query += "classifieduuid = ?AdId"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?AdId", ad.ClassifiedId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader()) { if(reader.Read ()) { ad.CreatorId = new UUID(reader.GetGuid("creatoruuid")); ad.ParcelId = new UUID(reader.GetGuid("parceluuid")); ad.SnapshotId = new UUID(reader.GetGuid("snapshotuuid")); ad.CreationDate = Convert.ToInt32(reader["creationdate"]); ad.ExpirationDate = Convert.ToInt32(reader["expirationdate"]); ad.ParentEstate = Convert.ToInt32(reader["parentestate"]); ad.Flags = (byte)reader.GetUInt32("classifiedflags"); ad.Category = reader.GetInt32("category"); ad.Price = reader.GetInt16("priceforlisting"); ad.Name = reader.GetString("name"); ad.Description = reader.GetString("description"); ad.SimName = reader.GetString("simname"); ad.GlobalPos = reader.GetString("posglobal"); ad.ParcelName = reader.GetString("parcelname"); } } } dbcon.Close(); } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": GetPickInfo exception {0}", e.Message); } return true; } #endregion Classifieds Queries #region Picks Queries public OSDArray GetAvatarPicks(UUID avatarId) { string query = string.Empty; query += "SELECT `pickuuid`,`name` FROM userpicks WHERE "; query += "creatoruuid = ?Id"; OSDArray data = new OSDArray(); try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?Id", avatarId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader()) { if(reader.HasRows) { while (reader.Read()) { OSDMap record = new OSDMap(); record.Add("pickuuid",OSD.FromString((string)reader["pickuuid"])); record.Add("name",OSD.FromString((string)reader["name"])); data.Add(record); } } } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": GetAvatarPicks exception {0}", e.Message); } return data; } public UserProfilePick GetPickInfo(UUID avatarId, UUID pickId) { string query = string.Empty; UserProfilePick pick = new UserProfilePick(); query += "SELECT * FROM userpicks WHERE "; query += "creatoruuid = ?CreatorId AND "; query += "pickuuid = ?PickId"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?CreatorId", avatarId.ToString()); cmd.Parameters.AddWithValue("?PickId", pickId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader()) { if(reader.HasRows) { reader.Read(); string description = (string)reader["description"]; if (string.IsNullOrEmpty(description)) description = "No description given."; UUID.TryParse((string)reader["pickuuid"], out pick.PickId); UUID.TryParse((string)reader["creatoruuid"], out pick.CreatorId); UUID.TryParse((string)reader["parceluuid"], out pick.ParcelId); UUID.TryParse((string)reader["snapshotuuid"], out pick.SnapshotId); pick.GlobalPos = (string)reader["posglobal"]; bool.TryParse((string)reader["toppick"], out pick.TopPick); bool.TryParse((string)reader["enabled"], out pick.Enabled); pick.Name = (string)reader["name"]; pick.Desc = description; pick.User = (string)reader["user"]; pick.OriginalName = (string)reader["originalname"]; pick.SimName = (string)reader["simname"]; pick.SortOrder = (int)reader["sortorder"]; } } } dbcon.Close(); } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": GetPickInfo exception {0}", e.Message); } return pick; } public bool UpdatePicksRecord(UserProfilePick pick) { string query = string.Empty; query += "INSERT INTO userpicks VALUES ("; query += "?PickId,"; query += "?CreatorId,"; query += "?TopPick,"; query += "?ParcelId,"; query += "?Name,"; query += "?Desc,"; query += "?SnapshotId,"; query += "?User,"; query += "?Original,"; query += "?SimName,"; query += "?GlobalPos,"; query += "?SortOrder,"; query += "?Enabled) "; query += "ON DUPLICATE KEY UPDATE "; query += "parceluuid=?ParcelId,"; query += "name=?Name,"; query += "description=?Desc,"; query += "snapshotuuid=?SnapshotId,"; query += "pickuuid=?PickId,"; query += "posglobal=?GlobalPos"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?PickId", pick.PickId.ToString()); cmd.Parameters.AddWithValue("?CreatorId", pick.CreatorId.ToString()); cmd.Parameters.AddWithValue("?TopPick", pick.TopPick.ToString()); cmd.Parameters.AddWithValue("?ParcelId", pick.ParcelId.ToString()); cmd.Parameters.AddWithValue("?Name", pick.Name.ToString()); cmd.Parameters.AddWithValue("?Desc", pick.Desc.ToString()); cmd.Parameters.AddWithValue("?SnapshotId", pick.SnapshotId.ToString()); cmd.Parameters.AddWithValue("?User", pick.User.ToString()); cmd.Parameters.AddWithValue("?Original", pick.OriginalName.ToString()); cmd.Parameters.AddWithValue("?SimName",pick.SimName.ToString()); cmd.Parameters.AddWithValue("?GlobalPos", pick.GlobalPos); cmd.Parameters.AddWithValue("?SortOrder", pick.SortOrder.ToString ()); cmd.Parameters.AddWithValue("?Enabled", pick.Enabled.ToString()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": UpdateAvatarNotes exception {0}", e.Message); return false; } return true; } public bool DeletePicksRecord(UUID pickId) { string query = string.Empty; query += "DELETE FROM userpicks WHERE "; query += "pickuuid = ?PickId"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?PickId", pickId.ToString()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": DeleteUserPickRecord exception {0}", e.Message); return false; } return true; } #endregion Picks Queries #region Avatar Notes Queries public bool GetAvatarNotes(ref UserProfileNotes notes) { // WIP string query = string.Empty; query += "SELECT `notes` FROM usernotes WHERE "; query += "useruuid = ?Id AND "; query += "targetuuid = ?TargetId"; OSDArray data = new OSDArray(); try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?Id", notes.UserId.ToString()); cmd.Parameters.AddWithValue("?TargetId", notes.TargetId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.HasRows) { reader.Read(); notes.Notes = OSD.FromString((string)reader["notes"]); } } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": GetAvatarNotes exception {0}", e.Message); } return true; } public bool UpdateAvatarNotes(ref UserProfileNotes note, ref string result) { string query = string.Empty; bool remove; if(string.IsNullOrEmpty(note.Notes)) { remove = true; query += "DELETE FROM usernotes WHERE "; query += "useruuid=?UserId AND "; query += "targetuuid=?TargetId"; } else { remove = false; query += "INSERT INTO usernotes VALUES ( "; query += "?UserId,"; query += "?TargetId,"; query += "?Notes )"; query += "ON DUPLICATE KEY "; query += "UPDATE "; query += "notes=?Notes"; } try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { if(!remove) cmd.Parameters.AddWithValue("?Notes", note.Notes); cmd.Parameters.AddWithValue("?TargetId", note.TargetId.ToString ()); cmd.Parameters.AddWithValue("?UserId", note.UserId.ToString()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": UpdateAvatarNotes exception {0}", e.Message); return false; } return true; } #endregion Avatar Notes Queries #region Avatar Properties public bool GetAvatarProperties(ref UserProfileProperties props, ref string result) { string query = string.Empty; query += "SELECT * FROM userprofile WHERE "; query += "useruuid = ?Id"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?Id", props.UserId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.HasRows) { m_log.DebugFormat("[PROFILES_DATA]" + ": Getting data for {0}.", props.UserId); reader.Read(); props.WebUrl = (string)reader["profileURL"]; UUID.TryParse((string)reader["profileImage"], out props.ImageId); props.AboutText = (string)reader["profileAboutText"]; UUID.TryParse((string)reader["profileFirstImage"], out props.FirstLifeImageId); props.FirstLifeText = (string)reader["profileFirstText"]; UUID.TryParse((string)reader["profilePartner"], out props.PartnerId); props.WantToMask = (int)reader["profileWantToMask"]; props.WantToText = (string)reader["profileWantToText"]; props.SkillsMask = (int)reader["profileSkillsMask"]; props.SkillsText = (string)reader["profileSkillsText"]; props.Language = (string)reader["profileLanguages"]; } else { m_log.DebugFormat("[PROFILES_DATA]" + ": No data for {0}", props.UserId); props.WebUrl = string.Empty; props.ImageId = UUID.Zero; props.AboutText = string.Empty; props.FirstLifeImageId = UUID.Zero; props.FirstLifeText = string.Empty; props.PartnerId = UUID.Zero; props.WantToMask = 0; props.WantToText = string.Empty; props.SkillsMask = 0; props.SkillsText = string.Empty; props.Language = string.Empty; props.PublishProfile = false; props.PublishMature = false; query = "INSERT INTO userprofile ("; query += "useruuid, "; query += "profilePartner, "; query += "profileAllowPublish, "; query += "profileMaturePublish, "; query += "profileURL, "; query += "profileWantToMask, "; query += "profileWantToText, "; query += "profileSkillsMask, "; query += "profileSkillsText, "; query += "profileLanguages, "; query += "profileImage, "; query += "profileAboutText, "; query += "profileFirstImage, "; query += "profileFirstText) VALUES ("; query += "?userId, "; query += "?profilePartner, "; query += "?profileAllowPublish, "; query += "?profileMaturePublish, "; query += "?profileURL, "; query += "?profileWantToMask, "; query += "?profileWantToText, "; query += "?profileSkillsMask, "; query += "?profileSkillsText, "; query += "?profileLanguages, "; query += "?profileImage, "; query += "?profileAboutText, "; query += "?profileFirstImage, "; query += "?profileFirstText)"; dbcon.Close(); dbcon.Open(); using (MySqlCommand put = new MySqlCommand(query, dbcon)) { put.Parameters.AddWithValue("?userId", props.UserId.ToString()); put.Parameters.AddWithValue("?profilePartner", props.PartnerId.ToString()); put.Parameters.AddWithValue("?profileAllowPublish", props.PublishProfile); put.Parameters.AddWithValue("?profileMaturePublish", props.PublishMature); put.Parameters.AddWithValue("?profileURL", props.WebUrl); put.Parameters.AddWithValue("?profileWantToMask", props.WantToMask); put.Parameters.AddWithValue("?profileWantToText", props.WantToText); put.Parameters.AddWithValue("?profileSkillsMask", props.SkillsMask); put.Parameters.AddWithValue("?profileSkillsText", props.SkillsText); put.Parameters.AddWithValue("?profileLanguages", props.Language); put.Parameters.AddWithValue("?profileImage", props.ImageId.ToString()); put.Parameters.AddWithValue("?profileAboutText", props.AboutText); put.Parameters.AddWithValue("?profileFirstImage", props.FirstLifeImageId.ToString()); put.Parameters.AddWithValue("?profileFirstText", props.FirstLifeText); put.ExecuteNonQuery(); } } } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": Requst properties exception {0}", e.Message); result = e.Message; return false; } return true; } public bool UpdateAvatarProperties(ref UserProfileProperties props, ref string result) { string query = string.Empty; query += "UPDATE userprofile SET "; query += "profilePartner=?profilePartner, "; query += "profileURL=?profileURL, "; query += "profileImage=?image, "; query += "profileAboutText=?abouttext,"; query += "profileFirstImage=?firstlifeimage,"; query += "profileFirstText=?firstlifetext "; query += "WHERE useruuid=?uuid"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?profileURL", props.WebUrl); cmd.Parameters.AddWithValue("?profilePartner", props.PartnerId.ToString()); cmd.Parameters.AddWithValue("?image", props.ImageId.ToString()); cmd.Parameters.AddWithValue("?abouttext", props.AboutText); cmd.Parameters.AddWithValue("?firstlifeimage", props.FirstLifeImageId.ToString()); cmd.Parameters.AddWithValue("?firstlifetext", props.FirstLifeText); cmd.Parameters.AddWithValue("?uuid", props.UserId.ToString()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": AgentPropertiesUpdate exception {0}", e.Message); return false; } return true; } #endregion Avatar Properties #region Avatar Interests public bool UpdateAvatarInterests(UserProfileProperties up, ref string result) { string query = string.Empty; query += "UPDATE userprofile SET "; query += "profileWantToMask=?WantMask, "; query += "profileWantToText=?WantText,"; query += "profileSkillsMask=?SkillsMask,"; query += "profileSkillsText=?SkillsText, "; query += "profileLanguages=?Languages "; query += "WHERE useruuid=?uuid"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?WantMask", up.WantToMask); cmd.Parameters.AddWithValue("?WantText", up.WantToText); cmd.Parameters.AddWithValue("?SkillsMask", up.SkillsMask); cmd.Parameters.AddWithValue("?SkillsText", up.SkillsText); cmd.Parameters.AddWithValue("?Languages", up.Language); cmd.Parameters.AddWithValue("?uuid", up.UserId.ToString()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": AgentInterestsUpdate exception {0}", e.Message); result = e.Message; return false; } return true; } #endregion Avatar Interests public OSDArray GetUserImageAssets(UUID avatarId) { OSDArray data = new OSDArray(); string query = "SELECT `snapshotuuid` FROM {0} WHERE `creatoruuid` = ?Id"; // Get classified image assets try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(string.Format (query,"`classifieds`"), dbcon)) { cmd.Parameters.AddWithValue("?Id", avatarId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.HasRows) { while (reader.Read()) { data.Add(new OSDString((string)reader["snapshotuuid"].ToString ())); } } } } dbcon.Close(); dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(string.Format (query,"`userpicks`"), dbcon)) { cmd.Parameters.AddWithValue("?Id", avatarId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.HasRows) { while (reader.Read()) { data.Add(new OSDString((string)reader["snapshotuuid"].ToString ())); } } } } dbcon.Close(); dbcon.Open(); query = "SELECT `profileImage`, `profileFirstImage` FROM `userprofile` WHERE `useruuid` = ?Id"; using (MySqlCommand cmd = new MySqlCommand(string.Format (query,"`userpicks`"), dbcon)) { cmd.Parameters.AddWithValue("?Id", avatarId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.HasRows) { while (reader.Read()) { data.Add(new OSDString((string)reader["profileImage"].ToString ())); data.Add(new OSDString((string)reader["profileFirstImage"].ToString ())); } } } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": GetAvatarNotes exception {0}", e.Message); } return data; } #region User Preferences public OSDArray GetUserPreferences(UUID avatarId) { string query = string.Empty; query += "SELECT imviaemail,visible,email FROM "; query += "usersettings WHERE "; query += "useruuid = ?Id"; OSDArray data = new OSDArray(); try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?Id", avatarId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader()) { if(reader.HasRows) { reader.Read(); OSDMap record = new OSDMap(); record.Add("imviaemail",OSD.FromString((string)reader["imviaemail"])); record.Add("visible",OSD.FromString((string)reader["visible"])); record.Add("email",OSD.FromString((string)reader["email"])); data.Add(record); } else { using (MySqlCommand put = new MySqlCommand(query, dbcon)) { query = "INSERT INTO usersettings VALUES "; query += "(?Id,'false','false', '')"; lock(Lock) { put.ExecuteNonQuery(); } } } } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": Get preferences exception {0}", e.Message); } return data; } public bool UpdateUserPreferences(bool emailIm, bool visible, UUID avatarId ) { string query = string.Empty; query += "UPDATE userpsettings SET "; query += "imviaemail=?ImViaEmail, "; query += "visible=?Visible,"; query += "WHERE useruuid=?uuid"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?ImViaEmail", emailIm.ToString().ToLower ()); cmd.Parameters.AddWithValue("?WantText", visible.ToString().ToLower ()); cmd.Parameters.AddWithValue("?uuid", avatarId.ToString()); lock(Lock) { cmd.ExecuteNonQuery(); } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": AgentInterestsUpdate exception {0}", e.Message); return false; } return true; } #endregion User Preferences #region Integration public bool GetUserAppData(ref UserAppData props, ref string result) { string query = string.Empty; query += "SELECT * FROM `userdata` WHERE "; query += "UserId = ?Id AND "; query += "TagId = ?TagId"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?Id", props.UserId.ToString()); cmd.Parameters.AddWithValue ("?TagId", props.TagId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.HasRows) { reader.Read(); props.DataKey = (string)reader["DataKey"]; props.DataVal = (string)reader["DataVal"]; } else { query += "INSERT INTO userdata VALUES ( "; query += "?UserId,"; query += "?TagId,"; query += "?DataKey,"; query += "?DataVal) "; using (MySqlCommand put = new MySqlCommand(query, dbcon)) { put.Parameters.AddWithValue("?Id", props.UserId.ToString()); put.Parameters.AddWithValue("?TagId", props.TagId.ToString()); put.Parameters.AddWithValue("?DataKey", props.DataKey.ToString()); put.Parameters.AddWithValue("?DataVal", props.DataVal.ToString()); lock(Lock) { put.ExecuteNonQuery(); } } } } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": Requst application data exception {0}", e.Message); result = e.Message; return false; } return true; } public bool SetUserAppData(UserAppData props, ref string result) { string query = string.Empty; query += "UPDATE userdata SET "; query += "TagId = ?TagId, "; query += "DataKey = ?DataKey, "; query += "DataVal = ?DataVal WHERE "; query += "UserId = ?UserId AND "; query += "TagId = ?TagId"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?UserId", props.UserId.ToString()); cmd.Parameters.AddWithValue("?TagId", props.TagId.ToString ()); cmd.Parameters.AddWithValue("?DataKey", props.DataKey.ToString ()); cmd.Parameters.AddWithValue("?DataVal", props.DataKey.ToString ()); lock(Lock) { cmd.ExecuteNonQuery(); } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": SetUserData exception {0}", e.Message); return false; } return true; } #endregion Integration } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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. * */ #region Import using System; using System.Collections.Generic; using System.Runtime.Serialization; using ASC.Api.Employee; using ASC.CRM.Core; using ASC.CRM.Core.Entities; using ASC.Specific; using ASC.Web.CRM.Classes; #endregion namespace ASC.Api.CRM.Wrappers { /// <summary> /// Invoice /// </summary> [DataContract(Name = "invoiceBase", Namespace = "")] public class InvoiceBaseWrapper : ObjectWrapperBase { public InvoiceBaseWrapper(int id) : base(id) { } public InvoiceBaseWrapper(Invoice invoice) : base(invoice.ID) { Status = new InvoiceStatusWrapper(invoice.Status); Number = invoice.Number; IssueDate = (ApiDateTime)invoice.IssueDate; TemplateType = invoice.TemplateType; DueDate = (ApiDateTime)invoice.DueDate; Currency = !String.IsNullOrEmpty(invoice.Currency) ? new CurrencyInfoWrapper(CurrencyProvider.Get(invoice.Currency)) : new CurrencyInfoWrapper(Global.TenantSettings.DefaultCurrency); ExchangeRate = invoice.ExchangeRate; Language = invoice.Language; PurchaseOrderNumber = invoice.PurchaseOrderNumber; Terms = invoice.Terms; Description = invoice.Description; FileID = invoice.FileID; CreateOn = (ApiDateTime)invoice.CreateOn; CreateBy = EmployeeWraper.Get(invoice.CreateBy); CanEdit = CRMSecurity.CanEdit(invoice); CanDelete = CRMSecurity.CanDelete(invoice); } [DataMember] public InvoiceStatusWrapper Status { get; set; } [DataMember] public string Number { get; set; } [DataMember] public ApiDateTime IssueDate { get; set; } [DataMember] public InvoiceTemplateType TemplateType { get; set; } [DataMember] public ContactBaseWrapper Contact { get; set; } [DataMember] public ContactBaseWrapper Consignee { get; set; } [DataMember] public EntityWrapper Entity { get; set; } [DataMember] public ApiDateTime DueDate { get; set; } [DataMember] public string Language { get; set; } [DataMember] public CurrencyInfoWrapper Currency { get; set; } [DataMember] public decimal ExchangeRate { get; set; } [DataMember] public string PurchaseOrderNumber { get; set; } [DataMember] public string Terms { get; set; } [DataMember] public string Description { get; set; } [DataMember] public int FileID { get; set; } [DataMember] public ApiDateTime CreateOn { get; set; } [DataMember] public EmployeeWraper CreateBy { get; set; } [DataMember] public decimal Cost { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public bool CanEdit { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public bool CanDelete { get; set; } } /// <summary> /// Invoice /// </summary> [DataContract(Name = "invoice", Namespace = "")] public class InvoiceWrapper : InvoiceBaseWrapper { public InvoiceWrapper(int id) : base(id) { } public InvoiceWrapper(Invoice invoice) : base(invoice.ID) { Status = new InvoiceStatusWrapper(invoice.Status); Number = invoice.Number; IssueDate = (ApiDateTime)invoice.IssueDate; TemplateType = invoice.TemplateType; DueDate = (ApiDateTime)invoice.DueDate; Currency = !String.IsNullOrEmpty(invoice.Currency) ? new CurrencyInfoWrapper(CurrencyProvider.Get(invoice.Currency)) : new CurrencyInfoWrapper(Global.TenantSettings.DefaultCurrency); ExchangeRate = invoice.ExchangeRate; Language = invoice.Language; PurchaseOrderNumber = invoice.PurchaseOrderNumber; Terms = invoice.Terms; Description = invoice.Description; FileID = invoice.FileID; CreateOn = (ApiDateTime)invoice.CreateOn; CreateBy = EmployeeWraper.Get(invoice.CreateBy); CanEdit = CRMSecurity.CanEdit(invoice); CanDelete = CRMSecurity.CanDelete(invoice); } [DataMember] public List<InvoiceLineWrapper> InvoiceLines { get; set; } public static InvoiceWrapper GetSample() { return new InvoiceWrapper(0) { Status = new InvoiceStatusWrapper(InvoiceStatus.Draft), Number = string.Empty, IssueDate = ApiDateTime.GetSample(), TemplateType = InvoiceTemplateType.Eur, Language = string.Empty, DueDate = ApiDateTime.GetSample(), Currency = CurrencyInfoWrapper.GetSample(), ExchangeRate = (decimal)1.00, PurchaseOrderNumber = string.Empty, Terms = string.Empty, Description = string.Empty, FileID = -1, CreateOn = ApiDateTime.GetSample(), CreateBy = EmployeeWraper.GetSample(), CanEdit = true, CanDelete = true, Cost = 0, InvoiceLines = new List<InvoiceLineWrapper> { InvoiceLineWrapper.GetSample() } }; } } /// <summary> /// Invoice Item /// </summary> [DataContract(Name = "invoiceItem", Namespace = "")] public class InvoiceItemWrapper : ObjectWrapperBase { public InvoiceItemWrapper(int id) : base(id) { } public InvoiceItemWrapper(InvoiceItem invoiceItem) : base(invoiceItem.ID) { Title = invoiceItem.Title; StockKeepingUnit = invoiceItem.StockKeepingUnit; Description = invoiceItem.Description; Price = invoiceItem.Price; StockQuantity = invoiceItem.StockQuantity; TrackInvenory = invoiceItem.TrackInventory; CreateOn = (ApiDateTime)invoiceItem.CreateOn; CreateBy = EmployeeWraper.Get(invoiceItem.CreateBy); Currency = !String.IsNullOrEmpty(invoiceItem.Currency) ? new CurrencyInfoWrapper(CurrencyProvider.Get(invoiceItem.Currency)) : new CurrencyInfoWrapper(Global.TenantSettings.DefaultCurrency); CanEdit = CRMSecurity.CanEdit(invoiceItem); CanDelete = CRMSecurity.CanDelete(invoiceItem); } [DataMember] public string Title { get; set; } [DataMember] public string StockKeepingUnit { get; set; } [DataMember] public string Description { get; set; } [DataMember] public decimal Price { get; set; } [DataMember] public CurrencyInfoWrapper Currency { get; set; } [DataMember] public decimal StockQuantity { get; set; } [DataMember] public bool TrackInvenory { get; set; } [DataMember] public InvoiceTaxWrapper InvoiceTax1 { get; set; } [DataMember] public InvoiceTaxWrapper InvoiceTax2 { get; set; } [DataMember] public ApiDateTime CreateOn { get; set; } [DataMember] public EmployeeWraper CreateBy { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public bool CanEdit { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public bool CanDelete { get; set; } } /// <summary> /// Invoice Tax /// </summary> [DataContract(Name = "invoiceTax", Namespace = "")] public class InvoiceTaxWrapper : ObjectWrapperBase { public InvoiceTaxWrapper(int id) : base(id) { } public InvoiceTaxWrapper(InvoiceTax invoiceTax) : base(invoiceTax.ID) { Name = invoiceTax.Name; Description = invoiceTax.Description; Rate = invoiceTax.Rate; CreateOn = (ApiDateTime)invoiceTax.CreateOn; CreateBy = EmployeeWraper.Get(invoiceTax.CreateBy); CanEdit = CRMSecurity.CanEdit(invoiceTax); CanDelete = CRMSecurity.CanDelete(invoiceTax); } [DataMember] public string Name { get; set; } [DataMember] public string Description { get; set; } [DataMember] public decimal Rate { get; set; } [DataMember] public ApiDateTime CreateOn { get; set; } [DataMember] public EmployeeWraper CreateBy { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public bool CanEdit { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public bool CanDelete { get; set; } } /// <summary> /// Invoice Line /// </summary> [DataContract(Name = "invoiceLine", Namespace = "")] public class InvoiceLineWrapper : ObjectWrapperBase { public InvoiceLineWrapper(int id) : base(id) { } public InvoiceLineWrapper(InvoiceLine invoiceLine) : base(invoiceLine.ID) { InvoiceID = invoiceLine.InvoiceID; InvoiceItemID = invoiceLine.InvoiceItemID; InvoiceTax1ID = invoiceLine.InvoiceTax1ID; InvoiceTax2ID = invoiceLine.InvoiceTax2ID; SortOrder = invoiceLine.SortOrder; Description = invoiceLine.Description; Quantity = invoiceLine.Quantity; Price = invoiceLine.Price; Discount = invoiceLine.Discount; } [DataMember] public int InvoiceID { get; set; } [DataMember] public int InvoiceItemID { get; set; } [DataMember] public int InvoiceTax1ID { get; set; } [DataMember] public int InvoiceTax2ID { get; set; } [DataMember] public int SortOrder { get; set; } [DataMember] public string Description { get; set; } [DataMember] public decimal Quantity { get; set; } [DataMember] public decimal Price { get; set; } [DataMember] public decimal Discount { get; set; } public static InvoiceLineWrapper GetSample() { return new InvoiceLineWrapper(0) { Description = string.Empty, Discount = (decimal)0.00, InvoiceID = 0, InvoiceItemID = 0, InvoiceTax1ID = 0, InvoiceTax2ID = 0, Price = (decimal)0.00, Quantity = (decimal)0.00 }; } } /// <summary> /// Invoice Status /// </summary> [DataContract(Name = "invoiceStatus", Namespace = "")] public class InvoiceStatusWrapper : ObjectWrapperBase { public InvoiceStatusWrapper(int id) : base(id) { Title = ((InvoiceStatus)id).ToLocalizedString(); } public InvoiceStatusWrapper(InvoiceStatus status) : base((int)status) { Title = status.ToLocalizedString(); } [DataMember] public string Title { get; set; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using lro = Google.LongRunning; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using 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.ResourceManager.V3 { /// <summary>Settings for <see cref="TagBindingsClient"/> instances.</summary> public sealed partial class TagBindingsSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="TagBindingsSettings"/>.</summary> /// <returns>A new instance of the default <see cref="TagBindingsSettings"/>.</returns> public static TagBindingsSettings GetDefault() => new TagBindingsSettings(); /// <summary>Constructs a new <see cref="TagBindingsSettings"/> object with default settings.</summary> public TagBindingsSettings() { } private TagBindingsSettings(TagBindingsSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); ListTagBindingsSettings = existing.ListTagBindingsSettings; CreateTagBindingSettings = existing.CreateTagBindingSettings; CreateTagBindingOperationsSettings = existing.CreateTagBindingOperationsSettings.Clone(); DeleteTagBindingSettings = existing.DeleteTagBindingSettings; DeleteTagBindingOperationsSettings = existing.DeleteTagBindingOperationsSettings.Clone(); OnCopy(existing); } partial void OnCopy(TagBindingsSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>TagBindingsClient.ListTagBindings</c> and <c>TagBindingsClient.ListTagBindingsAsync</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: 5</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 ListTagBindingsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 5, 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>TagBindingsClient.CreateTagBinding</c> and <c>TagBindingsClient.CreateTagBindingAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings CreateTagBindingSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary> /// Long Running Operation settings for calls to <c>TagBindingsClient.CreateTagBinding</c> and /// <c>TagBindingsClient.CreateTagBindingAsync</c>. /// </summary> /// <remarks> /// Uses default <see cref="gax::PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20 seconds.</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45 seconds.</description></item> /// <item><description>Total timeout: 24 hours.</description></item> /// </list> /// </remarks> public lro::OperationsSettings CreateTagBindingOperationsSettings { get; set; } = new lro::OperationsSettings { DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)), }; /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>TagBindingsClient.DeleteTagBinding</c> and <c>TagBindingsClient.DeleteTagBindingAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings DeleteTagBindingSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary> /// Long Running Operation settings for calls to <c>TagBindingsClient.DeleteTagBinding</c> and /// <c>TagBindingsClient.DeleteTagBindingAsync</c>. /// </summary> /// <remarks> /// Uses default <see cref="gax::PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20 seconds.</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45 seconds.</description></item> /// <item><description>Total timeout: 24 hours.</description></item> /// </list> /// </remarks> public lro::OperationsSettings DeleteTagBindingOperationsSettings { get; set; } = new lro::OperationsSettings { DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)), }; /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="TagBindingsSettings"/> object.</returns> public TagBindingsSettings Clone() => new TagBindingsSettings(this); } /// <summary> /// Builder class for <see cref="TagBindingsClient"/> to provide simple configuration of credentials, endpoint etc. /// </summary> public sealed partial class TagBindingsClientBuilder : gaxgrpc::ClientBuilderBase<TagBindingsClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public TagBindingsSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public TagBindingsClientBuilder() { UseJwtAccessWithScopes = TagBindingsClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref TagBindingsClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<TagBindingsClient> task); /// <summary>Builds the resulting client.</summary> public override TagBindingsClient Build() { TagBindingsClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<TagBindingsClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<TagBindingsClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private TagBindingsClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return TagBindingsClient.Create(callInvoker, Settings); } private async stt::Task<TagBindingsClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return TagBindingsClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => TagBindingsClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => TagBindingsClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => TagBindingsClient.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>TagBindings client wrapper, for convenient use.</summary> /// <remarks> /// Allow users to create and manage TagBindings between TagValues and /// different cloud resources throughout the GCP resource hierarchy. /// </remarks> public abstract partial class TagBindingsClient { /// <summary> /// The default endpoint for the TagBindings service, which is a host of "cloudresourcemanager.googleapis.com" /// and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "cloudresourcemanager.googleapis.com:443"; /// <summary>The default TagBindings scopes.</summary> /// <remarks> /// The default TagBindings scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// <item><description>https://www.googleapis.com/auth/cloud-platform.read-only</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/cloud-platform.read-only", }); 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="TagBindingsClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="TagBindingsClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="TagBindingsClient"/>.</returns> public static stt::Task<TagBindingsClient> CreateAsync(st::CancellationToken cancellationToken = default) => new TagBindingsClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="TagBindingsClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="TagBindingsClientBuilder"/>. /// </summary> /// <returns>The created <see cref="TagBindingsClient"/>.</returns> public static TagBindingsClient Create() => new TagBindingsClientBuilder().Build(); /// <summary> /// Creates a <see cref="TagBindingsClient"/> 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="TagBindingsSettings"/>.</param> /// <returns>The created <see cref="TagBindingsClient"/>.</returns> internal static TagBindingsClient Create(grpccore::CallInvoker callInvoker, TagBindingsSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } TagBindings.TagBindingsClient grpcClient = new TagBindings.TagBindingsClient(callInvoker); return new TagBindingsClientImpl(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 TagBindings client</summary> public virtual TagBindings.TagBindingsClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Lists the TagBindings for the given cloud resource, as specified with /// `parent`. /// /// NOTE: The `parent` field is expected to be a full resource name: /// https://cloud.google.com/apis/design/resource_names#full_resource_name /// </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="TagBinding"/> resources.</returns> public virtual gax::PagedEnumerable<ListTagBindingsResponse, TagBinding> ListTagBindings(ListTagBindingsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Lists the TagBindings for the given cloud resource, as specified with /// `parent`. /// /// NOTE: The `parent` field is expected to be a full resource name: /// https://cloud.google.com/apis/design/resource_names#full_resource_name /// </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="TagBinding"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListTagBindingsResponse, TagBinding> ListTagBindingsAsync(ListTagBindingsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Lists the TagBindings for the given cloud resource, as specified with /// `parent`. /// /// NOTE: The `parent` field is expected to be a full resource name: /// https://cloud.google.com/apis/design/resource_names#full_resource_name /// </summary> /// <param name="parent"> /// Required. The full resource name of a resource for which you want to list existing /// TagBindings. /// E.g. "//cloudresourcemanager.googleapis.com/projects/123" /// </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="TagBinding"/> resources.</returns> public virtual gax::PagedEnumerable<ListTagBindingsResponse, TagBinding> ListTagBindings(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListTagBindings(new ListTagBindingsRequest { Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists the TagBindings for the given cloud resource, as specified with /// `parent`. /// /// NOTE: The `parent` field is expected to be a full resource name: /// https://cloud.google.com/apis/design/resource_names#full_resource_name /// </summary> /// <param name="parent"> /// Required. The full resource name of a resource for which you want to list existing /// TagBindings. /// E.g. "//cloudresourcemanager.googleapis.com/projects/123" /// </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="TagBinding"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListTagBindingsResponse, TagBinding> ListTagBindingsAsync(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListTagBindingsAsync(new ListTagBindingsRequest { Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists the TagBindings for the given cloud resource, as specified with /// `parent`. /// /// NOTE: The `parent` field is expected to be a full resource name: /// https://cloud.google.com/apis/design/resource_names#full_resource_name /// </summary> /// <param name="parent"> /// Required. The full resource name of a resource for which you want to list existing /// TagBindings. /// E.g. "//cloudresourcemanager.googleapis.com/projects/123" /// </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="TagBinding"/> resources.</returns> public virtual gax::PagedEnumerable<ListTagBindingsResponse, TagBinding> ListTagBindings(gax::IResourceName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListTagBindings(new ListTagBindingsRequest { ParentAsResourceName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists the TagBindings for the given cloud resource, as specified with /// `parent`. /// /// NOTE: The `parent` field is expected to be a full resource name: /// https://cloud.google.com/apis/design/resource_names#full_resource_name /// </summary> /// <param name="parent"> /// Required. The full resource name of a resource for which you want to list existing /// TagBindings. /// E.g. "//cloudresourcemanager.googleapis.com/projects/123" /// </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="TagBinding"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListTagBindingsResponse, TagBinding> ListTagBindingsAsync(gax::IResourceName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListTagBindingsAsync(new ListTagBindingsRequest { ParentAsResourceName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Creates a TagBinding between a TagValue and a cloud resource /// (currently project, folder, or organization). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<TagBinding, CreateTagBindingMetadata> CreateTagBinding(CreateTagBindingRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a TagBinding between a TagValue and a cloud resource /// (currently project, folder, or organization). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<TagBinding, CreateTagBindingMetadata>> CreateTagBindingAsync(CreateTagBindingRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a TagBinding between a TagValue and a cloud resource /// (currently project, folder, or organization). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<TagBinding, CreateTagBindingMetadata>> CreateTagBindingAsync(CreateTagBindingRequest request, st::CancellationToken cancellationToken) => CreateTagBindingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary>The long-running operations client for <c>CreateTagBinding</c>.</summary> public virtual lro::OperationsClient CreateTagBindingOperationsClient => throw new sys::NotImplementedException(); /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>CreateTagBinding</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual lro::Operation<TagBinding, CreateTagBindingMetadata> PollOnceCreateTagBinding(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<TagBinding, CreateTagBindingMetadata>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), CreateTagBindingOperationsClient, callSettings); /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of /// <c>CreateTagBinding</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual stt::Task<lro::Operation<TagBinding, CreateTagBindingMetadata>> PollOnceCreateTagBindingAsync(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<TagBinding, CreateTagBindingMetadata>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), CreateTagBindingOperationsClient, callSettings); /// <summary> /// Creates a TagBinding between a TagValue and a cloud resource /// (currently project, folder, or organization). /// </summary> /// <param name="tagBinding"> /// Required. The TagBinding to be created. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<TagBinding, CreateTagBindingMetadata> CreateTagBinding(TagBinding tagBinding, gaxgrpc::CallSettings callSettings = null) => CreateTagBinding(new CreateTagBindingRequest { TagBinding = gax::GaxPreconditions.CheckNotNull(tagBinding, nameof(tagBinding)), }, callSettings); /// <summary> /// Creates a TagBinding between a TagValue and a cloud resource /// (currently project, folder, or organization). /// </summary> /// <param name="tagBinding"> /// Required. The TagBinding to be created. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<TagBinding, CreateTagBindingMetadata>> CreateTagBindingAsync(TagBinding tagBinding, gaxgrpc::CallSettings callSettings = null) => CreateTagBindingAsync(new CreateTagBindingRequest { TagBinding = gax::GaxPreconditions.CheckNotNull(tagBinding, nameof(tagBinding)), }, callSettings); /// <summary> /// Creates a TagBinding between a TagValue and a cloud resource /// (currently project, folder, or organization). /// </summary> /// <param name="tagBinding"> /// Required. The TagBinding to be created. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<TagBinding, CreateTagBindingMetadata>> CreateTagBindingAsync(TagBinding tagBinding, st::CancellationToken cancellationToken) => CreateTagBindingAsync(tagBinding, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes a TagBinding. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<wkt::Empty, DeleteTagBindingMetadata> DeleteTagBinding(DeleteTagBindingRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes a TagBinding. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<wkt::Empty, DeleteTagBindingMetadata>> DeleteTagBindingAsync(DeleteTagBindingRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes a TagBinding. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<wkt::Empty, DeleteTagBindingMetadata>> DeleteTagBindingAsync(DeleteTagBindingRequest request, st::CancellationToken cancellationToken) => DeleteTagBindingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary>The long-running operations client for <c>DeleteTagBinding</c>.</summary> public virtual lro::OperationsClient DeleteTagBindingOperationsClient => throw new sys::NotImplementedException(); /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>DeleteTagBinding</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual lro::Operation<wkt::Empty, DeleteTagBindingMetadata> PollOnceDeleteTagBinding(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<wkt::Empty, DeleteTagBindingMetadata>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), DeleteTagBindingOperationsClient, callSettings); /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of /// <c>DeleteTagBinding</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual stt::Task<lro::Operation<wkt::Empty, DeleteTagBindingMetadata>> PollOnceDeleteTagBindingAsync(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<wkt::Empty, DeleteTagBindingMetadata>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), DeleteTagBindingOperationsClient, callSettings); /// <summary> /// Deletes a TagBinding. /// </summary> /// <param name="name"> /// Required. The name of the TagBinding. This is a String of the form: /// `tagBindings/{id}` (e.g. /// `tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F123/tagValues/456`). /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<wkt::Empty, DeleteTagBindingMetadata> DeleteTagBinding(string name, gaxgrpc::CallSettings callSettings = null) => DeleteTagBinding(new DeleteTagBindingRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), }, callSettings); /// <summary> /// Deletes a TagBinding. /// </summary> /// <param name="name"> /// Required. The name of the TagBinding. This is a String of the form: /// `tagBindings/{id}` (e.g. /// `tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F123/tagValues/456`). /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<wkt::Empty, DeleteTagBindingMetadata>> DeleteTagBindingAsync(string name, gaxgrpc::CallSettings callSettings = null) => DeleteTagBindingAsync(new DeleteTagBindingRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), }, callSettings); /// <summary> /// Deletes a TagBinding. /// </summary> /// <param name="name"> /// Required. The name of the TagBinding. This is a String of the form: /// `tagBindings/{id}` (e.g. /// `tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F123/tagValues/456`). /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<wkt::Empty, DeleteTagBindingMetadata>> DeleteTagBindingAsync(string name, st::CancellationToken cancellationToken) => DeleteTagBindingAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes a TagBinding. /// </summary> /// <param name="name"> /// Required. The name of the TagBinding. This is a String of the form: /// `tagBindings/{id}` (e.g. /// `tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F123/tagValues/456`). /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<wkt::Empty, DeleteTagBindingMetadata> DeleteTagBinding(TagBindingName name, gaxgrpc::CallSettings callSettings = null) => DeleteTagBinding(new DeleteTagBindingRequest { TagBindingName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), }, callSettings); /// <summary> /// Deletes a TagBinding. /// </summary> /// <param name="name"> /// Required. The name of the TagBinding. This is a String of the form: /// `tagBindings/{id}` (e.g. /// `tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F123/tagValues/456`). /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<wkt::Empty, DeleteTagBindingMetadata>> DeleteTagBindingAsync(TagBindingName name, gaxgrpc::CallSettings callSettings = null) => DeleteTagBindingAsync(new DeleteTagBindingRequest { TagBindingName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), }, callSettings); /// <summary> /// Deletes a TagBinding. /// </summary> /// <param name="name"> /// Required. The name of the TagBinding. This is a String of the form: /// `tagBindings/{id}` (e.g. /// `tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F123/tagValues/456`). /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<wkt::Empty, DeleteTagBindingMetadata>> DeleteTagBindingAsync(TagBindingName name, st::CancellationToken cancellationToken) => DeleteTagBindingAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>TagBindings client wrapper implementation, for convenient use.</summary> /// <remarks> /// Allow users to create and manage TagBindings between TagValues and /// different cloud resources throughout the GCP resource hierarchy. /// </remarks> public sealed partial class TagBindingsClientImpl : TagBindingsClient { private readonly gaxgrpc::ApiCall<ListTagBindingsRequest, ListTagBindingsResponse> _callListTagBindings; private readonly gaxgrpc::ApiCall<CreateTagBindingRequest, lro::Operation> _callCreateTagBinding; private readonly gaxgrpc::ApiCall<DeleteTagBindingRequest, lro::Operation> _callDeleteTagBinding; /// <summary> /// Constructs a client wrapper for the TagBindings service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="TagBindingsSettings"/> used within this client.</param> public TagBindingsClientImpl(TagBindings.TagBindingsClient grpcClient, TagBindingsSettings settings) { GrpcClient = grpcClient; TagBindingsSettings effectiveSettings = settings ?? TagBindingsSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); CreateTagBindingOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.CreateTagBindingOperationsSettings); DeleteTagBindingOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.DeleteTagBindingOperationsSettings); _callListTagBindings = clientHelper.BuildApiCall<ListTagBindingsRequest, ListTagBindingsResponse>(grpcClient.ListTagBindingsAsync, grpcClient.ListTagBindings, effectiveSettings.ListTagBindingsSettings); Modify_ApiCall(ref _callListTagBindings); Modify_ListTagBindingsApiCall(ref _callListTagBindings); _callCreateTagBinding = clientHelper.BuildApiCall<CreateTagBindingRequest, lro::Operation>(grpcClient.CreateTagBindingAsync, grpcClient.CreateTagBinding, effectiveSettings.CreateTagBindingSettings); Modify_ApiCall(ref _callCreateTagBinding); Modify_CreateTagBindingApiCall(ref _callCreateTagBinding); _callDeleteTagBinding = clientHelper.BuildApiCall<DeleteTagBindingRequest, lro::Operation>(grpcClient.DeleteTagBindingAsync, grpcClient.DeleteTagBinding, effectiveSettings.DeleteTagBindingSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callDeleteTagBinding); Modify_DeleteTagBindingApiCall(ref _callDeleteTagBinding); 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_ListTagBindingsApiCall(ref gaxgrpc::ApiCall<ListTagBindingsRequest, ListTagBindingsResponse> call); partial void Modify_CreateTagBindingApiCall(ref gaxgrpc::ApiCall<CreateTagBindingRequest, lro::Operation> call); partial void Modify_DeleteTagBindingApiCall(ref gaxgrpc::ApiCall<DeleteTagBindingRequest, lro::Operation> call); partial void OnConstruction(TagBindings.TagBindingsClient grpcClient, TagBindingsSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC TagBindings client</summary> public override TagBindings.TagBindingsClient GrpcClient { get; } partial void Modify_ListTagBindingsRequest(ref ListTagBindingsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_CreateTagBindingRequest(ref CreateTagBindingRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_DeleteTagBindingRequest(ref DeleteTagBindingRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Lists the TagBindings for the given cloud resource, as specified with /// `parent`. /// /// NOTE: The `parent` field is expected to be a full resource name: /// https://cloud.google.com/apis/design/resource_names#full_resource_name /// </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="TagBinding"/> resources.</returns> public override gax::PagedEnumerable<ListTagBindingsResponse, TagBinding> ListTagBindings(ListTagBindingsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListTagBindingsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<ListTagBindingsRequest, ListTagBindingsResponse, TagBinding>(_callListTagBindings, request, callSettings); } /// <summary> /// Lists the TagBindings for the given cloud resource, as specified with /// `parent`. /// /// NOTE: The `parent` field is expected to be a full resource name: /// https://cloud.google.com/apis/design/resource_names#full_resource_name /// </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="TagBinding"/> resources.</returns> public override gax::PagedAsyncEnumerable<ListTagBindingsResponse, TagBinding> ListTagBindingsAsync(ListTagBindingsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListTagBindingsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<ListTagBindingsRequest, ListTagBindingsResponse, TagBinding>(_callListTagBindings, request, callSettings); } /// <summary>The long-running operations client for <c>CreateTagBinding</c>.</summary> public override lro::OperationsClient CreateTagBindingOperationsClient { get; } /// <summary> /// Creates a TagBinding between a TagValue and a cloud resource /// (currently project, folder, or organization). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override lro::Operation<TagBinding, CreateTagBindingMetadata> CreateTagBinding(CreateTagBindingRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateTagBindingRequest(ref request, ref callSettings); return new lro::Operation<TagBinding, CreateTagBindingMetadata>(_callCreateTagBinding.Sync(request, callSettings), CreateTagBindingOperationsClient); } /// <summary> /// Creates a TagBinding between a TagValue and a cloud resource /// (currently project, folder, or organization). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override async stt::Task<lro::Operation<TagBinding, CreateTagBindingMetadata>> CreateTagBindingAsync(CreateTagBindingRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateTagBindingRequest(ref request, ref callSettings); return new lro::Operation<TagBinding, CreateTagBindingMetadata>(await _callCreateTagBinding.Async(request, callSettings).ConfigureAwait(false), CreateTagBindingOperationsClient); } /// <summary>The long-running operations client for <c>DeleteTagBinding</c>.</summary> public override lro::OperationsClient DeleteTagBindingOperationsClient { get; } /// <summary> /// Deletes a TagBinding. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override lro::Operation<wkt::Empty, DeleteTagBindingMetadata> DeleteTagBinding(DeleteTagBindingRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteTagBindingRequest(ref request, ref callSettings); return new lro::Operation<wkt::Empty, DeleteTagBindingMetadata>(_callDeleteTagBinding.Sync(request, callSettings), DeleteTagBindingOperationsClient); } /// <summary> /// Deletes a TagBinding. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override async stt::Task<lro::Operation<wkt::Empty, DeleteTagBindingMetadata>> DeleteTagBindingAsync(DeleteTagBindingRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteTagBindingRequest(ref request, ref callSettings); return new lro::Operation<wkt::Empty, DeleteTagBindingMetadata>(await _callDeleteTagBinding.Async(request, callSettings).ConfigureAwait(false), DeleteTagBindingOperationsClient); } } public partial class ListTagBindingsRequest : gaxgrpc::IPageRequest { } public partial class ListTagBindingsResponse : gaxgrpc::IPageResponse<TagBinding> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<TagBinding> GetEnumerator() => TagBindings.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } public static partial class TagBindings { public partial class TagBindingsClient { /// <summary> /// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as /// this client. /// </summary> /// <returns>A new Operations client for the same target as this client.</returns> public virtual lro::Operations.OperationsClient CreateOperationsClient() => new lro::Operations.OperationsClient(CallInvoker); } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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.Configuration; using System.Globalization; using System.IO; using System.Text; using System.Web; using AjaxPro; using ASC.Common.Logging; using ASC.Core; using ASC.Core.Users; using ASC.Web.Core; using ASC.Web.Core.Jabber; using ASC.Web.Studio; using ASC.Web.Studio.Core; using ASC.Web.Studio.Utility; using ASC.Web.Talk.Addon; using ASC.Web.Talk.ClientScript; using ASC.Web.Talk.Resources; namespace ASC.Web.Talk { [AjaxNamespace("JabberClient")] public partial class JabberClient : MainPage { private static string JabberResource { get { return "TMTalk"; } } private TalkConfiguration _cfg; private static String EscapeJsString(String s) { return s.Replace("'", "\\'"); } protected void Page_Load(object sender, EventArgs e) { var thirdPartyChat = ConfigurationManagerExtension.AppSettings["web.third-party-chat-url"]; var isEnabledTalk = ConfigurationManagerExtension.AppSettings["web.talk"] ?? "false"; if (!String.IsNullOrEmpty(thirdPartyChat)) { if (CoreContext.Configuration.CustomMode) { Response.Redirect(thirdPartyChat + "?ask_key=" + HttpUtility.UrlEncode(CookiesManager.GetCookies(CookiesType.AuthKey)), true); } Response.Redirect(thirdPartyChat, true); } if (isEnabledTalk != "true") { Response.Redirect(CommonLinkUtility.GetDefault()); } _cfg = new TalkConfiguration(); Utility.RegisterTypeForAjax(GetType()); Master.DisabledSidePanel = true; Master.DisabledTopStudioPanel = true; Page .RegisterBodyScripts("~/addons/talk/js/gears.init.js", "~/addons/talk/js/gears.init.js", "~/addons/talk/js/iscroll.js", "~/addons/talk/js/talk.customevents.js", "~/js/third-party/jquery/jquery.notification.js", "~/js/third-party/moment.min.js", "~/js/third-party/moment-timezone.min.js", "~/addons/talk/js/talk.common.js", "~/addons/talk/js/talk.navigationitem.js", "~/addons/talk/js/talk.msmanager.js", "~/addons/talk/js/talk.mucmanager.js", "~/addons/talk/js/talk.roomsmanager.js", "~/addons/talk/js/talk.contactsmanager.js", "~/addons/talk/js/talk.messagesmanager.js", "~/addons/talk/js/talk.connectiomanager.js", "~/addons/talk/js/talk.default.js", "~/addons/talk/js/talk.init.js") .RegisterStyle("~/addons/talk/css/default/talk.style.css"); if (Request.Browser != null && Request.Browser.Browser != "IE" && Request.Browser.Browser != "InternetExplorer") { Page .RegisterBodyScripts("~/js/third-party/firebase.js", "~/js/third-party/firebase-app.js", "~/js/third-party/firebase-auth.js", "~/js/third-party/firebase-database.js", "~/js/third-party/firebase-messaging.js"); } var virtPath = "~/addons/talk/css/default/talk.style." + CultureInfo.CurrentCulture.Name.ToLower() + ".css"; if (File.Exists(Server.MapPath(virtPath))) { Page.RegisterStyle(virtPath); } Page.RegisterStyle("~/addons/talk/css/default/talk.text-overflow.css"); switch (_cfg.RequestTransportType.ToLower()) { case "flash": Page.RegisterBodyScripts("~/addons/talk/js/jlib/plugins/strophe.flxhr.js", "~/addons/talk/js/jlib/flxhr/checkplayer.js", "~/addons/talk/js/jlib/flxhr/flensed.js", "~/addons/talk/js/jlib/flxhr/flxhr.js", "~/addons/talk/js/jlib/flxhr/swfobject.js", "~/js/third-party/xregexp.js", "~/addons/talk/js/jlib/strophe/base64.js", "~/addons/talk/js/jlib/strophe/md5.js", "~/addons/talk/js/jlib/strophe/core.js"); break; default: Page.RegisterBodyScripts( "~/addons/talk/js/jlib/strophe/base64.js", "~/addons/talk/js/jlib/strophe/md5.js", "~/addons/talk/js/jlib/strophe/core.js", "~/js/third-party/xregexp.js", "~/addons/talk/js/jlib/flxhr/swfobject.js"); break; } Master.AddClientScript(new TalkClientScript(), new TalkClientScriptLocalization()); try { Page.Title = TalkResource.ProductName + " - " + CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).DisplayUserName(false); } catch (System.Security.SecurityException) { Page.Title = TalkResource.ProductName + " - " + HeaderStringHelper.GetPageTitle(TalkResource.DefaultContactTitle); } try { Page.RegisterInlineScript("ASC.TMTalk.notifications && ASC.TMTalk.notifications.initialiseFirebase(" + GetFirebaseConfig() + ");"); } catch (Exception) { } } [AjaxMethod(HttpSessionStateRequirement.ReadWrite), Core.Security.SecurityPassthrough] public string GetAuthToken() { try { return new JabberServiceClient().GetAuthToken(TenantProvider.CurrentTenantID); } catch (Exception ex) { LogManager.GetLogger("ASC.Talk").Error(ex); return String.Empty; } } [AjaxMethod] public string GetSpaceUsage() { try { var spaceUsage = TalkSpaceUsageStatManager.GetSpaceUsage(); return spaceUsage > 0 ? FileSizeComment.FilesSizeToString(spaceUsage) : String.Empty; } catch (Exception ex) { LogManager.GetLogger("ASC.Talk").Error(ex); return String.Empty; } } [AjaxMethod] public string ClearSpaceUsage(TalkSpaceUsageStatManager.ClearType type) { try { TalkSpaceUsageStatManager.ClearSpaceUsage(type); return GetSpaceUsage(); } catch (Exception ex) { LogManager.GetLogger("ASC.Talk").Error(ex); return String.Empty; } } protected String GetBoshUri() { return _cfg.BoshUri; } protected String GetResourcePriority() { return _cfg.ResourcePriority; } protected String GetInactivity() { return _cfg.ClientInactivity; } protected String GetFileTransportType() { return _cfg.FileTransportType ?? String.Empty; } protected String GetRequestTransportType() { return _cfg.RequestTransportType ?? String.Empty; } protected String GetMassendState() { return _cfg.EnabledMassend.ToString().ToLower(); } protected String GetConferenceState() { return _cfg.EnabledConferences.ToString().ToLower(); } protected String GetMonthNames() { return String.Join(",", CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedMonthNames); } protected String GetDayNames() { return String.Join(",", CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedDayNames); } protected String GetHistoryLength() { return _cfg.HistoryLength ?? String.Empty; } protected String GetValidSymbols() { return _cfg.ValidSymbols ?? String.Empty; } protected String GetFullDateFormat() { return TalkResource.FullDateFormat; } protected String GetShortDateFormat() { return TalkResource.ShortDateFormat; } protected String GetUserPhotoHandlerPath() { return VirtualPathUtility.ToAbsolute("~/addons/talk/userphoto.ashx"); } protected String GetNotificationHandlerPath() { return VirtualPathUtility.ToAbsolute("~/addons/talk/notification.html"); } protected string GetJidServerPartOfJid() { string tenantDomain = CoreContext.TenantManager.GetCurrentTenant().TenantDomain; if (_cfg.ReplaceDomain && tenantDomain != null && tenantDomain.EndsWith(_cfg.ReplaceToDomain)) { int place = tenantDomain.LastIndexOf(_cfg.ReplaceToDomain); if (place >= 0) { return tenantDomain.Remove(place, _cfg.ReplaceToDomain.Length).Insert(place, _cfg.ReplaceFromDomain); } } return tenantDomain; } protected String GetJabberAccount() { try { return EscapeJsString(CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).UserName.ToLower()) + "@" + GetJidServerPartOfJid() + "/" + JabberResource; } catch (Exception) { return String.Empty; } } private String GetFirebaseConfig() { string firebase_projectId = FireBase.Instance.ProjectId; firebase_projectId = firebase_projectId.Trim(); var script = new StringBuilder(); if (firebase_projectId != String.Empty) { script.AppendLine("{apiKey: '" + FireBase.Instance.ApiKey.Trim() + "',"); script.AppendLine(" authDomain: '" + firebase_projectId + ".firebaseapp.com',"); script.AppendLine(" databaseURL: 'https://" + firebase_projectId + ".firebaseapp.com',"); script.AppendLine(" projectId: '" + firebase_projectId + "',"); script.AppendLine(" storageBucket: '" + firebase_projectId + ".appspot.com',"); script.AppendLine(" messagingSenderId: '" + FireBase.Instance.MessagingSenderId.Trim() + "'}"); return script.ToString(); } else { return null; } } } }
using System; using System.CodeDom; using System.Reflection; using System.Globalization; namespace Microsoft.Samples.CodeDomTestSuite { [CLSCompliant(true)] #if WHIDBEY public static class CDHelper { #else public class CDHelper { #endif ///////////////////////////////////////////////////////////// // CodeTypeDeclaration helpers // classes public static CodeTypeDeclaration CreateClass (string name) { CodeTypeDeclaration ct = new CodeTypeDeclaration (name); ct.IsClass = true; return ct; } public static CodeTypeDeclaration CreateClass (string name, MemberAttributes attribute) { CodeTypeDeclaration ct = new CodeTypeDeclaration (name); ct.Attributes = attribute; ct.IsClass = true; return ct; } public static CodeTypeDeclaration CreateClass (string name, MemberAttributes attribute, TypeAttributes typeAttr) { CodeTypeDeclaration ct = new CodeTypeDeclaration (name); ct.Attributes = attribute; ct.TypeAttributes = typeAttr; ct.IsClass = true; return ct; } public static CodeTypeDeclaration CreateClass (string name, MemberAttributes attribute, TypeAttributes typeAttr, CodeTypeReference[] baseTypes) { CodeTypeDeclaration ct = new CodeTypeDeclaration (name); ct.Attributes = attribute; ct.TypeAttributes = typeAttr; ct.BaseTypes.AddRange (baseTypes); ct.IsClass = true; return ct; } public static CodeTypeDeclaration CreateClass (string name, MemberAttributes attribute, CodeTypeReference[] baseTypes) { CodeTypeDeclaration ct = new CodeTypeDeclaration (name); ct.Attributes = attribute; ct.BaseTypes.AddRange (baseTypes); ct.IsClass = true; return ct; } // interfaces public static CodeTypeDeclaration CreateInterface (string name) { CodeTypeDeclaration ct = new CodeTypeDeclaration (name); ct.IsInterface = true; return ct; } public static CodeTypeDeclaration CreateInterface (string name, MemberAttributes attribute) { CodeTypeDeclaration ct = new CodeTypeDeclaration (name); ct.Attributes = attribute; ct.IsInterface = true; return ct; } public static CodeTypeDeclaration CreateInterface (string name, MemberAttributes attribute, TypeAttributes typeAttr) { CodeTypeDeclaration ct = new CodeTypeDeclaration (name); ct.Attributes = attribute; ct.TypeAttributes = typeAttr; ct.IsInterface = true; return ct; } public static CodeTypeDeclaration CreateInterface (string name, MemberAttributes attribute, TypeAttributes typeAttr, CodeTypeReference[] baseTypes) { CodeTypeDeclaration ct = new CodeTypeDeclaration (name); ct.Attributes = attribute; ct.TypeAttributes = typeAttr; ct.BaseTypes.AddRange (baseTypes); ct.IsInterface = true; return ct; } // end CodeTypeDeclaration helpers ///////////////////////////////////////////////////////////// // CodeConstructor helpers public static CodeConstructor CreateConstructor () { return new CodeConstructor (); } public static CodeConstructor CreateConstructor (MemberAttributes attribute) { CodeConstructor cc = CreateConstructor (); cc.Attributes = attribute; return cc; } // CodeMemberMethod helpers public static CodeMemberMethod CreateMethod (string name) { CodeMemberMethod cm = new CodeMemberMethod (); cm.Name = name; return cm; } public static CodeMemberMethod CreateMethod (string name, CodeTypeReference returnType) { CodeMemberMethod cm = CreateMethod (name); cm.ReturnType = returnType; return cm; } public static CodeMemberMethod CreateMethod (string name, CodeTypeReference returnType, MemberAttributes attribute) { CodeMemberMethod cm = CreateMethod (name, returnType); cm.Attributes = attribute; return cm; } public static CodeMemberMethod CreateMethod (string name, CodeTypeReference returnType, MemberAttributes attribute, CodeParameterDeclarationExpressionCollection parameters) { CodeMemberMethod cm = CreateMethod (name, returnType, attribute); if (parameters != null) foreach (CodeParameterDeclarationExpression p in parameters) cm.Parameters.Add (p); return cm; } // CodeNamespace helpers public static CodeNamespace CreateNamespace (string name) { return new CodeNamespace (name); } // CodeParameterDeclarationExpressionCollection helpers // -- this one is possibly dangerous? public static CodeParameterDeclarationExpressionCollection CreateParameterList (params object[] parameters) { // must have an even number of arguments for // a list of pairs to be valid if (parameters.Length % 2 != 0) throw new ArgumentException ("Must supply an even number of arguments."); CodeParameterDeclarationExpressionCollection exps = new CodeParameterDeclarationExpressionCollection (); for (Int32 i = 0; i < parameters.Length; i += 2) { if (!typeof (string).IsInstanceOfType (parameters[i + 1])) throw new ArgumentException (String.Format (CultureInfo.InvariantCulture, "Argument {0} should be of type string.", i + 1)); if (typeof (Type).IsInstanceOfType (parameters[i])) { exps.Add (new CodeParameterDeclarationExpression ( (Type) parameters[i], (string) parameters[i + 1])); } else if (typeof (string).IsInstanceOfType (parameters[i])) { exps.Add (new CodeParameterDeclarationExpression ( (string) parameters[i], (string) parameters[i + 1])); } else if (typeof (CodeTypeReference).IsInstanceOfType (parameters[i])) { exps.Add (new CodeParameterDeclarationExpression ( (CodeTypeReference) parameters[i], (string) parameters[i + 1])); } else { throw new ArgumentException (String.Format (CultureInfo.InvariantCulture, "Argument {0} should be of Type, string, or CodeTypeReference.", i)); } } return exps; } // CodeMemberProperty helpers // -- type defined by string public static CodeMemberProperty CreateProperty (string type, string name) { CodeMemberProperty cp = new CodeMemberProperty (); cp.Name = name; cp.Type = new CodeTypeReference (type); return cp; } public static CodeMemberProperty CreateProperty (string type, string name, MemberAttributes attribute) { CodeMemberProperty cp = CreateProperty (type, name); cp.Attributes = attribute; return cp; } // -- type defined by Type public static CodeMemberProperty CreateProperty (Type type, string name) { CodeMemberProperty cp = new CodeMemberProperty (); cp.Name = name; cp.Type = new CodeTypeReference (type); return cp; } public static CodeMemberProperty CreateProperty (Type type, string name, MemberAttributes attribute) { CodeMemberProperty cp = CreateProperty (type, name); cp.Attributes = attribute; return cp; } // -- type defined by CodeTypeReference public static CodeMemberProperty CreateProperty (CodeTypeReference type, string name, MemberAttributes attribute) { CodeMemberProperty cp = CreateProperty (type, name); cp.Attributes = attribute; return cp; } public static CodeMemberProperty CreateProperty (CodeTypeReference type, string name) { CodeMemberProperty cp = new CodeMemberProperty (); cp.Name = name; cp.Type = type; return cp; } // ---------------------------------------------------- // CodeStatement helpers // Creates: // for (varName = startVal; varName < limit; varName = varName + 1) { // // } public static CodeIterationStatement CreateCountUpLoop (string varName, int startVal, CodeExpression limit) { CodeIterationStatement iter = new CodeIterationStatement (); iter.InitStatement = new CodeAssignStatement (new CodeVariableReferenceExpression (varName), new CodePrimitiveExpression (startVal)); iter.TestExpression = new CodeBinaryOperatorExpression (new CodeVariableReferenceExpression (varName), CodeBinaryOperatorType.LessThan, limit); iter.IncrementStatement = new CodeAssignStatement (new CodeVariableReferenceExpression (varName), new CodeBinaryOperatorExpression (new CodeVariableReferenceExpression (varName), CodeBinaryOperatorType.Add, new CodePrimitiveExpression (1))); return iter; } // creates: // var1 (op) var2 // // It automatically boxes any strings as variable references, // ints and doubles become primitives everything else generates a // runtime exception public static CodeBinaryOperatorExpression CreateBinaryOperatorExpression (object var1, CodeBinaryOperatorType op, object var2) { if (var1 == null) throw new ArgumentNullException ("var1"); if (var2 == null) throw new ArgumentNullException ("var2"); CodeExpression var1Exp = null; CodeExpression var2Exp = null; if (var1 is string) var1Exp = new CodeVariableReferenceExpression ((string) var1); else if (var1 is int) var1Exp = new CodePrimitiveExpression ((int) var1); else if (var1 is double) var1Exp = new CodePrimitiveExpression ((double) var2); else var1Exp = (CodeExpression) var1; if (var2 is string) var2Exp = new CodeVariableReferenceExpression ((string) var2); else if (var2 is int) var2Exp = new CodePrimitiveExpression ((int) var2); else if (var2 is double) var2Exp = new CodePrimitiveExpression ((double) var2); else var2Exp = (CodeExpression) var2; return new CodeBinaryOperatorExpression (var1Exp, op, var2Exp); } // creates: // varName = var1 (OP) var2 // // See above for rules about var1, var2 public static CodeAssignStatement CreateBinaryOperatorStatement (string varName, object var1, CodeBinaryOperatorType op, object var2) { return new CodeAssignStatement (new CodeVariableReferenceExpression (varName), CreateBinaryOperatorExpression (var1, op, var2)); } // creates: // varName = (type) var1 (OP) var2 public static CodeAssignStatement CreateBinaryOperatorStatementWithCast (string varName, CodeTypeReference type, object var1, CodeBinaryOperatorType op, object var2) { return new CodeAssignStatement (new CodeVariableReferenceExpression (varName), new CodeCastExpression (type, CreateBinaryOperatorExpression (var1, op, var2))); } // creates: // varName = (type) var1 (OP) var2 public static CodeAssignStatement CreateBinaryOperatorStatementWithCast (string varName, Type type, object var1, CodeBinaryOperatorType op, object var2) { return new CodeAssignStatement (new CodeVariableReferenceExpression (varName), new CodeCastExpression (type, CreateBinaryOperatorExpression (var1, op, var2))); } // creates: // varName = varName + expression; public static CodeAssignStatement CreateIncrementByStatement (string varName, CodeExpression expression) { return CreateBinaryOperatorStatement (varName, new CodeVariableReferenceExpression (varName), CodeBinaryOperatorType.Add, expression); } public static CodeAssignStatement CreateIncrementByStatement (string varName, int expression) { return CreateBinaryOperatorStatement (varName, new CodeVariableReferenceExpression (varName), CodeBinaryOperatorType.Add, new CodePrimitiveExpression (expression)); } public static CodeAssignStatement CreateIncrementByStatement (CodeExpression varName, int expression) { return new CodeAssignStatement (varName, new CodeBinaryOperatorExpression (varName, CodeBinaryOperatorType.Add, new CodePrimitiveExpression (expression))); } public static CodeAssignStatement CreateIncrementByStatement (string varName, string expression) { return CreateBinaryOperatorStatement (varName, new CodeVariableReferenceExpression (varName), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression (expression)); } /* public static CodeAssignStatement CreateIncrementByStatement (CodeExpression varName, string expression) { return new CodeBinaryOperatorExpression (varName, CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression (expression)); }*/ // creates: // array[index] // // Automatically boxes strings into CodeVariableReferenceExpression public static CodeArrayIndexerExpression CreateArrayRef (string array, string index) { return new CodeArrayIndexerExpression (new CodeVariableReferenceExpression (array), new CodeVariableReferenceExpression (index)); } // Same but automatically boxes int into CodePrimitiveExpression public static CodeArrayIndexerExpression CreateArrayRef (string array, int index) { return new CodeArrayIndexerExpression (new CodeVariableReferenceExpression (array), new CodePrimitiveExpression (index)); } // creates: // var.fieldName public static CodeFieldReferenceExpression CreateFieldRef (string var, string fieldName) { return new CodeFieldReferenceExpression (new CodeVariableReferenceExpression (var), fieldName); } // creates: // target.methodName () // // Boxes all string params as CodeVariableReferenceExpressions, // CodeExpressions get passed directly in // all others get boxed as CodePrimitiveExpressions public static CodeMethodInvokeExpression CreateMethodInvoke (CodeExpression target, string methodName, params object [] args) { CodeMethodInvokeExpression exp = new CodeMethodInvokeExpression ( new CodeMethodReferenceExpression (target, methodName)); foreach (object a in args) { if (a is string) exp.Parameters.Add (new CodeVariableReferenceExpression ((string) a)); else if (a is CodeExpression) exp.Parameters.Add ((CodeExpression) a); else exp.Parameters.Add (new CodePrimitiveExpression (a)); } return exp; } public static CodeStatement ConsoleWriteLineStatement (CodeExpression exp) { return new CodeExpressionStatement ( new CodeMethodInvokeExpression ( new CodeMethodReferenceExpression ( new CodeTypeReferenceExpression (new CodeTypeReference (typeof (System.Console))), "WriteLine"), new CodeExpression[] { exp, })); } public static CodeStatement ConsoleWriteLineStatement (string txt) { return ConsoleWriteLineStatement (new CodePrimitiveExpression (txt)); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // Compiler-targeted types that build tasks for use as the return types of asynchronous methods. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Diagnostics; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using Internal.Runtime.Augments; using Internal.Runtime.CompilerServices; using AsyncStatus = Internal.Runtime.Augments.AsyncStatus; using CausalityRelation = Internal.Runtime.Augments.CausalityRelation; using CausalitySource = Internal.Runtime.Augments.CausalitySource; using CausalityTraceLevel = Internal.Runtime.Augments.CausalityTraceLevel; using CausalitySynchronousWork = Internal.Runtime.Augments.CausalitySynchronousWork; using Thread = Internal.Runtime.Augments.RuntimeThread; namespace System.Runtime.CompilerServices { /// <summary> /// Provides a builder for asynchronous methods that return void. /// This type is intended for compiler use only. /// </summary> public struct AsyncVoidMethodBuilder { /// <summary>Action to invoke the state machine's MoveNext.</summary> private Action m_moveNextAction; /// <summary>The synchronization context associated with this operation.</summary> private SynchronizationContext m_synchronizationContext; //WARNING: We allow diagnostic tools to directly inspect this member (m_task). //See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. //Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. //Get in touch with the diagnostics team if you have questions. /// <summary>Task used for debugging and logging purposes only. Lazily initialized.</summary> private Task m_task; /// <summary>Initializes a new <see cref="AsyncVoidMethodBuilder"/>.</summary> /// <returns>The initialized <see cref="AsyncVoidMethodBuilder"/>.</returns> [MethodImpl(MethodImplOptions.NoInlining)] public static AsyncVoidMethodBuilder Create() { SynchronizationContext sc = SynchronizationContext.Current; if (sc != null) sc.OperationStarted(); // On ProjectN we will eagerly initalize the task and it's Id if the debugger is attached AsyncVoidMethodBuilder avmb = new AsyncVoidMethodBuilder() { m_synchronizationContext = sc }; avmb.m_task = avmb.GetTaskIfDebuggingEnabled(); if (avmb.m_task != null) { int i = avmb.m_task.Id; } return avmb; } /// <summary>Initiates the builder's execution with the associated state machine.</summary> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="stateMachine">The state machine instance, passed by reference.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine => AsyncMethodBuilderCore.Start(ref stateMachine); /// <summary>Associates the builder with the state machine it represents.</summary> /// <param name="stateMachine">The heap-allocated state machine object.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The builder is incorrectly initialized.</exception> public void SetStateMachine(IAsyncStateMachine stateMachine) { AsyncMethodBuilderCore.SetStateMachine(stateMachine, m_moveNextAction); // argument validation handled by AsyncMethodBuilderCore } /// <summary> /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// </summary> /// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> public void AwaitOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { AsyncMethodBuilderCore.CallOnCompleted( AsyncMethodBuilderCore.GetCompletionAction(ref m_moveNextAction, ref stateMachine, this.GetTaskIfDebuggingEnabled()), ref awaiter); } /// <summary> /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// </summary> /// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { AsyncMethodBuilderCore.CallUnsafeOnCompleted( AsyncMethodBuilderCore.GetCompletionAction(ref m_moveNextAction, ref stateMachine, this.GetTaskIfDebuggingEnabled()), ref awaiter); } /// <summary>Completes the method builder successfully.</summary> public void SetResult() { Task taskIfDebuggingEnabled = this.GetTaskIfDebuggingEnabled(); if (taskIfDebuggingEnabled != null) { if (DebuggerSupport.LoggingOn) DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, taskIfDebuggingEnabled, AsyncStatus.Completed); DebuggerSupport.RemoveFromActiveTasks(taskIfDebuggingEnabled); } NotifySynchronizationContextOfCompletion(); } /// <summary>Faults the method builder with an exception.</summary> /// <param name="exception">The exception that is the cause of this fault.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="exception"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception> [MethodImpl(MethodImplOptions.NoInlining)] public void SetException(Exception exception) { Task taskIfDebuggingEnabled = this.GetTaskIfDebuggingEnabled(); if (taskIfDebuggingEnabled != null) { if (DebuggerSupport.LoggingOn) DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, taskIfDebuggingEnabled, AsyncStatus.Error); } AsyncMethodBuilderCore.ThrowAsync(exception, m_synchronizationContext); NotifySynchronizationContextOfCompletion(); } /// <summary>Notifies the current synchronization context that the operation completed.</summary> [MethodImpl(MethodImplOptions.NoInlining)] private void NotifySynchronizationContextOfCompletion() { if (m_synchronizationContext != null) { try { m_synchronizationContext.OperationCompleted(); } catch (Exception exc) { // If the interaction with the SynchronizationContext goes awry, // fall back to propagating on the ThreadPool. AsyncMethodBuilderCore.ThrowAsync(exc, targetContext: null); } } } // This property lazily instantiates the Task in a non-thread-safe manner. internal Task Task { get { if (m_task == null) m_task = new Task(); return m_task; } } /// <summary> /// Gets an object that may be used to uniquely identify this builder to the debugger. /// </summary> /// <remarks> /// This property lazily instantiates the ID in a non-thread-safe manner. /// It must only be used by the debugger and only in a single-threaded manner. /// </remarks> private object ObjectIdForDebugger { get { return this.Task; } } } /// <summary> /// Provides a builder for asynchronous methods that return <see cref="System.Threading.Tasks.Task"/>. /// This type is intended for compiler use only. /// </summary> /// <remarks> /// AsyncTaskMethodBuilder is a value type, and thus it is copied by value. /// Prior to being copied, one of its Task, SetResult, or SetException members must be accessed, /// or else the copies may end up building distinct Task instances. /// </remarks> public struct AsyncTaskMethodBuilder { /// <summary>A cached VoidTaskResult task used for builders that complete synchronously.</summary> private static readonly Task<VoidTaskResult> s_cachedCompleted = AsyncTaskCache.CreateCacheableTask<VoidTaskResult>(default(VoidTaskResult)); private Action m_moveNextAction; // WARNING: We allow diagnostic tools to directly inspect this member (m_task). // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. // Get in touch with the diagnostics team if you have questions. private Task<VoidTaskResult> m_task; /// <summary>Initializes a new <see cref="AsyncTaskMethodBuilder"/>.</summary> /// <returns>The initialized <see cref="AsyncTaskMethodBuilder"/>.</returns> public static AsyncTaskMethodBuilder Create() { AsyncTaskMethodBuilder atmb = default(AsyncTaskMethodBuilder); // On ProjectN we will eagerly initalize the task and it's Id if the debugger is attached atmb.m_task = (Task<VoidTaskResult>)atmb.GetTaskIfDebuggingEnabled(); if (atmb.m_task != null) { int i = atmb.m_task.Id; } return atmb; } /// <summary>Initiates the builder's execution with the associated state machine.</summary> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="stateMachine">The state machine instance, passed by reference.</param> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine => AsyncMethodBuilderCore.Start(ref stateMachine); /// <summary>Associates the builder with the state machine it represents.</summary> /// <param name="stateMachine">The heap-allocated state machine object.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The builder is incorrectly initialized.</exception> public void SetStateMachine(IAsyncStateMachine stateMachine) { AsyncMethodBuilderCore.SetStateMachine(stateMachine, m_moveNextAction); // argument validation handled by AsyncMethodBuilderCore } /// <summary> /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// </summary> /// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> public void AwaitOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { EnsureTaskCreated(); AsyncMethodBuilderCore.CallOnCompleted( AsyncMethodBuilderCore.GetCompletionAction(ref m_moveNextAction, ref stateMachine, this.GetTaskIfDebuggingEnabled()), ref awaiter); } /// <summary> /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// </summary> /// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { EnsureTaskCreated(); AsyncMethodBuilderCore.CallUnsafeOnCompleted( AsyncMethodBuilderCore.GetCompletionAction(ref m_moveNextAction, ref stateMachine, this.GetTaskIfDebuggingEnabled()), ref awaiter); } [MethodImpl(MethodImplOptions.NoInlining)] private void EnsureTaskCreated() { if (m_task == null) m_task = new Task<VoidTaskResult>(); } /// <summary>Gets the <see cref="System.Threading.Tasks.Task"/> for this builder.</summary> /// <returns>The <see cref="System.Threading.Tasks.Task"/> representing the builder's asynchronous operation.</returns> /// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception> public Task Task { get { return m_task ?? (m_task = new Task<VoidTaskResult>()); } } /// <summary> /// Completes the <see cref="System.Threading.Tasks.Task"/> in the /// <see cref="System.Threading.Tasks.TaskStatus">RanToCompletion</see> state. /// </summary> /// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception> /// <exception cref="System.InvalidOperationException">The task has already completed.</exception> [MethodImpl(MethodImplOptions.NoInlining)] public void SetResult() { var task = m_task; if (task == null) m_task = s_cachedCompleted; else { if (DebuggerSupport.LoggingOn) DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, task, AsyncStatus.Completed); DebuggerSupport.RemoveFromActiveTasks(task); if (!task.TrySetResult(default(VoidTaskResult))) throw new InvalidOperationException(SR.TaskT_TransitionToFinal_AlreadyCompleted); } } /// <summary> /// Completes the <see cref="System.Threading.Tasks.Task"/> in the /// <see cref="System.Threading.Tasks.TaskStatus">Faulted</see> state with the specified exception. /// </summary> /// <param name="exception">The <see cref="System.Exception"/> to use to fault the task.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="exception"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception> /// <exception cref="System.InvalidOperationException">The task has already completed.</exception> [MethodImpl(MethodImplOptions.NoInlining)] public void SetException(Exception exception) { SetException(this.Task, exception); } [MethodImpl(MethodImplOptions.NoInlining)] internal static void SetException(Task task, Exception exception) { if (exception == null) throw new ArgumentNullException(nameof(exception)); // If the exception represents cancellation, cancel the task. Otherwise, fault the task. var oce = exception as OperationCanceledException; bool successfullySet = oce != null ? task.TrySetCanceled(oce.CancellationToken, oce) : task.TrySetException(exception); // Unlike with TaskCompletionSource, we do not need to spin here until m_task is completed, // since AsyncTaskMethodBuilder.SetException should not be immediately followed by any code // that depends on the task having completely completed. Moreover, with correct usage, // SetResult or SetException should only be called once, so the Try* methods should always // return true, so no spinning would be necessary anyway (the spinning in TCS is only relevant // if another thread won the race to complete the task). if (!successfullySet) { throw new InvalidOperationException(SR.TaskT_TransitionToFinal_AlreadyCompleted); } } /// <summary> /// Called by the debugger to request notification when the first wait operation /// (await, Wait, Result, etc.) on this builder's task completes. /// </summary> /// <param name="enabled"> /// true to enable notification; false to disable a previously set notification. /// </param> internal void SetNotificationForWaitCompletion(bool enabled) { // Get the task (forcing initialization if not already initialized), and set debug notification Task.SetNotificationForWaitCompletion(enabled); } /// <summary> /// Gets an object that may be used to uniquely identify this builder to the debugger. /// </summary> /// <remarks> /// This property lazily instantiates the ID in a non-thread-safe manner. /// It must only be used by the debugger, and only in a single-threaded manner /// when no other threads are in the middle of accessing this property or this.Task. /// </remarks> private object ObjectIdForDebugger { get { return this.Task; } } } /// <summary> /// Provides a builder for asynchronous methods that return <see cref="System.Threading.Tasks.Task{TResult}"/>. /// This type is intended for compiler use only. /// </summary> /// <remarks> /// AsyncTaskMethodBuilder{TResult} is a value type, and thus it is copied by value. /// Prior to being copied, one of its Task, SetResult, or SetException members must be accessed, /// or else the copies may end up building distinct Task instances. /// </remarks> public struct AsyncTaskMethodBuilder<TResult> { #if false /// <summary>A cached task for default(TResult).</summary> internal static readonly Task<TResult> s_defaultResultTask = AsyncTaskCache.CreateCacheableTask(default(TResult)); #endif private Action m_moveNextAction; // WARNING: We allow diagnostic tools to directly inspect this member (m_task). // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. // Get in touch with the diagnostics team if you have questions. // WARNING: For performance reasons, the m_task field is lazily initialized. // For correct results, the struct AsyncTaskMethodBuilder<TResult> must // always be used from the same location/copy, at least until m_task is // initialized. If that guarantee is broken, the field could end up being // initialized on the wrong copy. /// <summary>The lazily-initialized built task.</summary> private Task<TResult> m_task; // lazily-initialized: must not be readonly /// <summary>Initializes a new <see cref="AsyncTaskMethodBuilder"/>.</summary> /// <returns>The initialized <see cref="AsyncTaskMethodBuilder"/>.</returns> public static AsyncTaskMethodBuilder<TResult> Create() { AsyncTaskMethodBuilder<TResult> atmb = new AsyncTaskMethodBuilder<TResult>(); // On ProjectN we will eagerly initalize the task and it's Id if the debugger is attached atmb.m_task = (Task<TResult>)atmb.GetTaskIfDebuggingEnabled(); if (atmb.m_task != null) { int i = atmb.m_task.Id; } return atmb; } /// <summary>Initiates the builder's execution with the associated state machine.</summary> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="stateMachine">The state machine instance, passed by reference.</param> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine => AsyncMethodBuilderCore.Start(ref stateMachine); /// <summary>Associates the builder with the state machine it represents.</summary> /// <param name="stateMachine">The heap-allocated state machine object.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The builder is incorrectly initialized.</exception> public void SetStateMachine(IAsyncStateMachine stateMachine) { AsyncMethodBuilderCore.SetStateMachine(stateMachine, m_moveNextAction); // argument validation handled by AsyncMethodBuilderCore } /// <summary> /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// </summary> /// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> public void AwaitOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { // If this is our first await, we're not boxed yet. Set up our Task now, so it will be // visible to both the non-boxed and boxed builders. EnsureTaskCreated(); AsyncMethodBuilderCore.CallOnCompleted( AsyncMethodBuilderCore.GetCompletionAction(ref m_moveNextAction, ref stateMachine, this.GetTaskIfDebuggingEnabled()), ref awaiter); } /// <summary> /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// </summary> /// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { // If this is our first await, we're not boxed yet. Set up our Task now, so it will be // visible to both the non-boxed and boxed builders. EnsureTaskCreated(); AsyncMethodBuilderCore.CallUnsafeOnCompleted( AsyncMethodBuilderCore.GetCompletionAction(ref m_moveNextAction, ref stateMachine, this.GetTaskIfDebuggingEnabled()), ref awaiter); } [MethodImpl(MethodImplOptions.NoInlining)] private void EnsureTaskCreated() { if (m_task == null) m_task = new Task<TResult>(); } /// <summary>Gets the <see cref="System.Threading.Tasks.Task{TResult}"/> for this builder.</summary> /// <returns>The <see cref="System.Threading.Tasks.Task{TResult}"/> representing the builder's asynchronous operation.</returns> public Task<TResult> Task { get { // Get and return the task. If there isn't one, first create one and store it. var task = m_task; if (task == null) { m_task = task = new Task<TResult>(); } return task; } } /// <summary> /// Completes the <see cref="System.Threading.Tasks.Task{TResult}"/> in the /// <see cref="System.Threading.Tasks.TaskStatus">RanToCompletion</see> state with the specified result. /// </summary> /// <param name="result">The result to use to complete the task.</param> /// <exception cref="System.InvalidOperationException">The task has already completed.</exception> [MethodImpl(MethodImplOptions.NoInlining)] public void SetResult(TResult result) { // Get the currently stored task, which will be non-null if get_Task has already been accessed. // If there isn't one, get a task and store it. var task = m_task; if (task == null) { m_task = GetTaskForResult(result); Debug.Assert(m_task != null, "GetTaskForResult should never return null"); } // Slow path: complete the existing task. else { if (DebuggerSupport.LoggingOn) DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, task, AsyncStatus.Completed); DebuggerSupport.RemoveFromActiveTasks(task); if (!task.TrySetResult(result)) { throw new InvalidOperationException(SR.TaskT_TransitionToFinal_AlreadyCompleted); } } } /// <summary> /// Completes the <see cref="System.Threading.Tasks.Task{TResult}"/> in the /// <see cref="System.Threading.Tasks.TaskStatus">Faulted</see> state with the specified exception. /// </summary> /// <param name="exception">The <see cref="System.Exception"/> to use to fault the task.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="exception"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The task has already completed.</exception> [MethodImpl(MethodImplOptions.NoInlining)] public void SetException(Exception exception) { AsyncTaskMethodBuilder.SetException(this.Task, exception); } /// <summary> /// Called by the debugger to request notification when the first wait operation /// (await, Wait, Result, etc.) on this builder's task completes. /// </summary> /// <param name="enabled"> /// true to enable notification; false to disable a previously set notification. /// </param> /// <remarks> /// This should only be invoked from within an asynchronous method, /// and only by the debugger. /// </remarks> internal void SetNotificationForWaitCompletion(bool enabled) { // Get the task (forcing initialization if not already initialized), and set debug notification this.Task.SetNotificationForWaitCompletion(enabled); } /// <summary> /// Gets an object that may be used to uniquely identify this builder to the debugger. /// </summary> /// <remarks> /// This property lazily instantiates the ID in a non-thread-safe manner. /// It must only be used by the debugger, and only in a single-threaded manner /// when no other threads are in the middle of accessing this property or this.Task. /// </remarks> private object ObjectIdForDebugger { get { return this.Task; } } /// <summary> /// Gets a task for the specified result. This will either /// be a cached or new task, never null. /// </summary> /// <param name="result">The result for which we need a task.</param> /// <returns>The completed task containing the result.</returns> internal static Task<TResult> GetTaskForResult(TResult result) { // Currently NUTC does not perform the optimization needed by this method. The result is that // every call to this method results in quite a lot of work, including many allocations, which // is the opposite of the intent. For now, let's just return a new Task each time. // Bug 719350 tracks re-optimizing this in ProjectN. #if false // The goal of this function is to be give back a cached task if possible, // or to otherwise give back a new task. To give back a cached task, // we need to be able to evaluate the incoming result value, and we need // to avoid as much overhead as possible when doing so, as this function // is invoked as part of the return path from every async method. // Most tasks won't be cached, and thus we need the checks for those that are // to be as close to free as possible. This requires some trickiness given the // lack of generic specialization in .NET. // // Be very careful when modifying this code. It has been tuned // to comply with patterns recognized by both 32-bit and 64-bit JITs. // If changes are made here, be sure to look at the generated assembly, as // small tweaks can have big consequences for what does and doesn't get optimized away. // // Note that this code only ever accesses a static field when it knows it'll // find a cached value, since static fields (even if readonly and integral types) // require special access helpers in this NGEN'd and domain-neutral. if (null != (object)default(TResult)) // help the JIT avoid the value type branches for ref types { // Special case simple value types: // - Boolean // - Byte, SByte // - Char // - Int32, UInt32 // - Int64, UInt64 // - Int16, UInt16 // - IntPtr, UIntPtr // As of .NET 4.5, the (Type)(object)result pattern used below // is recognized and optimized by both 32-bit and 64-bit JITs. // For Boolean, we cache all possible values. if (typeof(TResult) == typeof(Boolean)) // only the relevant branches are kept for each value-type generic instantiation { Boolean value = (Boolean)(object)result; Task<Boolean> task = value ? AsyncTaskCache.TrueTask : AsyncTaskCache.FalseTask; return (Task<TResult>)(Task)(task);// JitHelpers.UnsafeCast<Task<TResult>>(task); // UnsafeCast avoids type check we know will succeed } // For Int32, we cache a range of common values, e.g. [-1,4). else if (typeof(TResult) == typeof(Int32)) { // Compare to constants to avoid static field access if outside of cached range. // We compare to the upper bound first, as we're more likely to cache miss on the upper side than on the // lower side, due to positive values being more common than negative as return values. Int32 value = (Int32)(object)result; if (value < AsyncTaskCache.EXCLUSIVE_INT32_MAX && value >= AsyncTaskCache.INCLUSIVE_INT32_MIN) { Task<Int32> task = AsyncTaskCache.Int32Tasks[value - AsyncTaskCache.INCLUSIVE_INT32_MIN]; return (Task<TResult>)(Task)(task);// JitHelpers.UnsafeCast<Task<TResult>>(task); // UnsafeCast avoids a type check we know will succeed } } // For other known value types, we only special-case 0 / default(TResult). else if ( (typeof(TResult) == typeof(UInt32) && default(UInt32) == (UInt32)(object)result) || (typeof(TResult) == typeof(Byte) && default(Byte) == (Byte)(object)result) || (typeof(TResult) == typeof(SByte) && default(SByte) == (SByte)(object)result) || (typeof(TResult) == typeof(Char) && default(Char) == (Char)(object)result) || (typeof(TResult) == typeof(Int64) && default(Int64) == (Int64)(object)result) || (typeof(TResult) == typeof(UInt64) && default(UInt64) == (UInt64)(object)result) || (typeof(TResult) == typeof(Int16) && default(Int16) == (Int16)(object)result) || (typeof(TResult) == typeof(UInt16) && default(UInt16) == (UInt16)(object)result) || (typeof(TResult) == typeof(IntPtr) && default(IntPtr) == (IntPtr)(object)result) || (typeof(TResult) == typeof(UIntPtr) && default(UIntPtr) == (UIntPtr)(object)result)) { return s_defaultResultTask; } } else if (result == null) // optimized away for value types { return s_defaultResultTask; } #endif // No cached task is available. Manufacture a new one for this result. return new Task<TResult>(result); } } /// <summary>Provides a cache of closed generic tasks for async methods.</summary> internal static class AsyncTaskCache { // All static members are initialized inline to ensure type is beforefieldinit #if false /// <summary>A cached Task{Boolean}.Result == true.</summary> internal static readonly Task<Boolean> TrueTask = CreateCacheableTask(true); /// <summary>A cached Task{Boolean}.Result == false.</summary> internal static readonly Task<Boolean> FalseTask = CreateCacheableTask(false); /// <summary>The cache of Task{Int32}.</summary> internal static readonly Task<Int32>[] Int32Tasks = CreateInt32Tasks(); /// <summary>The minimum value, inclusive, for which we want a cached task.</summary> internal const Int32 INCLUSIVE_INT32_MIN = -1; /// <summary>The maximum value, exclusive, for which we want a cached task.</summary> internal const Int32 EXCLUSIVE_INT32_MAX = 9; /// <summary>Creates an array of cached tasks for the values in the range [INCLUSIVE_MIN,EXCLUSIVE_MAX).</summary> private static Task<Int32>[] CreateInt32Tasks() { Debug.Assert(EXCLUSIVE_INT32_MAX >= INCLUSIVE_INT32_MIN, "Expected max to be at least min"); var tasks = new Task<Int32>[EXCLUSIVE_INT32_MAX - INCLUSIVE_INT32_MIN]; for (int i = 0; i < tasks.Length; i++) { tasks[i] = CreateCacheableTask(i + INCLUSIVE_INT32_MIN); } return tasks; } #endif /// <summary>Creates a non-disposable task.</summary> /// <typeparam name="TResult">Specifies the result type.</typeparam> /// <param name="result">The result for the task.</param> /// <returns>The cacheable task.</returns> internal static Task<TResult> CreateCacheableTask<TResult>(TResult result) { return new Task<TResult>(false, result, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, default(CancellationToken)); } } internal static class AsyncMethodBuilderCore { /// <summary>Initiates the builder's execution with the associated state machine.</summary> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="stateMachine">The state machine instance, passed by reference.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument is null (Nothing in Visual Basic).</exception> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { Thread currentThread = Thread.CurrentThread; ExecutionContext previousExecutionCtx = currentThread.ExecutionContext; SynchronizationContext previousSyncCtx = currentThread.SynchronizationContext; // Async state machines are required not to throw, so no need for try/finally here. stateMachine.MoveNext(); // The common case is that these have not changed, so avoid the cost of a write barrier if not needed. if (previousSyncCtx != currentThread.SynchronizationContext) { // Restore changed SynchronizationContext back to previous currentThread.SynchronizationContext = previousSyncCtx; } ExecutionContext currentExecutionCtx = currentThread.ExecutionContext; if (previousExecutionCtx != currentExecutionCtx) { // Restore changed ExecutionContext back to previous currentThread.ExecutionContext = previousExecutionCtx; if ((currentExecutionCtx != null && currentExecutionCtx.HasChangeNotifications) || (previousExecutionCtx != null && previousExecutionCtx.HasChangeNotifications)) { // There are change notifications; trigger any affected ExecutionContext.OnValuesChanged(currentExecutionCtx, previousExecutionCtx); } } } // // We are going to do something odd here, which may require some explaining. GetCompletionAction does quite a bit // of work, and is generic, parameterized over the type of the state machine. Since every async method has its own // state machine type, and they are basically all value types, we end up generating separate copies of this method // for every state machine. This adds up to a *lot* of code for an app that has many async methods. // // So, to save code size, we delegate all of the work to a non-generic helper. In the non-generic method, we have // to coerce our "ref TStateMachine" arg into both a "ref byte" and a "ref IAsyncResult." // // Note that this is only safe because: // // a) We are coercing byrefs only. These are just interior pointers; the runtime doesn't care *what* they point to. // b) We only read from one of those pointers after we're sure it's of the right type. This prevents us from, // say, ending up with a "heap reference" that's really a pointer to the stack. // [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Action GetCompletionAction<TStateMachine>(ref Action cachedMoveNextAction, ref TStateMachine stateMachine, Task taskIfDebuggingEnabled) where TStateMachine : IAsyncStateMachine { return GetCompletionActionHelper( ref cachedMoveNextAction, ref Unsafe.As<TStateMachine, byte>(ref stateMachine), EETypePtr.EETypePtrOf<TStateMachine>(), taskIfDebuggingEnabled); } [MethodImpl(MethodImplOptions.NoInlining)] private static unsafe Action GetCompletionActionHelper( ref Action cachedMoveNextAction, ref byte stateMachineAddress, EETypePtr stateMachineType, Task taskIfDebuggingEnabled) { // Alert a listening debugger that we can't make forward progress unless it slips threads. // If we don't do this, and a method that uses "await foo;" is invoked through funceval, // we could end up hooking up a callback to push forward the async method's state machine, // the debugger would then abort the funceval after it takes too long, and then continuing // execution could result in another callback being hooked up. At that point we have // multiple callbacks registered to push the state machine, which could result in bad behavior. //Debugger.NotifyOfCrossThreadDependency(); MoveNextRunner runner; if (cachedMoveNextAction != null) { Debug.Assert(cachedMoveNextAction.Target is MoveNextRunner); runner = (MoveNextRunner)cachedMoveNextAction.Target; runner.m_executionContext = ExecutionContext.Capture(); return cachedMoveNextAction; } runner = new MoveNextRunner(); runner.m_executionContext = ExecutionContext.Capture(); cachedMoveNextAction = runner.CallMoveNext; if (taskIfDebuggingEnabled != null) { runner.m_task = taskIfDebuggingEnabled; if (DebuggerSupport.LoggingOn) { IntPtr eeType = stateMachineType.RawValue; DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, taskIfDebuggingEnabled, "Async: " + eeType.ToString("x"), 0); } DebuggerSupport.AddToActiveTasks(taskIfDebuggingEnabled); } // // If the state machine is a value type, we need to box it now. // IAsyncStateMachine boxedStateMachine; if (stateMachineType.IsValueType) { object boxed = RuntimeImports.RhBox(stateMachineType, ref stateMachineAddress); Debug.Assert(boxed is IAsyncStateMachine); boxedStateMachine = Unsafe.As<IAsyncStateMachine>(boxed); } else { boxedStateMachine = Unsafe.As<byte, IAsyncStateMachine>(ref stateMachineAddress); } runner.m_stateMachine = boxedStateMachine; #if DEBUG // // In debug builds, we'll go ahead and call SetStateMachine, even though all of our initialization is done. // This way we'll keep forcing state machine implementations to keep the behavior needed by the CLR. // boxedStateMachine.SetStateMachine(boxedStateMachine); #endif // All done! return cachedMoveNextAction; } private class MoveNextRunner { internal IAsyncStateMachine m_stateMachine; internal ExecutionContext m_executionContext; internal Task m_task; internal void CallMoveNext() { Task task = m_task; if (task != null) DebuggerSupport.TraceSynchronousWorkStart(CausalityTraceLevel.Required, task, CausalitySynchronousWork.Execution); ExecutionContext.Run( m_executionContext, state => Unsafe.As<IAsyncStateMachine>(state).MoveNext(), m_stateMachine); if (task != null) DebuggerSupport.TraceSynchronousWorkCompletion(CausalityTraceLevel.Required, CausalitySynchronousWork.Execution); } } /// <summary>Associates the builder with the state machine it represents.</summary> /// <param name="stateMachine">The heap-allocated state machine object.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The builder is incorrectly initialized.</exception> internal static void SetStateMachine(IAsyncStateMachine stateMachine, Action cachedMoveNextAction) { // // Unlike the CLR, we do all of our initialization of the boxed state machine in GetCompletionAction. All we // need to do here is validate that everything's been set up correctly. Note that we don't call // IAsyncStateMachine.SetStateMachine in retail builds of the Framework, so we don't really expect a lot of calls // to this method. // if (stateMachine == null) throw new ArgumentNullException(nameof(stateMachine)); if (cachedMoveNextAction == null) throw new InvalidOperationException(SR.AsyncMethodBuilder_InstanceNotInitialized); Action unwrappedMoveNextAction = TryGetStateMachineForDebugger(cachedMoveNextAction); if (unwrappedMoveNextAction.Target != stateMachine) throw new InvalidOperationException(SR.AsyncMethodBuilder_InstanceNotInitialized); } [MethodImpl(MethodImplOptions.NoInlining)] internal static void CallOnCompleted<TAwaiter>(Action continuation, ref TAwaiter awaiter) where TAwaiter : INotifyCompletion { try { awaiter.OnCompleted(continuation); } catch (Exception e) { RuntimeAugments.ReportUnhandledException(e); } } [MethodImpl(MethodImplOptions.NoInlining)] internal static void CallUnsafeOnCompleted<TAwaiter>(Action continuation, ref TAwaiter awaiter) where TAwaiter : ICriticalNotifyCompletion { try { awaiter.UnsafeOnCompleted(continuation); } catch (Exception e) { RuntimeAugments.ReportUnhandledException(e); } } /// <summary>Throws the exception on the ThreadPool.</summary> /// <param name="exception">The exception to propagate.</param> /// <param name="targetContext">The target context on which to propagate the exception. Null to use the ThreadPool.</param> internal static void ThrowAsync(Exception exception, SynchronizationContext targetContext) { if (exception == null) throw new ArgumentNullException(nameof(exception)); // If the user supplied a SynchronizationContext... if (targetContext != null) { try { // Capture the exception into an ExceptionDispatchInfo so that its // stack trace and Watson bucket info will be preserved var edi = ExceptionDispatchInfo.Capture(exception); // Post the throwing of the exception to that context, and return. targetContext.Post(state => ((ExceptionDispatchInfo)state).Throw(), edi); return; } catch (Exception postException) { // If something goes horribly wrong in the Post, we'll treat this a *both* exceptions // going unhandled. RuntimeAugments.ReportUnhandledException(new AggregateException(exception, postException)); } } RuntimeAugments.ReportUnhandledException(exception); } // // This helper routine is targeted by the debugger. Its purpose is to remove any delegate wrappers introduced by the framework // that the debugger doesn't want to see. // [DependencyReductionRoot] internal static Action TryGetStateMachineForDebugger(Action action) { Object target = action.Target; MoveNextRunner runner = target as MoveNextRunner; if (runner != null) return runner.m_stateMachine.MoveNext; return action; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Text; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Lucene.Net.Analysis; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Search; using Lucene.Net.Store; using Lucene.Net.Util.Cache; namespace Lucene.Net.Test.Util.Cache { /// <summary> /// Summary description for TestCache /// </summary> [TestFixture] public class CacheTest { public CacheTest() { // // TODO: Add constructor logic here // } private RAMDirectory directory; private IndexReader reader; #region setup/teardown methods [SetUp] public void MyTestInitialize() { // create the initial index this.directory = new RAMDirectory(); this.CreateInitialIndex(this.directory); this.reader = IndexReader.Open(this.directory, true); } [TearDown] public void MyTestCleanup() { if (this.reader != null) { this.reader.Close(); this.reader = null; } if (this.directory != null) { this.directory.Close(); this.directory = null; } GC.Collect(); } #endregion [Test] public void CreateAddRetreive_SingleReader() { // warm the cache Terms t = MockCache.Instance.Get(this.reader, "Cached"); this.AssertCache(t, 1, "Cached", 10); // get the item from cache t = MockCache.Instance.Get(this.reader, "Cached"); this.AssertCache(t, 1, "Cached", 10); } [Test] public void CreateAddRetreive_TwoReaders() { RAMDirectory rd = new RAMDirectory(); this.CreateInitialIndex(rd); IndexReader r2 = IndexReader.Open(rd, true); // warm the cache with the class reader Terms t = MockCache.Instance.Get(this.reader, "Cached"); this.AssertCache(t, 1, "Cached", 10); // warm the cache with the method reader t = MockCache.Instance.Get(r2, "Cached"); this.AssertCache(t, 2, "Cached", 10); } [Test] public void GCRemoval() { // warm the cache Terms t = MockCache.Instance.Get(this.reader, "Cached"); this.AssertCache(t, 1, "Cached", 10); // add items to the existing index this.AddItemsToIndex(this.directory); IndexReader newReader = IndexReader.Open(this.directory, true); Assert.AreEqual(20, newReader.NumDocs()); // test the cache, the old item from the class reader should still be there t = MockCache.Instance.Get(newReader, "Cached"); this.AssertCache(t, 2, "Cached", 20); // close and null out the class reader, then force a GC this.reader.Close(); this.reader = null; GC.Collect(); // test the cache, should still have the item from the method reader // as there has been no addition to the cache since it was removed t = MockCache.Instance.Get(newReader, "Cached"); this.AssertCache(t, 2, "Cached", 20); // add another reader to the cache, which will clear out the class reader IndexReader newReader2 = IndexReader.Open(this.directory, true); t = MockCache.Instance.Get(newReader2, "Cached"); this.AssertCache(t, 2, "Cached", 20); newReader.Close(); newReader = null; newReader2.Close(); newReader2 = null; } private void AssertCache(Terms t, int keyCount, string field, int count) { Assert.AreEqual(keyCount, MockCache.Instance.KeyCount); Assert.AreEqual(field, t.Field); Assert.AreEqual(count, t.Count); } private void CreateInitialIndex(Directory dir) { IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.UNLIMITED); this.AddDocuments(writer, 0, 10); writer.Close(); } private void AddItemsToIndex(Directory dir) { IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), false, IndexWriter.MaxFieldLength.UNLIMITED); this.AddDocuments(writer, 20, 30); writer.Close(); } private void AddDocuments(IndexWriter writer, int start, int end) { for (int i = start; i < end; i++) { Document doc = new Document(); doc.Add(new Field("Cached", i.ToString(), Field.Store.NO, Field.Index.ANALYZED)); doc.Add(new Field("Skipped", i.ToString(), Field.Store.NO, Field.Index.ANALYZED)); writer.AddDocument(doc); } } /// <summary> /// Mock cache that caches the number of terms in a field. /// </summary> public class MockCache : SegmentCache<Terms> { /// <summary> /// Singleton. /// </summary> private static MockCache instance = new MockCache(); /// <summary> /// Singleton accessor. /// </summary> public static MockCache Instance { get { return MockCache.instance; } } /// <summary> /// Create the values for the cache. /// </summary> /// <param name="reader"></param> /// <param name="key">The key for the item in cache - in this case a field name.</param> /// <returns></returns> protected override Terms CreateValue(IndexReader reader, string key) { Terms item = new Terms(); item.Field = key; using (StringFieldEnumerator sfe = new StringFieldEnumerator(reader, key, false)) { foreach (string s in sfe.Terms) { item.Count++; } } return item; } } /// <summary> /// Simple item to cache. /// </summary> public class Terms { /// <summary> /// The name of the field. /// </summary> public string Field { get; set; } /// <summary> /// The number of terms in a field. /// </summary> public int Count { get; set; } /// <summary> /// Reset the instance. /// </summary> public void Reset() { this.Field = string.Empty; this.Count = 0; } } } }
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using GgpGrpc.Models; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Debugger.Interop; using NSubstitute; using NUnit.Framework; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.VisualStudio.Threading; using YetiVSI.DebugEngine; using YetiVSI.PortSupplier; using YetiVSI.Metrics; using YetiVSI.Shared.Metrics; using YetiCommon; using YetiCommon.SSH; using YetiVSITestsCommon; namespace YetiVSI.Test.PortSupplier { [TestFixture] class DebugPortTests { const string _reserverAccount = "reserver@test.com"; const string _testGameletIp = "1.2.3.4"; const string _testGameletTarget = _testGameletIp + ":44722"; const string _testGameletId = "gameletid"; const string _testGameletName = "gamelet name"; const string _testDebugSessionId = "abc123"; DebugProcess.Factory _processFactory; IProcessListRequest _processListRequest; IDialogUtil _dialogUtil; ISshManager _sshManager; IMetrics _metrics; DebugPort.Factory _portFactory; IDebugPortSupplier2 _portSupplier; [SetUp] public void SetUp() { _processFactory = Substitute.For<DebugProcess.Factory>(); _dialogUtil = Substitute.For<IDialogUtil>(); _sshManager = Substitute.For<ISshManager>(); _processListRequest = Substitute.For<IProcessListRequest>(); var processListRequestFactory = Substitute.For<ProcessListRequest.Factory>(); processListRequestFactory.Create().Returns(_processListRequest); var cancelableTaskFactory = FakeCancelableTask.CreateFactory(new JoinableTaskContext(), false); _metrics = Substitute.For<IMetrics>(); _portFactory = new DebugPort.Factory(_processFactory, processListRequestFactory, cancelableTaskFactory, _dialogUtil, _sshManager, _metrics, _reserverAccount); _portSupplier = Substitute.For<IDebugPortSupplier2>(); } [Test] public void GetPortRequest() { var port = _portFactory.Create(new Gamelet(), _portSupplier, _testDebugSessionId); Assert.AreEqual(AD7Constants.E_PORT_NO_REQUEST, port.GetPortRequest(out IDebugPortRequest2 request)); Assert.IsNull(request); } [Test] public void GetPortSupplier() { var port = _portFactory.Create(new Gamelet(), this._portSupplier, _testDebugSessionId); Assert.AreEqual(VSConstants.S_OK, port.GetPortSupplier(out IDebugPortSupplier2 portSupplier)); Assert.AreEqual(this._portSupplier, portSupplier); } [Test] public void GetPortNameById() { var port = _portFactory.Create(new Gamelet { Id = _testGameletId, DisplayName = "", ReserverEmail = _reserverAccount }, _portSupplier, _testDebugSessionId); Assert.AreEqual(VSConstants.S_OK, port.GetPortName(out string name)); Assert.AreEqual(_testGameletId, name); } [Test] public void GetPortNameByNameForReserver() { var port = _portFactory.Create(new Gamelet { Id = _testGameletId, DisplayName = _testGameletName, ReserverEmail = _reserverAccount }, _portSupplier, _testDebugSessionId); Assert.AreEqual(VSConstants.S_OK, port.GetPortName(out string name)); Assert.AreEqual("gamelet name [gameletid]", name); } [Test] public void GetPortNameForNonReserver() { var port = _portFactory.Create( new Gamelet { Id = _testGameletId, DisplayName = _testGameletName, ReserverEmail = "anotherReserver@test.com" }, _portSupplier, _testDebugSessionId); Assert.AreEqual(VSConstants.S_OK, port.GetPortName(out string name)); Assert.AreEqual("Reserver: anotherReserver@test.com; Instance: gamelet name", name); } [Test] public void GetDebugSessionId() { var port = _portFactory.Create(new Gamelet(), _portSupplier, _testDebugSessionId); Assert.AreEqual(_testDebugSessionId, ((DebugPort)port).DebugSessionId); } [Test] public void EnumProcesses() { var gamelet = new Gamelet { Id = _testGameletId, IpAddr = _testGameletIp }; var port = _portFactory.Create(gamelet, _portSupplier, _testDebugSessionId); _sshManager.EnableSshAsync(gamelet, Arg.Any<IAction>()).Returns(Task.FromResult(true)); var entry1 = new ProcessListEntry {Pid = 101, Title = "title1", Command = "command 1"}; var entry2 = new ProcessListEntry {Pid = 102, Title = "title2", Command = "command 2"}; _processListRequest.GetBySshAsync(new SshTarget(_testGameletTarget)) .Returns(new List<ProcessListEntry>() { entry1, entry2 }); var process1 = Substitute.For<IDebugProcess2>(); _processFactory.Create(port, entry1.Pid, entry1.Title, entry1.Command) .Returns(process1); var process2 = Substitute.For<IDebugProcess2>(); _processFactory.Create(port, entry2.Pid, entry2.Title, entry2.Command) .Returns(process2); Assert.AreEqual(VSConstants.S_OK, port.EnumProcesses(out IEnumDebugProcesses2 processesEnum)); var processes = new IDebugProcess2[2]; uint numFetched = 0; Assert.AreEqual(VSConstants.S_OK, processesEnum.Next((uint) processes.Length, processes, ref numFetched)); Assert.AreEqual(2, numFetched); Assert.AreEqual(processes[0], process1); Assert.AreEqual(processes[1], process2); AssertMetricRecorded(DeveloperEventType.Types.Type.VsiGameletsEnableSsh, DeveloperEventStatus.Types.Code.Success); AssertMetricRecorded(DeveloperEventType.Types.Type.VsiProcessList, DeveloperEventStatus.Types.Code.Success); } [Test] public void EnumProcessesError() { var gamelet = new Gamelet { Id = _testGameletId, IpAddr = _testGameletIp }; var port = _portFactory.Create(gamelet, _portSupplier, _testDebugSessionId); _sshManager.EnableSshAsync(gamelet, Arg.Any<IAction>()).Returns(Task.FromResult(true)); _processListRequest.When(x => x.GetBySshAsync(new SshTarget(_testGameletTarget))) .Do(x => { throw new ProcessException("test exception"); }); Assert.AreEqual(VSConstants.S_OK, port.EnumProcesses(out IEnumDebugProcesses2 processesEnum)); Assert.AreEqual(VSConstants.S_OK, processesEnum.GetCount(out uint count)); Assert.AreEqual(0, count); _dialogUtil.Received().ShowError(Arg.Is<string>(x => x.Contains("test exception")), Arg.Any<ProcessException>()); AssertMetricRecorded(DeveloperEventType.Types.Type.VsiGameletsEnableSsh, DeveloperEventStatus.Types.Code.Success); AssertMetricRecorded(DeveloperEventType.Types.Type.VsiProcessList, DeveloperEventStatus.Types.Code.ExternalToolUnavailable); } [Test] public void EnableSshError() { var gamelet = new Gamelet { Id = _testGameletId, IpAddr = _testGameletIp }; var port = _portFactory.Create(gamelet, _portSupplier, _testDebugSessionId); _sshManager.When(x => x.EnableSshAsync(gamelet, Arg.Any<IAction>())).Do(x => { throw new SshKeyException("test exception"); }); Assert.AreEqual(VSConstants.S_OK, port.EnumProcesses(out IEnumDebugProcesses2 processesEnum)); Assert.AreEqual(VSConstants.S_OK, processesEnum.GetCount(out uint count)); Assert.AreEqual(0, count); _dialogUtil.Received().ShowError(Arg.Is<string>(x => x.Contains("test exception")), Arg.Any<SshKeyException>()); AssertMetricRecorded(DeveloperEventType.Types.Type.VsiGameletsEnableSsh, DeveloperEventStatus.Types.Code.InternalError); } void AssertMetricRecorded(DeveloperEventType.Types.Type type, DeveloperEventStatus.Types.Code status) { _metrics.Received().RecordEvent( type, Arg.Is<DeveloperLogEvent>(p => p.StatusCode == status && p.DebugSessionIdStr == _testDebugSessionId)); } } }
using System; using System.Collections.Generic; using System.Linq; namespace Pidgin.Expression { /// <summary> /// Methods to create <see cref="OperatorTableRow{TToken, T}"/> values. /// </summary> public static class Operator { /// <summary> /// Creates a row in a table of operators which contains a single binary infix operator with the specified associativity. /// Can be combined with other <see cref="OperatorTableRow{TToken, T}"/>s using /// <see cref="OperatorTableRow{TToken, T}.And(OperatorTableRow{TToken, T})"/> to build a larger row. /// </summary> /// <param name="type">The associativity of the infix operator</param> /// <param name="opParser">A parser for an infix operator</param> /// <returns>A row in a table of operators which contains a single infix operator.</returns> public static OperatorTableRow<TToken, T> Binary<TToken, T>( BinaryOperatorType type, Parser<TToken, Func<T, T, T>> opParser ) { if (opParser == null) { throw new ArgumentNullException(nameof(opParser)); } switch (type) { case BinaryOperatorType.NonAssociative: return InfixN(opParser); case BinaryOperatorType.LeftAssociative: return InfixL(opParser); case BinaryOperatorType.RightAssociative: return InfixR(opParser); default: throw new ArgumentOutOfRangeException(nameof(type)); } } /// <summary> /// Creates a row in a table of operators which contains a single unary operator - either a prefix operator or a postfix operator. /// Can be combined with other <see cref="OperatorTableRow{TToken, T}"/>s using /// <see cref="OperatorTableRow{TToken, T}.And(OperatorTableRow{TToken, T})"/> to build a larger row. /// </summary> /// <param name="type">The type of the unary operator</param> /// <param name="opParser">A parser for a unary operator</param> /// <returns>A row in a table of operators which contains a single unary operator.</returns> public static OperatorTableRow<TToken, T> Unary<TToken, T>( UnaryOperatorType type, Parser<TToken, Func<T, T>> opParser ) { if (opParser == null) { throw new ArgumentNullException(nameof(opParser)); } switch (type) { case UnaryOperatorType.Prefix: return Prefix(opParser); case UnaryOperatorType.Postfix: return Postfix(opParser); default: throw new ArgumentOutOfRangeException(nameof(type)); } } /// <summary> /// Creates a row in a table of operators which contains a single non-associative infix operator. /// Can be combined with other <see cref="OperatorTableRow{TToken, T}"/>s using /// <see cref="OperatorTableRow{TToken, T}.And(OperatorTableRow{TToken, T})"/> to build a larger row. /// </summary> /// <param name="opParser">A parser for an infix operator</param> /// <returns>A row in a table of operators which contains a single infix operator.</returns> public static OperatorTableRow<TToken, T> InfixN<TToken, T>(Parser<TToken, Func<T, T, T>> opParser) { if (opParser == null) { throw new ArgumentNullException(nameof(opParser)); } return new OperatorTableRow<TToken, T>(new[]{ opParser }, null, null, null, null ); } /// <summary> /// Creates a row in a table of operators which contains a single left-associative infix operator. /// Can be combined with other <see cref="OperatorTableRow{TToken, T}"/>s using /// <see cref="OperatorTableRow{TToken, T}.And(OperatorTableRow{TToken, T})"/> to build a larger row. /// </summary> /// <param name="opParser">A parser for an infix operator</param> /// <returns>A row in a table of operators which contains a single infix operator.</returns> public static OperatorTableRow<TToken, T> InfixL<TToken, T>(Parser<TToken, Func<T, T, T>> opParser) { if (opParser == null) { throw new ArgumentNullException(nameof(opParser)); } return new OperatorTableRow<TToken, T>(null, new[]{ opParser }, null, null, null); } /// <summary> /// Creates a row in a table of operators which contains a single right-associative infix operator. /// Can be combined with other <see cref="OperatorTableRow{TToken, T}"/>s using /// <see cref="OperatorTableRow{TToken, T}.And(OperatorTableRow{TToken, T})"/> to build a larger row. /// </summary> /// <param name="opParser">A parser for an infix operator</param> /// <returns>A row in a table of operators which contains a single infix operator.</returns> public static OperatorTableRow<TToken, T> InfixR<TToken, T>(Parser<TToken, Func<T, T, T>> opParser) { if (opParser == null) { throw new ArgumentNullException(nameof(opParser)); } return new OperatorTableRow<TToken, T>(null, null, new[]{ opParser }, null, null); } /// <summary> /// Creates a row in a table of operators which contains a single prefix operator. /// Can be combined with other <see cref="OperatorTableRow{TToken, T}"/>s using /// <see cref="OperatorTableRow{TToken, T}.And(OperatorTableRow{TToken, T})"/> to build a larger row. /// </summary> /// <param name="opParser">A parser for an prefix operator</param> /// <returns>A row in a table of operators which contains a single prefix operator.</returns> public static OperatorTableRow<TToken, T> Prefix<TToken, T>(Parser<TToken, Func<T, T>> opParser) { if (opParser == null) { throw new ArgumentNullException(nameof(opParser)); } return new OperatorTableRow<TToken, T>(null, null, null, new[]{ opParser }, null); } /// <summary> /// Creates a row in a table of operators which contains a single postfix operator. /// Can be combined with other <see cref="OperatorTableRow{TToken, T}"/>s using /// <see cref="OperatorTableRow{TToken, T}.And(OperatorTableRow{TToken, T})"/> to build a larger row. /// </summary> /// <param name="opParser">A parser for an postfix operator</param> /// <returns>A row in a table of operators which contains a single postfix operator.</returns> public static OperatorTableRow<TToken, T> Postfix<TToken, T>(Parser<TToken, Func<T, T>> opParser) { if (opParser == null) { throw new ArgumentNullException(nameof(opParser)); } return new OperatorTableRow<TToken, T>(null, null, null, null, new[]{ opParser }); } /// <summary> /// Creates a row in a table of operators which contains a chainable collection of prefix operators. /// By default <see cref="Prefix"/> operators can only appear onc, so <c>- - 1</c> would not be parsed as "minus minus 1". /// /// This method is equivalent to: /// <code> /// Prefix( /// OneOf(opParsers) /// .AtLeastOnce() /// .Select&lt;Func&lt;T, T&gt;&gt;(fs => z => fs.AggregateR(z, (f, x) => f(x))) /// ) /// </code> /// </summary> /// <param name="opParsers">A collection of parsers for individual prefix operators</param> /// <returns>A row in a table of operators which contains a chainable collection of prefix operators</returns> public static OperatorTableRow<TToken, T> PrefixChainable<TToken, T>(IEnumerable<Parser<TToken, Func<T, T>>> opParsers) => Prefix( Parser.OneOf(opParsers) .AtLeastOncePooled() .Select<Func<T, T>>(fs => z => { for (var i = fs.Count - 1; i >= 0; i--) { z = fs[i](z); } fs.Dispose(); return z; } ) ); /// <summary> /// Creates a row in a table of operators which contains a chainable collection of prefix operators. /// By default <see cref="Prefix"/> operators can only appear onc, so <c>- - 1</c> would not be parsed as "minus minus 1". /// /// This method is equivalent to: /// <code> /// Prefix( /// OneOf(opParsers) /// .AtLeastOnce() /// .Select&lt;Func&lt;T, T&gt;&gt;(fs => z => fs.AggregateR(z, (f, x) => f(x))) /// ) /// </code> /// </summary> /// <param name="opParsers">A collection of parsers for individual prefix operators</param> /// <returns>A row in a table of operators which contains a chainable collection of prefix operators</returns> public static OperatorTableRow<TToken, T> PrefixChainable<TToken, T>(params Parser<TToken, Func<T, T>>[] opParsers) => PrefixChainable(opParsers.AsEnumerable()); /// <summary> /// Creates a row in a table of operators which contains a chainable collection of postfix operators. /// By default <see cref="Postfix"/> operators can only appear onc, so <c>foo()()</c> would not be parsed as "call(call(foo))". /// /// This method is equivalent to: /// <code> /// Postfix( /// OneOf(opParsers) /// .AtLeastOnce() /// .Select&lt;Func&lt;T, T&gt;&gt;(fs => z => fs.Aggregate(z, (x, f) => f(x))) /// ) /// </code> /// </summary> /// <param name="opParsers">A collection of parsers for individual postfix operators</param> /// <returns>A row in a table of operators which contains a chainable collection of postfix operators</returns> public static OperatorTableRow<TToken, T> PostfixChainable<TToken, T>(IEnumerable<Parser<TToken, Func<T, T>>> opParsers) => Postfix( Parser.OneOf(opParsers) .AtLeastOncePooled() .Select<Func<T, T>>(fs => z => { for (var i = 0; i < fs.Count; i++) { z = fs[i](z); } fs.Dispose(); return z; } ) ); /// <summary> /// Creates a row in a table of operators which contains a chainable collection of postfix operators. /// By default <see cref="Postfix"/> operators can only appear onc, so <c>foo()()</c> would not be parsed as "call(call(foo))". /// /// This method is equivalent to: /// <code> /// Postfix( /// OneOf(opParsers) /// .AtLeastOnce() /// .Select&lt;Func&lt;T, T&gt;&gt;(fs => z => fs.Aggregate(z, (x, f) => f(x))) /// ) /// </code> /// </summary> /// <param name="opParsers">A collection of parsers for individual postfix operators</param> /// <returns>A row in a table of operators which contains a chainable collection of postfix operators</returns> public static OperatorTableRow<TToken, T> PostfixChainable<TToken, T>(params Parser<TToken, Func<T, T>>[] opParsers) => PostfixChainable(opParsers.AsEnumerable()); } }
// 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 DuplicateOddIndexedSingle() { var test = new SimpleUnaryOpTest__DuplicateOddIndexedSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__DuplicateOddIndexedSingle { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__DuplicateOddIndexedSingle testClass) { var result = Avx.DuplicateOddIndexed(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__DuplicateOddIndexedSingle testClass) { fixed (Vector256<Single>* pFld1 = &_fld1) { var result = Avx.DuplicateOddIndexed( Avx.LoadVector256((Single*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector256<Single> _clsVar1; private Vector256<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__DuplicateOddIndexedSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); } public SimpleUnaryOpTest__DuplicateOddIndexedSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.DuplicateOddIndexed( Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.DuplicateOddIndexed( Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.DuplicateOddIndexed( Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.DuplicateOddIndexed), new Type[] { typeof(Vector256<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.DuplicateOddIndexed), new Type[] { typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.DuplicateOddIndexed), new Type[] { typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.DuplicateOddIndexed( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Single>* pClsVar1 = &_clsVar1) { var result = Avx.DuplicateOddIndexed( Avx.LoadVector256((Single*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr); var result = Avx.DuplicateOddIndexed(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)); var result = Avx.DuplicateOddIndexed(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)); var result = Avx.DuplicateOddIndexed(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__DuplicateOddIndexedSingle(); var result = Avx.DuplicateOddIndexed(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__DuplicateOddIndexedSingle(); fixed (Vector256<Single>* pFld1 = &test._fld1) { var result = Avx.DuplicateOddIndexed( Avx.LoadVector256((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.DuplicateOddIndexed(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Single>* pFld1 = &_fld1) { var result = Avx.DuplicateOddIndexed( Avx.LoadVector256((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.DuplicateOddIndexed(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx.DuplicateOddIndexed( Avx.LoadVector256((Single*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(firstOp[1]) != BitConverter.SingleToInt32Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((i % 2 == 0) ? (BitConverter.SingleToInt32Bits(firstOp[i + 1]) != BitConverter.SingleToInt32Bits(result[i])) : (BitConverter.SingleToInt32Bits(firstOp[i]) != BitConverter.SingleToInt32Bits(result[i]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.DuplicateOddIndexed)}<Single>(Vector256<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Subjects; using Avalonia.Collections; using Avalonia.Controls.Utils; using Avalonia.Layout; using Avalonia.VisualTree; namespace Avalonia.Controls { /// <summary> /// Shared size scope implementation. /// Shares the size information between participating grids. /// An instance of this class is attached to every <see cref="Control"/> that has its /// IsSharedSizeScope property set to true. /// </summary> internal sealed class SharedSizeScopeHost : IDisposable { private enum MeasurementState { Invalidated, Measuring, Cached } /// <summary> /// Class containing the measured rows/columns for a single grid. /// Monitors changes to the row/column collections as well as the SharedSizeGroup changes /// for the individual items in those collections. /// Notifies the <see cref="SharedSizeScopeHost"/> of SharedSizeGroup changes. /// </summary> private sealed class MeasurementCache : IDisposable { readonly CompositeDisposable _subscriptions; readonly Subject<(string, string, MeasurementResult)> _groupChanged = new Subject<(string, string, MeasurementResult)>(); public ISubject<(string oldName, string newName, MeasurementResult result)> GroupChanged => _groupChanged; public MeasurementCache(Grid grid) { Grid = grid; Results = grid.RowDefinitions.Cast<DefinitionBase>() .Concat(grid.ColumnDefinitions) .Select(d => new MeasurementResult(grid, d)) .ToList(); grid.RowDefinitions.CollectionChanged += DefinitionsCollectionChanged; grid.ColumnDefinitions.CollectionChanged += DefinitionsCollectionChanged; _subscriptions = new CompositeDisposable( Disposable.Create(() => grid.RowDefinitions.CollectionChanged -= DefinitionsCollectionChanged), Disposable.Create(() => grid.ColumnDefinitions.CollectionChanged -= DefinitionsCollectionChanged), grid.RowDefinitions.TrackItemPropertyChanged(DefinitionPropertyChanged), grid.ColumnDefinitions.TrackItemPropertyChanged(DefinitionPropertyChanged)); } // method to be hooked up once RowDefinitions/ColumnDefinitions collections can be replaced on a grid private void DefinitionsChanged(object sender, AvaloniaPropertyChangedEventArgs e) { // route to collection changed as a Reset. DefinitionsCollectionChanged(null, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } private void DefinitionPropertyChanged(Tuple<object, PropertyChangedEventArgs> propertyChanged) { if (propertyChanged.Item2.PropertyName == nameof(DefinitionBase.SharedSizeGroup)) { var result = Results.Single(mr => ReferenceEquals(mr.Definition, propertyChanged.Item1)); var oldName = result.SizeGroup?.Name; var newName = (propertyChanged.Item1 as DefinitionBase).SharedSizeGroup; _groupChanged.OnNext((oldName, newName, result)); } } private void DefinitionsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { int offset = 0; if (sender is ColumnDefinitions) offset = Grid.RowDefinitions.Count; var newItems = e.NewItems?.OfType<DefinitionBase>().Select(db => new MeasurementResult(Grid, db)).ToList() ?? new List<MeasurementResult>(); var oldItems = e.OldStartingIndex >= 0 ? Results.GetRange(e.OldStartingIndex + offset, e.OldItems.Count) : new List<MeasurementResult>(); void NotifyNewItems() { foreach (var item in newItems) { if (string.IsNullOrEmpty(item.Definition.SharedSizeGroup)) continue; _groupChanged.OnNext((null, item.Definition.SharedSizeGroup, item)); } } void NotifyOldItems() { foreach (var item in oldItems) { if (string.IsNullOrEmpty(item.Definition.SharedSizeGroup)) continue; _groupChanged.OnNext((item.Definition.SharedSizeGroup, null, item)); } } switch (e.Action) { case NotifyCollectionChangedAction.Add: Results.InsertRange(e.NewStartingIndex + offset, newItems); NotifyNewItems(); break; case NotifyCollectionChangedAction.Remove: Results.RemoveRange(e.OldStartingIndex + offset, oldItems.Count); NotifyOldItems(); break; case NotifyCollectionChangedAction.Move: Results.RemoveRange(e.OldStartingIndex + offset, oldItems.Count); Results.InsertRange(e.NewStartingIndex + offset, oldItems); break; case NotifyCollectionChangedAction.Replace: Results.RemoveRange(e.OldStartingIndex + offset, oldItems.Count); Results.InsertRange(e.NewStartingIndex + offset, newItems); NotifyOldItems(); NotifyNewItems(); break; case NotifyCollectionChangedAction.Reset: oldItems = Results; newItems = Results = Grid.RowDefinitions.Cast<DefinitionBase>() .Concat(Grid.ColumnDefinitions) .Select(d => new MeasurementResult(Grid, d)) .ToList(); NotifyOldItems(); NotifyNewItems(); break; } } /// <summary> /// Updates the Results collection with Grid Measure results. /// </summary> /// <param name="rowResult">Result of the GridLayout.Measure method for the RowDefinitions in the grid.</param> /// <param name="columnResult">Result of the GridLayout.Measure method for the ColumnDefinitions in the grid.</param> public void UpdateMeasureResult(GridLayout.MeasureResult rowResult, GridLayout.MeasureResult columnResult) { MeasurementState = MeasurementState.Cached; for (int i = 0; i < Grid.RowDefinitions.Count; i++) { Results[i].MeasuredResult = rowResult.LengthList[i]; Results[i].MinLength = rowResult.MinLengths[i]; } for (int i = 0; i < Grid.ColumnDefinitions.Count; i++) { Results[i + Grid.RowDefinitions.Count].MeasuredResult = columnResult.LengthList[i]; Results[i + Grid.RowDefinitions.Count].MinLength = columnResult.MinLengths[i]; } } /// <summary> /// Clears the measurement cache, in preparation for the Measure pass. /// </summary> public void InvalidateMeasure() { var newItems = new List<MeasurementResult>(); var oldItems = new List<MeasurementResult>(); MeasurementState = MeasurementState.Invalidated; Results.ForEach(r => { r.MeasuredResult = double.NaN; r.SizeGroup?.Reset(); }); } /// <summary> /// Clears the <see cref="IObservable{T}"/> subscriptions. /// </summary> public void Dispose() { _subscriptions.Dispose(); _groupChanged.OnCompleted(); } /// <summary> /// Gets the <see cref="Grid"/> for which this cache has been created. /// </summary> public Grid Grid { get; } /// <summary> /// Gets the <see cref="MeasurementState"/> of this cache. /// </summary> public MeasurementState MeasurementState { get; private set; } /// <summary> /// Gets the list of <see cref="MeasurementResult"/> instances. /// </summary> /// <remarks> /// The list is a 1-1 map of the concatenation of RowDefinitions and ColumnDefinitions /// </remarks> public List<MeasurementResult> Results { get; private set; } } /// <summary> /// Class containing the Measure result for a single Row/Column in a grid. /// </summary> private class MeasurementResult { public MeasurementResult(Grid owningGrid, DefinitionBase definition) { OwningGrid = owningGrid; Definition = definition; MeasuredResult = double.NaN; } /// <summary> /// Gets the <see cref="RowDefinition"/>/<see cref="ColumnDefinition"/> related to this <see cref="MeasurementResult"/> /// </summary> public DefinitionBase Definition { get; } /// <summary> /// Gets or sets the actual result of the Measure operation for this column. /// </summary> public double MeasuredResult { get; set; } /// <summary> /// Gets or sets the Minimum constraint for a Row/Column - relevant for star Rows/Columns in unconstrained grids. /// </summary> public double MinLength { get; set; } /// <summary> /// Gets or sets the <see cref="Group"/> that this result belongs to. /// </summary> public Group SizeGroup { get; set; } /// <summary> /// Gets the Grid that is the parent of the Row/Column /// </summary> public Grid OwningGrid { get; } /// <summary> /// Calculates the effective length that this Row/Column wishes to enforce in the SharedSizeGroup. /// </summary> /// <returns>A tuple of length and the priority in the shared size group.</returns> public (double length, int priority) GetPriorityLength() { var length = (Definition as ColumnDefinition)?.Width ?? ((RowDefinition)Definition).Height; if (length.IsAbsolute) return (MeasuredResult, 1); if (length.IsAuto) return (MeasuredResult, 2); if (MinLength > 0) return (MinLength, 3); return (MeasuredResult, 4); } } /// <summary> /// Visitor class used to gather the final length for a given SharedSizeGroup. /// </summary> /// <remarks> /// The values are applied according to priorities defined in <see cref="MeasurementResult.GetPriorityLength"/>. /// </remarks> private class LentgthGatherer { /// <summary> /// Gets the final Length to be applied to every Row/Column in a SharedSizeGroup /// </summary> public double Length { get; private set; } private int gatheredPriority = 6; /// <summary> /// Visits the <paramref name="result"/> applying the result of <see cref="MeasurementResult.GetPriorityLength"/> to its internal cache. /// </summary> /// <param name="result">The <see cref="MeasurementResult"/> instance to visit.</param> public void Visit(MeasurementResult result) { var (length, priority) = result.GetPriorityLength(); if (gatheredPriority < priority) return; gatheredPriority = priority; if (gatheredPriority == priority) { Length = Math.Max(length,Length); } else { Length = length; } } } /// <summary> /// Representation of a SharedSizeGroup, containing Rows/Columns with the same SharedSizeGroup property value. /// </summary> private class Group { private double? cachedResult; private List<MeasurementResult> _results = new List<MeasurementResult>(); /// <summary> /// Gets the name of the SharedSizeGroup. /// </summary> public string Name { get; } public Group(string name) { Name = name; } /// <summary> /// Gets the collection of the <see cref="MeasurementResult"/> instances. /// </summary> public IReadOnlyList<MeasurementResult> Results => _results; /// <summary> /// Gets the final, calculated length for all Rows/Columns in the SharedSizeGroup. /// </summary> public double CalculatedLength => (cachedResult ?? (cachedResult = Gather())).Value; /// <summary> /// Clears the previously cached result in preparation for measurement. /// </summary> public void Reset() { cachedResult = null; } /// <summary> /// Ads a measurement result to this group and sets it's <see cref="MeasurementResult.SizeGroup"/> property /// to this instance. /// </summary> /// <param name="result">The <see cref="MeasurementResult"/> to include in this group.</param> public void Add(MeasurementResult result) { if (_results.Contains(result)) throw new AvaloniaInternalException( $"SharedSizeScopeHost: Invalid call to Group.Add - The SharedSizeGroup {Name} already contains the passed result"); result.SizeGroup = this; _results.Add(result); } /// <summary> /// Removes the measurement result from this group and clears its <see cref="MeasurementResult.SizeGroup"/> value. /// </summary> /// <param name="result">The <see cref="MeasurementResult"/> to clear.</param> public void Remove(MeasurementResult result) { if (!_results.Contains(result)) throw new AvaloniaInternalException( $"SharedSizeScopeHost: Invalid call to Group.Remove - The SharedSizeGroup {Name} does not contain the passed result"); result.SizeGroup = null; _results.Remove(result); } private double Gather() { var visitor = new LentgthGatherer(); _results.ForEach(visitor.Visit); return visitor.Length; } } private readonly AvaloniaList<MeasurementCache> _measurementCaches = new AvaloniaList<MeasurementCache>(); private readonly Dictionary<string, Group> _groups = new Dictionary<string, Group>(); private bool _invalidating; /// <summary> /// Removes the SharedSizeScope and notifies all affected grids of the change. /// </summary> public void Dispose() { while (_measurementCaches.Any()) _measurementCaches[0].Grid.SharedScopeChanged(); } /// <summary> /// Registers the grid in this SharedSizeScope, to be called when the grid is added to the visual tree. /// </summary> /// <param name="toAdd">The <see cref="Grid"/> to add to this scope.</param> internal void RegisterGrid(Grid toAdd) { if (_measurementCaches.Any(mc => ReferenceEquals(mc.Grid, toAdd))) throw new AvaloniaInternalException("SharedSizeScopeHost: tried to register a grid twice!"); var cache = new MeasurementCache(toAdd); _measurementCaches.Add(cache); AddGridToScopes(cache); } /// <summary> /// Removes the registration for a grid in this SharedSizeScope. /// </summary> /// <param name="toRemove">The <see cref="Grid"/> to remove.</param> internal void UnegisterGrid(Grid toRemove) { var cache = _measurementCaches.FirstOrDefault(mc => ReferenceEquals(mc.Grid, toRemove)); if (cache == null) throw new AvaloniaInternalException("SharedSizeScopeHost: tried to unregister a grid that wasn't registered before!"); _measurementCaches.Remove(cache); RemoveGridFromScopes(cache); cache.Dispose(); } /// <summary> /// Helper method to check if a grid needs to forward its Mesure results to, and requrest Arrange results from this scope. /// </summary> /// <param name="toCheck">The <see cref="Grid"/> that should be checked.</param> /// <returns>True if the grid should forward its calls.</returns> internal bool ParticipatesInScope(Grid toCheck) { return _measurementCaches.FirstOrDefault(mc => ReferenceEquals(mc.Grid, toCheck)) ?.Results.Any(r => r.SizeGroup != null) ?? false; } /// <summary> /// Notifies the SharedSizeScope that a grid had requested its measurement to be invalidated. /// Forwards the same call to all affected grids in this scope. /// </summary> /// <param name="grid">The <see cref="Grid"/> that had it's Measure invalidated.</param> internal void InvalidateMeasure(Grid grid) { // prevent stack overflow if (_invalidating) return; _invalidating = true; InvalidateMeasureImpl(grid); _invalidating = false; } /// <summary> /// Updates the measurement cache with the results of the <paramref name="grid"/> measurement pass. /// </summary> /// <param name="grid">The <see cref="Grid"/> that has been measured.</param> /// <param name="rowResult">Measurement result for the grid's <see cref="RowDefinitions"/></param> /// <param name="columnResult">Measurement result for the grid's <see cref="ColumnDefinitions"/></param> internal void UpdateMeasureStatus(Grid grid, GridLayout.MeasureResult rowResult, GridLayout.MeasureResult columnResult) { var cache = _measurementCaches.FirstOrDefault(mc => ReferenceEquals(mc.Grid, grid)); if (cache == null) throw new AvaloniaInternalException("SharedSizeScopeHost: Attempted to update measurement status for a grid that wasn't registered!"); cache.UpdateMeasureResult(rowResult, columnResult); } /// <summary> /// Calculates the measurement result including the impact of any SharedSizeGroups that might affect this grid. /// </summary> /// <param name="grid">The <see cref="Grid"/> that is being Arranged</param> /// <param name="rowResult">The <paramref name="grid"/>'s cached measurement result.</param> /// <param name="columnResult">The <paramref name="grid"/>'s cached measurement result.</param> /// <returns>Row and column measurement result updated with the SharedSizeScope constraints.</returns> internal (GridLayout.MeasureResult, GridLayout.MeasureResult) HandleArrange(Grid grid, GridLayout.MeasureResult rowResult, GridLayout.MeasureResult columnResult) { return ( Arrange(grid.RowDefinitions, rowResult), Arrange(grid.ColumnDefinitions, columnResult) ); } /// <summary> /// Invalidates the measure of all grids affected by the SharedSizeGroups contained within. /// </summary> /// <param name="grid">The <see cref="Grid"/> that is being invalidated.</param> private void InvalidateMeasureImpl(Grid grid) { var cache = _measurementCaches.FirstOrDefault(mc => ReferenceEquals(mc.Grid, grid)); if (cache == null) throw new AvaloniaInternalException( $"SharedSizeScopeHost: InvalidateMeasureImpl - called with a grid not present in the internal cache"); // already invalidated the cache, early out. if (cache.MeasurementState == MeasurementState.Invalidated) return; // we won't calculate, so we should not invalidate. if (!ParticipatesInScope(grid)) return; cache.InvalidateMeasure(); // maybe there is a condition to only call arrange on some of the calls? grid.InvalidateMeasure(); // find all the scopes within the invalidated grid var scopeNames = cache.Results .Where(mr => mr.SizeGroup != null) .Select(mr => mr.SizeGroup.Name) .Distinct(); // find all grids related to those scopes var otherGrids = scopeNames.SelectMany(sn => _groups[sn].Results) .Select(r => r.OwningGrid) .Where(g => g.IsMeasureValid) .Distinct(); // invalidate them as well foreach (var otherGrid in otherGrids) { InvalidateMeasureImpl(otherGrid); } } /// <summary> /// <see cref="IObserver{T}"/> callback notifying the scope that a <see cref="MeasurementResult"/> has changed its /// SharedSizeGroup /// </summary> /// <param name="change">Old and New name (either can be null) of the SharedSizeGroup, as well as the result.</param> private void SharedGroupChanged((string oldName, string newName, MeasurementResult result) change) { RemoveFromGroup(change.oldName, change.result); AddToGroup(change.newName, change.result); } /// <summary> /// Handles the impact of SharedSizeGroups on the Arrange of <see cref="RowDefinitions"/>/<see cref="ColumnDefinitions"/> /// </summary> /// <param name="definitions">Rows/Columns that were measured</param> /// <param name="measureResult">The initial measurement result.</param> /// <returns>Modified measure result</returns> private GridLayout.MeasureResult Arrange(IReadOnlyList<DefinitionBase> definitions, GridLayout.MeasureResult measureResult) { var conventions = measureResult.LeanLengthList.ToList(); var lengths = measureResult.LengthList.ToList(); var desiredLength = 0.0; for (int i = 0; i < definitions.Count; i++) { var definition = definitions[i]; // for empty SharedSizeGroups pass on unmodified result. if (string.IsNullOrEmpty(definition.SharedSizeGroup)) { desiredLength += measureResult.LengthList[i]; continue; } var group = _groups[definition.SharedSizeGroup]; // Length calculated over all Definitions participating in a SharedSizeGroup. var length = group.CalculatedLength; conventions[i] = new GridLayout.LengthConvention( new GridLength(length), measureResult.LeanLengthList[i].MinLength, measureResult.LeanLengthList[i].MaxLength ); lengths[i] = length; desiredLength += length; } return new GridLayout.MeasureResult( measureResult.ContainerLength, desiredLength, measureResult.GreedyDesiredLength,//?? conventions, lengths, measureResult.MinLengths); } /// <summary> /// Adds all measurement results for a grid to their repsective scopes. /// </summary> /// <param name="cache">The <see cref="MeasurementCache"/> for a grid to be added.</param> private void AddGridToScopes(MeasurementCache cache) { cache.GroupChanged.Subscribe(SharedGroupChanged); foreach (var result in cache.Results) { var scopeName = result.Definition.SharedSizeGroup; AddToGroup(scopeName, result); } } /// <summary> /// Handles adding the <see cref="MeasurementResult"/> to a SharedSizeGroup. /// Does nothing for empty SharedSizeGroups. /// </summary> /// <param name="scopeName">The name (can be null or empty) of the group to add the <paramref name="result"/> to.</param> /// <param name="result">The <see cref="MeasurementResult"/> to add to a scope.</param> private void AddToGroup(string scopeName, MeasurementResult result) { if (string.IsNullOrEmpty(scopeName)) return; if (!_groups.TryGetValue(scopeName, out var group)) _groups.Add(scopeName, group = new Group(scopeName)); group.Add(result); } /// <summary> /// Removes all measurement results for a grid from their respective scopes. /// </summary> /// <param name="cache">The <see cref="MeasurementCache"/> for a grid to be removed.</param> private void RemoveGridFromScopes(MeasurementCache cache) { foreach (var result in cache.Results) { var scopeName = result.Definition.SharedSizeGroup; RemoveFromGroup(scopeName, result); } } /// <summary> /// Handles removing the <see cref="MeasurementResult"/> from a SharedSizeGroup. /// Does nothing for empty SharedSizeGroups. /// </summary> /// <param name="scopeName">The name (can be null or empty) of the group to remove the <paramref name="result"/> from.</param> /// <param name="result">The <see cref="MeasurementResult"/> to remove from a scope.</param> private void RemoveFromGroup(string scopeName, MeasurementResult result) { if (string.IsNullOrEmpty(scopeName)) return; if (!_groups.TryGetValue(scopeName, out var group)) throw new AvaloniaInternalException($"SharedSizeScopeHost: The scope {scopeName} wasn't found in the shared size scope"); group.Remove(result); if (!group.Results.Any()) _groups.Remove(scopeName); } } }
// --------------------------------------------------------------------------- // <copyright file="GetAttachmentRequest.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the GetAttachmentRequest class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; /// <summary> /// Represents a GetAttachment request. /// </summary> internal sealed class GetAttachmentRequest : MultiResponseServiceRequest<GetAttachmentResponse>, IJsonSerializable { private List<Attachment> attachments = new List<Attachment>(); private List<string> attachmentIds = new List<string>(); private List<PropertyDefinitionBase> additionalProperties = new List<PropertyDefinitionBase>(); private BodyType? bodyType; /// <summary> /// Initializes a new instance of the <see cref="GetAttachmentRequest"/> class. /// </summary> /// <param name="service">The service.</param> /// <param name="errorHandlingMode"> Indicates how errors should be handled.</param> internal GetAttachmentRequest(ExchangeService service, ServiceErrorHandling errorHandlingMode) : base(service, errorHandlingMode) { } /// <summary> /// Validate request. /// </summary> internal override void Validate() { base.Validate(); if (this.Attachments.Count > 0) { EwsUtilities.ValidateParamCollection(this.Attachments, "Attachments"); } if (this.AttachmentIds.Count > 0) { EwsUtilities.ValidateParamCollection(this.AttachmentIds, "AttachmentIds"); } if (this.AttachmentIds.Count == 0 && this.Attachments.Count == 0) { throw new ArgumentException(Strings.CollectionIsEmpty, @"Attachments/AttachmentIds"); } for (int i = 0; i < this.AdditionalProperties.Count; i++) { EwsUtilities.ValidateParam(this.AdditionalProperties[i], string.Format("AdditionalProperties[{0}]", i)); } } /// <summary> /// Creates the service response. /// </summary> /// <param name="service">The service.</param> /// <param name="responseIndex">Index of the response.</param> /// <returns>Service response.</returns> internal override GetAttachmentResponse CreateServiceResponse(ExchangeService service, int responseIndex) { return new GetAttachmentResponse(this.Attachments.Count > 0 ? this.Attachments[responseIndex] : null); } /// <summary> /// Gets the expected response message count. /// </summary> /// <returns>Number of expected response messages.</returns> internal override int GetExpectedResponseMessageCount() { return this.Attachments.Count + this.AttachmentIds.Count; } /// <summary> /// Gets the name of the XML element. /// </summary> /// <returns>XML element name,</returns> internal override string GetXmlElementName() { return XmlElementNames.GetAttachment; } /// <summary> /// Gets the name of the response XML element. /// </summary> /// <returns>XML element name,</returns> internal override string GetResponseXmlElementName() { return XmlElementNames.GetAttachmentResponse; } /// <summary> /// Gets the name of the response message XML element. /// </summary> /// <returns>XML element name,</returns> internal override string GetResponseMessageXmlElementName() { return XmlElementNames.GetAttachmentResponseMessage; } /// <summary> /// Writes XML elements. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteElementsToXml(EwsServiceXmlWriter writer) { if (this.BodyType.HasValue || this.AdditionalProperties.Count > 0) { writer.WriteStartElement(XmlNamespace.Messages, XmlElementNames.AttachmentShape); if (this.BodyType.HasValue) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.BodyType, this.BodyType.Value); } if (this.AdditionalProperties.Count > 0) { PropertySet.WriteAdditionalPropertiesToXml(writer, this.AdditionalProperties); } writer.WriteEndElement(); // AttachmentShape } writer.WriteStartElement(XmlNamespace.Messages, XmlElementNames.AttachmentIds); foreach (Attachment attachment in this.Attachments) { this.WriteAttachmentIdXml(writer, attachment.Id); } foreach (string attachmentId in this.AttachmentIds) { this.WriteAttachmentIdXml(writer, attachmentId); } writer.WriteEndElement(); } /// <summary> /// Creates a JSON representation of this object. /// </summary> /// <param name="service">The service.</param> /// <returns> /// A Json value (either a JsonObject, an array of Json values, or a Json primitive) /// </returns> object IJsonSerializable.ToJson(ExchangeService service) { JsonObject jsonRequest = new JsonObject(); if (this.BodyType.HasValue || this.AdditionalProperties.Count > 0) { JsonObject jsonAttachmentShape = new JsonObject(); if (this.BodyType.HasValue) { jsonAttachmentShape.Add(XmlElementNames.BodyType, this.BodyType.Value); } if (this.AdditionalProperties.Count > 0) { PropertySet.WriteAdditionalPropertiesToJson(jsonAttachmentShape, service, this.AdditionalProperties); } jsonRequest.Add(XmlElementNames.AttachmentShape, jsonAttachmentShape); } List<object> attachmentIds = new List<object>(); foreach (Attachment attachment in this.Attachments) { this.AddJsonAttachmentIdToList(attachmentIds, attachment.Id); } foreach (string attachmentId in this.AttachmentIds) { this.AddJsonAttachmentIdToList(attachmentIds, attachmentId); } jsonRequest.Add(XmlElementNames.AttachmentIds, attachmentIds.ToArray()); return jsonRequest; } /// <summary> /// Gets the request version. /// </summary> /// <returns>Earliest Exchange version in which this request is supported.</returns> internal override ExchangeVersion GetMinimumRequiredServerVersion() { return ExchangeVersion.Exchange2007_SP1; } /// <summary> /// Gets the attachments. /// </summary> /// <value>The attachments.</value> public List<Attachment> Attachments { get { return this.attachments; } } /// <summary> /// Gets the attachment ids. /// </summary> /// <value>The attachment ids.</value> public List<string> AttachmentIds { get { return this.attachmentIds; } } /// <summary> /// Gets the additional properties. /// </summary> /// <value>The additional properties.</value> public List<PropertyDefinitionBase> AdditionalProperties { get { return this.additionalProperties; } } /// <summary> /// Gets or sets the type of the body. /// </summary> /// <value>The type of the body.</value> public BodyType? BodyType { get { return this.bodyType; } set { this.bodyType = value; } } /// <summary> /// Gets a value indicating whether the TimeZoneContext SOAP header should be emitted. /// </summary> /// <value> /// <c>true</c> if the time zone should be emitted; otherwise, <c>false</c>. /// </value> internal override bool EmitTimeZoneHeader { get { // we currently do not emit "AttachmentResponseShapeType.IncludeMimeContent" // return this.additionalProperties.Contains(ItemSchema.MimeContent); } } /// <summary> /// Writes attachment id elements. /// </summary> /// <param name="writer">The writer.</param> /// <param name="attachmentId">The attachment id.</param> private void WriteAttachmentIdXml(EwsServiceXmlWriter writer, string attachmentId) { writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.AttachmentId); writer.WriteAttributeValue(XmlAttributeNames.Id, attachmentId); writer.WriteEndElement(); } /// <summary> /// Add json attachment id to list /// </summary> /// <param name="attachmentIds">The attachment id object list.</param> /// <param name="attachmentId">The attachment id.</param> private void AddJsonAttachmentIdToList(List<object> attachmentIds, string attachmentId) { JsonObject jsonAttachmentId = new JsonObject(); jsonAttachmentId.Add(XmlAttributeNames.Id, attachmentId); attachmentIds.Add(jsonAttachmentId); } } }
using Xunit; using Should; using System.Linq; namespace AutoMapper.UnitTests { namespace ReverseMapping { using System; using System.Text.RegularExpressions; public class ReverseMapConventions : AutoMapperSpecBase { Rotator_Ad_Run _destination; DateTime _startDate = DateTime.Now, _endDate = DateTime.Now.AddHours(2); public class Rotator_Ad_Run { public DateTime Start_Date { get; set; } public DateTime End_Date { get; set; } public bool Enabled { get; set; } } public class RotatorAdRunViewModel { public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public bool Enabled { get; set; } } public class UnderscoreNamingConvention : INamingConvention { public Regex SplittingExpression { get; } = new Regex(@"\p{Lu}[a-z0-9]*(?=_?)"); public string SeparatorCharacter => "_"; } protected override void Establish_context() { Mapper.Initialize(config => { config.CreateProfile("MyMapperProfile", prf => { prf.SourceMemberNamingConvention = new UnderscoreNamingConvention(); prf.CreateMap<Rotator_Ad_Run, RotatorAdRunViewModel>(); }); config.CreateProfile("MyMapperProfile2", prf => { prf.DestinationMemberNamingConvention = new UnderscoreNamingConvention(); prf.CreateMap<RotatorAdRunViewModel, Rotator_Ad_Run>(); }); }); } protected override void Because_of() { _destination = Mapper.Map<RotatorAdRunViewModel, Rotator_Ad_Run>(new RotatorAdRunViewModel { Enabled = true, EndDate = _endDate, StartDate = _startDate }); } [Fact] public void Should_apply_the_convention_in_reverse() { _destination.Enabled.ShouldBeTrue(); _destination.End_Date.ShouldEqual(_endDate); _destination.Start_Date.ShouldEqual(_startDate); } } public class When_reverse_mapping_classes_with_simple_properties : AutoMapperSpecBase { private Source _source; public class Source { public int Value { get; set; } } public class Destination { public int Value { get; set; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.CreateMap<Source, Destination>() .ReverseMap(); }); } protected override void Because_of() { var dest = new Destination { Value = 10 }; _source = Mapper.Map<Destination, Source>(dest); } [Fact] public void Should_create_a_map_with_the_reverse_items() { _source.Value.ShouldEqual(10); } } public class When_validating_only_against_source_members_and_source_matches : NonValidatingSpecBase { public class Source { public int Value { get; set; } } public class Destination { public int Value { get; set; } public int Value2 { get; set; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.CreateMap<Source, Destination>(MemberList.Source); }); } [Fact] public void Should_only_map_source_members() { var typeMap = Mapper.FindTypeMapFor<Source, Destination>(); typeMap.GetPropertyMaps().Count().ShouldEqual(1); } [Fact] public void Should_not_throw_any_configuration_validation_errors() { typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Mapper.AssertConfigurationIsValid); } } public class When_validating_only_against_source_members_and_source_does_not_match : NonValidatingSpecBase { public class Source { public int Value { get; set; } public int Value2 { get; set; } } public class Destination { public int Value { get; set; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.CreateMap<Source, Destination>(MemberList.Source); }); } [Fact] public void Should_throw_a_configuration_validation_error() { typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Mapper.AssertConfigurationIsValid); } } public class When_validating_only_against_source_members_and_unmatching_source_members_are_manually_mapped : NonValidatingSpecBase { public class Source { public int Value { get; set; } public int Value2 { get; set; } } public class Destination { public int Value { get; set; } public int Value3 { get; set; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.CreateMap<Source, Destination>(MemberList.Source) .ForMember(dest => dest.Value3, opt => opt.MapFrom(src => src.Value2)); }); } [Fact] public void Should_not_throw_a_configuration_validation_error() { typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Mapper.AssertConfigurationIsValid); } } public class When_validating_only_against_source_members_and_unmatching_source_members_are_manually_mapped_with_resolvers : NonValidatingSpecBase { public class Source { public int Value { get; set; } public int Value2 { get; set; } } public class Destination { public int Value { get; set; } public int Value3 { get; set; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.CreateMap<Source, Destination>(MemberList.Source) .ForMember(dest => dest.Value3, opt => opt.ResolveUsing(src => src.Value2)) .ForSourceMember(src => src.Value2, opt => opt.Ignore()); }); } [Fact] public void Should_not_throw_a_configuration_validation_error() { typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Mapper.AssertConfigurationIsValid); } } public class When_reverse_mapping_and_ignoring_via_method : NonValidatingSpecBase { public class Source { public int Value { get; set; } } public class Dest { public int Value { get; set; } public int Ignored { get; set; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.CreateMap<Source, Dest>() .ForMember(d => d.Ignored, opt => opt.Ignore()) .ReverseMap(); }); } [Fact] public void Should_show_valid() { typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(() => Mapper.AssertConfigurationIsValid()); } } public class When_reverse_mapping_and_ignoring : AutoMapperSpecBase { public class Foo { public string Bar { get; set; } public string Baz { get; set; } } public class Foo2 { public string Bar { get; set; } public string Boo { get; set; } } [Fact] public void GetUnmappedPropertyNames_ShouldReturnBoo() { //Arrange Mapper.CreateMap<Foo, Foo2>(); var typeMap = Mapper.GetAllTypeMaps() .First(x => x.SourceType == typeof(Foo) && x.DestinationType == typeof(Foo2)); //Act var unmappedPropertyNames = typeMap.GetUnmappedPropertyNames(); //Assert unmappedPropertyNames[0].ShouldEqual("Boo"); } [Fact] public void WhenSecondCallTo_GetUnmappedPropertyNames_ShouldReturnBoo() { //Arrange Mapper.CreateMap<Foo, Foo2>().ReverseMap(); var typeMap = Mapper.GetAllTypeMaps() .First(x => x.SourceType == typeof(Foo2) && x.DestinationType == typeof(Foo)); //Act var unmappedPropertyNames = typeMap.GetUnmappedPropertyNames(); //Assert unmappedPropertyNames[0].ShouldEqual("Boo"); } [Fact] public void Should_not_throw_exception_for_unmapped_properties() { Mapper.CreateMap<Foo, Foo2>() .IgnoreAllNonExisting() .ReverseMap() .IgnoreAllNonExistingSource(); Mapper.AssertConfigurationIsValid(); } } public static class AutoMapperExtensions { // from http://stackoverflow.com/questions/954480/automapper-ignore-the-rest/6474397#6474397 public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this AutoMapper.IMappingExpression<TSource, TDestination> expression) { var sourceType = typeof(TSource); var destinationType = typeof(TDestination); var existingMaps = AutoMapper.Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType) && x.DestinationType.Equals(destinationType)); foreach (var property in existingMaps.GetUnmappedPropertyNames()) { expression.ForMember(property, opt => opt.Ignore()); } return expression; } public static IMappingExpression<TSource, TDestination> IgnoreAllNonExistingSource<TSource, TDestination>(this AutoMapper.IMappingExpression<TSource, TDestination> expression) { var sourceType = typeof(TSource); var destinationType = typeof(TDestination); var existingMaps = AutoMapper.Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType) && x.DestinationType.Equals(destinationType)); foreach (var property in existingMaps.GetUnmappedPropertyNames()) { expression.ForSourceMember(property, opt => opt.Ignore()); } return expression; } } } }
// 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 Xunit; using Xunit.Sdk; namespace Tests.Collections { public abstract class IDictionaryTest<TKey, TValue> : ICollectionTest<KeyValuePair<TKey, TValue>> { protected IDictionaryTest(bool isSynchronized) : base(isSynchronized) { } protected IDictionary<TKey, TValue> GetDictionary(object[] items) { return (IDictionary<TKey, TValue>)GetCollection(items); } [Theory] [InlineData(1)] [InlineData(16)] [InlineData(100)] public void KeysShouldBeCorrect(int count) { object[] items = GenerateItems(count); var expectedKeys = new TKey[items.Length]; for (int i = 0; i < items.Length; ++i) { expectedKeys[i] = ((KeyValuePair<TKey, TValue>)items[i]).Key; } IDictionary<TKey, TValue> dict = GetDictionary(items); CollectionAssert.Equal(expectedKeys, dict.Keys); IDictionary dict2 = dict as IDictionary; if (dict2 != null) { CollectionAssert.Equal(expectedKeys, dict2.Keys); } } [Theory] [InlineData(1)] [InlineData(16)] [InlineData(100)] public void ValuesShouldBeCorrect(int count) { object[] items = GenerateItems(count); var expectedValues = new TValue[items.Length]; for (int i = 0; i < items.Length; ++i) { expectedValues[i] = ((KeyValuePair<TKey, TValue>)items[i]).Value; } IDictionary<TKey, TValue> dict = GetDictionary(items); CollectionAssert.Equal(expectedValues, dict.Values); IDictionary dict2 = dict as IDictionary; if (dict2 != null) { CollectionAssert.Equal(expectedValues, dict2.Values); } } [Fact] public void ItemShouldBeCorrect() { object[] items = GenerateItems(16); IDictionary<TKey, TValue> dict = GetDictionary(items); var isReadOnly = dict.IsReadOnly; for (int i = 0; i < items.Length; ++i) { var pair = (KeyValuePair<TKey, TValue>)items[i]; Assert.Equal(pair.Value, dict[pair.Key]); if (isReadOnly) { Assert.Throws<NotSupportedException>(() => dict[pair.Key] = pair.Value); } else { dict[pair.Key] = pair.Value; } } IDictionary dict2 = dict as IDictionary; if (dict2 != null) { for (int i = 0; i < items.Length; ++i) { var pair = (KeyValuePair<TKey, TValue>)items[i]; Assert.Equal(pair.Value, dict2[pair.Key]); if (isReadOnly) { Assert.Throws<NotSupportedException>(() => dict2[pair.Key] = pair.Value); } else { dict2[pair.Key] = pair.Value; } } } } [Fact] public void IDictionaryShouldContainAllKeys() { object[] items = GenerateItems(16); IDictionary dict = GetDictionary(items) as IDictionary; foreach (KeyValuePair<TKey, TValue> item in items) { Assert.True(dict.Contains(item.Key)); } } [Fact] public void WhenDictionaryIsReadOnlyAddShouldThrow() { object[] items = GenerateItems(16); IDictionary dict = GetDictionary(items) as IDictionary; if (dict.IsReadOnly) { var pair = (KeyValuePair<TKey, TValue>)GenerateItem(); Assert.Throws<NotSupportedException>(() => dict.Add(pair.Key, pair.Value)); } } [Fact] public void WhenDictionaryIsReadOnlyClearShouldThrow() { object[] items = GenerateItems(16); IDictionary dict = GetDictionary(items) as IDictionary; if (dict.IsReadOnly) { Assert.Throws<NotSupportedException>(() => dict.Clear()); } } [Fact] public void WhenDictionaryIsReadOnlyRemoveShouldThrow() { object[] items = GenerateItems(16); IDictionary dict = GetDictionary(items) as IDictionary; if (dict != null && dict.IsReadOnly) { var key = ((KeyValuePair<TKey, TValue>)GenerateItem()).Key; Assert.Throws<NotSupportedException>(() => dict.Remove(key)); } } [Fact] public void IDictionaryGetEnumeratorShouldEnumerateSameItemsAsIEnumerableGetEnumerator() { object[] items = GenerateItems(16); IDictionary dict = GetDictionary(items) as IDictionary; if (dict != null) { IEnumerator enumerator = ((IEnumerable)dict).GetEnumerator(); IDictionaryEnumerator dictEnumerator = dict.GetEnumerator(); int i = 0; while (i++ < 2) { while (enumerator.MoveNext()) { Assert.True(dictEnumerator.MoveNext()); var pair = (KeyValuePair<TKey, TValue>) enumerator.Current; Assert.Equal(dictEnumerator.Current, dictEnumerator.Entry); var entry = dictEnumerator.Entry; Assert.Equal(pair.Key, dictEnumerator.Key); Assert.Equal(pair.Value, dictEnumerator.Value); Assert.Equal(pair.Key, entry.Key); Assert.Equal(pair.Value, entry.Value); } Assert.False(dictEnumerator.MoveNext()); dictEnumerator.Reset(); enumerator.Reset(); } } } [Fact] public void KeyCollectionIsReadOnly() { object[] items = GenerateItems(16); IDictionary<TKey, TValue> dict = GetDictionary(items); var item = (KeyValuePair<TKey, TValue>)GenerateItem(); var keys = dict.Keys; Assert.True(keys.IsReadOnly); Assert.Throws<NotSupportedException>(() => keys.Add(item.Key)); Assert.Throws<NotSupportedException>(() => keys.Clear()); Assert.Throws<NotSupportedException>(() => keys.Remove(item.Key)); } [Fact] public void KeyCollectionShouldContainAllKeys() { object[] items = GenerateItems(16); IDictionary<TKey, TValue> dict = GetDictionary(items); var keys = dict.Keys; foreach (KeyValuePair<TKey, TValue> item in items) Assert.True(keys.Contains(item.Key)); } [Fact] public void KeyCollectionShouldNotBeSynchronized() { object[] items = GenerateItems(16); IDictionary<TKey, TValue> dict = GetDictionary(items); var keys = (ICollection)dict.Keys; Assert.False(keys.IsSynchronized); } [Fact] public void KeyCollectionSyncRootShouldNotBeNull() { object[] items = GenerateItems(16); IDictionary<TKey, TValue> dict = GetDictionary(items); var keys = (ICollection)dict.Keys; Assert.NotNull(keys.SyncRoot); } [Fact] public void ValueCollectionIsReadOnly() { object[] items = GenerateItems(16); IDictionary<TKey, TValue> dict = GetDictionary(items); var item = (KeyValuePair<TKey, TValue>)GenerateItem(); var values = dict.Values; Assert.True(values.IsReadOnly); Assert.Throws<NotSupportedException>(() => values.Add(item.Value)); Assert.Throws<NotSupportedException>(() => values.Clear()); Assert.Throws<NotSupportedException>(() => values.Remove(item.Value)); } [Fact] public void ValueCollectionShouldContainAllValues() { object[] items = GenerateItems(16); IDictionary<TKey, TValue> dict = GetDictionary(items); var values = dict.Values; foreach (KeyValuePair<TKey, TValue> item in items) Assert.True(values.Contains(item.Value)); } [Fact] public void ValueCollectionShouldNotBeSynchronized() { object[] items = GenerateItems(16); IDictionary<TKey, TValue> dict = GetDictionary(items); var values = (ICollection)dict.Values; Assert.False(values.IsSynchronized); } [Fact] public void ValueCollectionSyncRootShouldNotBeNull() { object[] items = GenerateItems(16); IDictionary<TKey, TValue> dict = GetDictionary(items); var values = (ICollection)dict.Values; Assert.NotNull(values.SyncRoot); } } }
using System; using TidyNet.Dom; using System.Collections; namespace TidyNet { /// <summary> /// Entity hash table /// /// (c) 1998-2000 (W3C) MIT, INRIA, Keio University /// See Tidy.cs for the copyright notice. /// Derived from <a href="http://www.w3.org/People/Raggett/tidy"> /// HTML Tidy Release 4 Aug 2000</a> /// /// </summary> /// <author>Dave Raggett &lt;dsr@w3.org&gt;</author> /// <author>Andy Quick &lt;ac.quick@sympatico.ca&gt; (translation to Java)</author> /// <author>Seth Yates &lt;seth_yates@hotmail.com&gt; (translation to C#)</author> /// <version>1.0, 1999/05/22</version> /// <version>1.0.1, 1999/05/29</version> /// <version>1.1, 1999/06/18 Java Bean</version> /// <version>1.2, 1999/07/10 Tidy Release 7 Jul 1999</version> /// <version>1.3, 1999/07/30 Tidy Release 26 Jul 1999</version> /// <version>1.4, 1999/09/04 DOM support</version> /// <version>1.5, 1999/10/23 Tidy Release 27 Sep 1999</version> /// <version>1.6, 1999/11/01 Tidy Release 22 Oct 1999</version> /// <version>1.7, 1999/12/06 Tidy Release 30 Nov 1999</version> /// <version>1.8, 2000/01/22 Tidy Release 13 Jan 2000</version> /// <version>1.9, 2000/06/03 Tidy Release 30 Apr 2000</version> /// <version>1.10, 2000/07/22 Tidy Release 8 Jul 2000</version> /// <version>1.11, 2000/08/16 Tidy Release 4 Aug 2000</version> internal class EntityTable { public EntityTable() { } public virtual Entity Lookup(string name) { return (Entity)_entityHashtable[name]; } public virtual Entity Install(string name, short code) { Entity ent = Lookup(name); if (ent == null) { ent = new Entity(name, code); _entityHashtable[name] = ent; } else { ent.Code = code; } return ent; } public virtual Entity Install(Entity ent) { object entity = _entityHashtable[ent.Name]; _entityHashtable[ent.Name] = ent; return (Entity)entity; } /* entity starting with "&" returns zero on error */ public virtual short EntityCode(string name) { int c; if (name.Length <= 1) { return 0; } /* numeric entitity: name = "&#" followed by number */ if (name[1] == '#') { c = 0; /* zero on missing/bad number */ /* 'x' prefix denotes hexadecimal number format */ try { if (name.Length >= 4 && name[2] == 'x') { c = Convert.ToInt32(name.Substring(3), 16); } else if (name.Length >= 3) { c = Int32.Parse(name.Substring(2)); } } catch (FormatException) { } return (short) c; } /* Named entity: name ="&" followed by a name */ Entity ent = Lookup(name.Substring(1)); if (ent != null) { return ent.Code; } return 0; /* zero signifies unknown entity name */ } public virtual string EntityName(short code) { string name = null; foreach (Entity ent in _entityHashtable.Values) { if (ent.Code == code) { name = ent.Name; break; } } return name; } public static EntityTable DefaultEntityTable { get { if (_defaultEntityTable == null) { _defaultEntityTable = new EntityTable(); for (int i = 0; i < _entities.Length; i++) { _defaultEntityTable.Install(_entities[i]); } } return _defaultEntityTable; } } private Hashtable _entityHashtable = new Hashtable(); private static EntityTable _defaultEntityTable = null; private static Entity[] _entities = new Entity[] { new Entity("nbsp", 160), new Entity("iexcl", 161), new Entity("cent", 162), new Entity("pound", 163), new Entity("curren", 164), new Entity("yen", 165), new Entity("brvbar", 166), new Entity("sect", 167), new Entity("uml", 168), new Entity("copy", 169), new Entity("ordf", 170), new Entity("laquo", 171), new Entity("not", 172), new Entity("shy", 173), new Entity("reg", 174), new Entity("macr", 175), new Entity("deg", 176), new Entity("plusmn", 177), new Entity("sup2", 178), new Entity("sup3", 179), new Entity("acute", 180), new Entity("micro", 181), new Entity("para", 182), new Entity("middot", 183), new Entity("cedil", 184), new Entity("sup1", 185), new Entity("ordm", 186), new Entity("raquo", 187), new Entity("frac14", 188), new Entity("frac12", 189), new Entity("frac34", 190), new Entity("iquest", 191), new Entity("Agrave", 192), new Entity("Aacute", 193), new Entity("Acirc", 194), new Entity("Atilde", 195), new Entity("Auml", 196), new Entity("Aring", 197), new Entity("AElig", 198), new Entity("Ccedil", 199), new Entity("Egrave", 200), new Entity("Eacute", 201), new Entity("Ecirc", 202), new Entity("Euml", 203), new Entity("Igrave", 204), new Entity("Iacute", 205), new Entity("Icirc", 206), new Entity("Iuml", 207), new Entity("ETH", 208), new Entity("Ntilde", 209), new Entity("Ograve", 210), new Entity("Oacute", 211), new Entity("Ocirc", 212), new Entity("Otilde", 213), new Entity("Ouml", 214), new Entity("times", 215), new Entity("Oslash", 216), new Entity("Ugrave", 217), new Entity("Uacute", 218), new Entity("Ucirc", 219), new Entity("Uuml", 220), new Entity("Yacute", 221), new Entity("THORN", 222), new Entity("szlig", 223), new Entity("agrave", 224), new Entity("aacute", 225), new Entity("acirc", 226), new Entity("atilde", 227), new Entity("auml", 228), new Entity("aring", 229), new Entity("aelig", 230), new Entity("ccedil", 231), new Entity("egrave", 232), new Entity("eacute", 233), new Entity("ecirc", 234), new Entity("euml", 235), new Entity("igrave", 236), new Entity("iacute", 237), new Entity("icirc", 238), new Entity("iuml", 239), new Entity("eth", 240), new Entity("ntilde", 241), new Entity("ograve", 242), new Entity("oacute", 243), new Entity("ocirc", 244), new Entity("otilde", 245), new Entity("ouml", 246), new Entity("divide", 247), new Entity("oslash", 248), new Entity("ugrave", 249), new Entity("uacute", 250), new Entity("ucirc", 251), new Entity("uuml", 252), new Entity("yacute", 253), new Entity("thorn", 254), new Entity("yuml", 255), new Entity("fnof", 402), new Entity("Alpha", 913), new Entity("Beta", 914), new Entity("Gamma", 915), new Entity("Delta", 916), new Entity("Epsilon", 917), new Entity("Zeta", 918), new Entity("Eta", 919), new Entity("Theta", 920), new Entity("Iota", 921), new Entity("Kappa", 922), new Entity("Lambda", 923), new Entity("Mu", 924), new Entity("Nu", 925), new Entity("Xi", 926), new Entity("Omicron", 927), new Entity("Pi", 928), new Entity("Rho", 929), new Entity("Sigma", 931), new Entity("Tau", 932), new Entity("Upsilon", 933), new Entity("Phi", 934), new Entity("Chi", 935), new Entity("Psi", 936), new Entity("Omega", 937), new Entity("alpha", 945), new Entity("beta", 946), new Entity("gamma", 947), new Entity("delta", 948), new Entity("epsilon", 949), new Entity("zeta", 950), new Entity("eta", 951), new Entity("theta", 952), new Entity("iota", 953), new Entity("kappa", 954), new Entity("lambda", 955), new Entity("mu", 956), new Entity("nu", 957), new Entity("xi", 958), new Entity("omicron", 959), new Entity("pi", 960), new Entity("rho", 961), new Entity("sigmaf", 962), new Entity("sigma", 963), new Entity("tau", 964), new Entity("upsilon", 965), new Entity("phi", 966), new Entity("chi", 967), new Entity("psi", 968), new Entity("omega", 969), new Entity("thetasym", 977), new Entity("upsih", 978), new Entity("piv", 982), new Entity("bull", 8226), new Entity("hellip", 8230), new Entity("prime", 8242), new Entity("Prime", 8243), new Entity("oline", 8254), new Entity("frasl", 8260), new Entity("weierp", 8472), new Entity("image", 8465), new Entity("real", 8476), new Entity("trade", 8482), new Entity("alefsym", 8501), new Entity("larr", 8592), new Entity("uarr", 8593), new Entity("rarr", 8594), new Entity("darr", 8595), new Entity("harr", 8596), new Entity("crarr", 8629), new Entity("lArr", 8656), new Entity("uArr", 8657), new Entity("rArr", 8658), new Entity("dArr", 8659), new Entity("hArr", 8660), new Entity("forall", 8704), new Entity("part", 8706), new Entity("exist", 8707), new Entity("empty", 8709), new Entity("nabla", 8711), new Entity("isin", 8712), new Entity("notin", 8713), new Entity("ni", 8715), new Entity("prod", 8719), new Entity("sum", 8721), new Entity("minus", 8722), new Entity("lowast", 8727), new Entity("radic", 8730), new Entity("prop", 8733), new Entity("infin", 8734), new Entity("ang", 8736), new Entity("and", 8743), new Entity("or", 8744), new Entity("cap", 8745), new Entity("cup", 8746), new Entity("int", 8747), new Entity("there4", 8756), new Entity("sim", 8764), new Entity("cong", 8773), new Entity("asymp", 8776), new Entity("ne", 8800), new Entity("equiv", 8801), new Entity("le", 8804), new Entity("ge", 8805), new Entity("sub", 8834), new Entity("sup", 8835), new Entity("nsub", 8836), new Entity("sube", 8838), new Entity("supe", 8839), new Entity("oplus", 8853), new Entity("otimes", 8855), new Entity("perp", 8869), new Entity("sdot", 8901), new Entity("lceil", 8968), new Entity("rceil", 8969), new Entity("lfloor", 8970), new Entity("rfloor", 8971), new Entity("lang", 9001), new Entity("rang", 9002), new Entity("loz", 9674), new Entity("spades", 9824), new Entity("clubs", 9827), new Entity("hearts", 9829), new Entity("diams", 9830), new Entity("quot", 34), new Entity("amp", 38), new Entity("lt", 60), new Entity("gt", 62), new Entity("OElig", 338), new Entity("oelig", 339), new Entity("Scaron", 352), new Entity("scaron", 353), new Entity("Yuml", 376), new Entity("circ", 710), new Entity("tilde", 732), new Entity("ensp", 8194), new Entity("emsp", 8195), new Entity("thinsp", 8201), new Entity("zwnj", 8204), new Entity("zwj", 8205), new Entity("lrm", 8206), new Entity("rlm", 8207), new Entity("ndash", 8211), new Entity("mdash", 8212), new Entity("lsquo", 8216), new Entity("rsquo", 8217), new Entity("sbquo", 8218), new Entity("ldquo", 8220), new Entity("rdquo", 8221), new Entity("bdquo", 8222), new Entity("dagger", 8224), new Entity("Dagger", 8225), new Entity("permil", 8240), new Entity("lsaquo", 8249), new Entity("rsaquo", 8250), new Entity("euro", 8364) }; } }
using System; using System.Linq; using System.Linq.Expressions; using FluentNHibernate.Automapping.TestFixtures; using FluentNHibernate.Automapping.TestFixtures.CustomTypes; using FluentNHibernate.Conventions.Helpers.Builders; using FluentNHibernate.Conventions.Instances; using FluentNHibernate.Mapping; using FluentNHibernate.MappingModel; using NUnit.Framework; namespace FluentNHibernate.Testing.ConventionsTests.OverridingFluentInterface { [TestFixture] public class PropertyConventionTests { private PersistenceModel model; private IMappingProvider mapping; private Type mappingType; [SetUp] public void CreatePersistenceModel() { model = new PersistenceModel(); } [Test] public void AccessShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.Access.Field()); Convention(x => x.Access.Property()); VerifyModel(x => x.Access.ShouldEqual("field")); } [Test] public void ColumnNameShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.Column("xxx")); Convention(x => x.Column("yyy")); VerifyModel(x => { x.Columns.Count().ShouldEqual(1); x.Columns.First().Name.ShouldEqual("xxx"); }); } [Test] public void SqlTypeShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.CustomSqlType("sql-type")); Convention(x => x.CustomSqlType("type")); VerifyModel(x => x.Columns.First().SqlType.ShouldEqual("sql-type")); } [Test] public void TypeShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.CustomType<CustomUserType>()); Convention(x => x.CustomType<int>()); VerifyModel(x => x.Type.Name.ShouldEqual(typeof(CustomUserType).AssemblyQualifiedName)); } [Test] public void FormulaShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.Formula("form")); Convention(x => x.Formula("xxx")); VerifyModel(x => x.Formula.ShouldEqual("form")); } [Test] public void GeneratedShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.Generated.Always()); Convention(x => x.Generated.Never()); VerifyModel(x => x.Generated.ShouldEqual("always")); } [Test] public void InsertShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.Insert()); Convention(x => x.Not.Insert()); VerifyModel(x => x.Insert.ShouldBeTrue()); } [Test] public void NullableShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.Nullable()); Convention(x => x.Not.Nullable()); VerifyModel(x => x.Columns.First().NotNull.ShouldBeFalse()); } [Test] public void OptimisticLockShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.OptimisticLock()); Convention(x => x.Not.OptimisticLock()); VerifyModel(x => x.OptimisticLock.ShouldBeTrue()); } [Test] public void ReadOnlyShouldntOverwriteInsert() { Mapping(x => x.LineOne, x => x.Insert()); Convention(x => x.ReadOnly()); VerifyModel(x => x.Insert.ShouldBeTrue()); } [Test] public void ReadOnlyShouldntOverwriteUpdate() { Mapping(x => x.LineOne, x => x.Update()); Convention(x => x.ReadOnly()); VerifyModel(x => x.Update.ShouldBeTrue()); } [Test] public void ReadOnlyShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.ReadOnly()); Convention(x => x.Not.ReadOnly()); VerifyModel(x => { x.Insert.ShouldBeFalse(); x.Update.ShouldBeFalse(); }); } [Test] public void UniqueShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.Unique()); Convention(x => x.Not.Unique()); VerifyModel(x => x.Columns.First().Unique.ShouldBeTrue()); } [Test] public void UniqueKeyShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.UniqueKey("key")); Convention(x => x.UniqueKey("test")); VerifyModel(x => x.Columns.First().UniqueKey.ShouldEqual("key")); } [Test] public void UpdateShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.Update()); Convention(x => x.Not.Update()); VerifyModel(x => x.Update.ShouldBeTrue()); } [Test] public void LengthShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.Length(100)); Convention(x => x.Length(10)); VerifyModel(x => x.Columns.First().Length.ShouldEqual(100)); } [Test] public void LazyShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.LazyLoad()); Convention(x => x.Not.LazyLoad()); VerifyModel(x => x.Lazy.ShouldBeTrue()); } [Test] public void IndexShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.Index("value")); Convention(x => x.Index("xxx")); VerifyModel(x => x.Columns.First().Index.ShouldEqual("value")); } [Test] public void PrecisionShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.Precision(100)); Convention(x => x.Precision(200)); VerifyModel(x => x.Columns.First().Precision.ShouldEqual(100)); } [Test] public void ScaleShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.Scale(100)); Convention(x => x.Scale(200)); VerifyModel(x => x.Columns.First().Scale.ShouldEqual(100)); } [Test] public void DefaultShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.Default("value")); Convention(x => x.Default("xxx")); VerifyModel(x => x.Columns.First().Default.ShouldEqual("value")); } [Test] public void CheckShouldntBeOverwritten() { Mapping(x => x.LineOne, x => x.Check("value")); Convention(x => x.Check("xxx")); VerifyModel(x => x.Columns.First().Check.ShouldEqual("value")); } #region Helpers private void Convention(Action<IPropertyInstance> convention) { model.Conventions.Add(new PropertyConventionBuilder().Always(convention)); } private void Mapping(Expression<Func<ExampleClass, object>> property, Action<PropertyPart> mappingDefinition) { var classMap = new ClassMap<ExampleClass>(); classMap.Id(x => x.Id); var map = classMap.Map(property); mappingDefinition(map); mapping = classMap; mappingType = typeof(ExampleClass); } private void VerifyModel(Action<PropertyMapping> modelVerification) { model.Add(mapping); var generatedModels = model.BuildMappings(); var modelInstance = generatedModels .First(x => x.Classes.FirstOrDefault(c => c.Type == mappingType) != null) .Classes.First() .Properties.First(); modelVerification(modelInstance); } #endregion } }
using Lucene.Net.Support; using System; using System.Diagnostics; namespace Lucene.Net.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// A native int hash-based set where one value is reserved to mean "EMPTY" internally. The space overhead is fairly low /// as there is only one power-of-two sized int[] to hold the values. The set is re-hashed when adding a value that /// would make it >= 75% full. Consider extending and over-riding <seealso cref="#hash(int)"/> if the values might be poor /// hash keys; Lucene docids should be fine. /// The internal fields are exposed publicly to enable more efficient use at the expense of better O-O principles. /// <p/> /// To iterate over the integers held in this set, simply use code like this: /// <pre class="prettyprint"> /// SentinelIntSet set = ... /// for (int v : set.keys) { /// if (v == set.emptyVal) /// continue; /// //use v... /// }</pre> /// /// @lucene.internal /// </summary> public class SentinelIntSet { /// <summary> /// A power-of-2 over-sized array holding the integers in the set along with empty values. </summary> public int[] Keys; public int Count; public readonly int EmptyVal; /// <summary> /// the count at which a rehash should be done </summary> public int RehashCount; /// /// <param name="size"> The minimum number of elements this set should be able to hold without rehashing /// (i.e. the slots are guaranteed not to change) </param> /// <param name="emptyVal"> The integer value to use for EMPTY </param> public SentinelIntSet(int size, int emptyVal) { this.EmptyVal = emptyVal; int tsize = Math.Max(Lucene.Net.Util.BitUtil.NextHighestPowerOfTwo(size), 1); RehashCount = tsize - (tsize >> 2); if (size >= RehashCount) // should be able to hold "size" w/o re-hashing { tsize <<= 1; RehashCount = tsize - (tsize >> 2); } Keys = new int[tsize]; if (emptyVal != 0) { Clear(); } } public virtual void Clear() { Arrays.Fill(Keys, EmptyVal); Count = 0; } /// <summary> /// (internal) Return the hash for the key. The default implementation just returns the key, /// which is not appropriate for general purpose use. /// </summary> public virtual int Hash(int key) { return key; } /// <summary> /// The number of integers in this set. </summary> public virtual int Size() { return Count; } /// <summary> /// (internal) Returns the slot for this key </summary> public virtual int GetSlot(int key) { Debug.Assert(key != EmptyVal); int h = Hash(key); int s = h & (Keys.Length - 1); if (Keys[s] == key || Keys[s] == EmptyVal) { return s; } int increment = (h >> 7) | 1; do { s = (s + increment) & (Keys.Length - 1); } while (Keys[s] != key && Keys[s] != EmptyVal); return s; } /// <summary> /// (internal) Returns the slot for this key, or -slot-1 if not found </summary> public virtual int Find(int key) { Debug.Assert(key != EmptyVal); int h = Hash(key); int s = h & (Keys.Length - 1); if (Keys[s] == key) { return s; } if (Keys[s] == EmptyVal) { return -s - 1; } int increment = (h >> 7) | 1; for (; ; ) { s = (s + increment) & (Keys.Length - 1); if (Keys[s] == key) { return s; } if (Keys[s] == EmptyVal) { return -s - 1; } } } /// <summary> /// Does this set contain the specified integer? </summary> public virtual bool Exists(int key) { return Find(key) >= 0; } /// <summary> /// Puts this integer (key) in the set, and returns the slot index it was added to. /// It rehashes if adding it would make the set more than 75% full. /// </summary> public virtual int Put(int key) { int s = Find(key); if (s < 0) { Count++; if (Count >= RehashCount) { Rehash(); s = GetSlot(key); } else { s = -s - 1; } Keys[s] = key; } return s; } /// <summary> /// (internal) Rehashes by doubling {@code int[] key} and filling with the old values. </summary> public virtual void Rehash() { int newSize = Keys.Length << 1; int[] oldKeys = Keys; Keys = new int[newSize]; if (EmptyVal != 0) { Arrays.Fill(Keys, EmptyVal); } foreach (int key in oldKeys) { if (key == EmptyVal) { continue; } int newSlot = GetSlot(key); Keys[newSlot] = key; } RehashCount = newSize - (newSize >> 2); } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; namespace XenAPI { /// <summary> /// A VLAN mux/demux /// First published in XenServer 4.1. /// </summary> public partial class VLAN : XenObject<VLAN> { public VLAN() { } public VLAN(string uuid, XenRef<PIF> tagged_PIF, XenRef<PIF> untagged_PIF, long tag, Dictionary<string, string> other_config) { this.uuid = uuid; this.tagged_PIF = tagged_PIF; this.untagged_PIF = untagged_PIF; this.tag = tag; this.other_config = other_config; } /// <summary> /// Creates a new VLAN from a Proxy_VLAN. /// </summary> /// <param name="proxy"></param> public VLAN(Proxy_VLAN proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(VLAN update) { uuid = update.uuid; tagged_PIF = update.tagged_PIF; untagged_PIF = update.untagged_PIF; tag = update.tag; other_config = update.other_config; } internal void UpdateFromProxy(Proxy_VLAN proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; tagged_PIF = proxy.tagged_PIF == null ? null : XenRef<PIF>.Create(proxy.tagged_PIF); untagged_PIF = proxy.untagged_PIF == null ? null : XenRef<PIF>.Create(proxy.untagged_PIF); tag = proxy.tag == null ? 0 : long.Parse((string)proxy.tag); other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } public Proxy_VLAN ToProxy() { Proxy_VLAN result_ = new Proxy_VLAN(); result_.uuid = uuid ?? ""; result_.tagged_PIF = tagged_PIF ?? ""; result_.untagged_PIF = untagged_PIF ?? ""; result_.tag = tag.ToString(); result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } /// <summary> /// Creates a new VLAN from a Hashtable. /// </summary> /// <param name="table"></param> public VLAN(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); tagged_PIF = Marshalling.ParseRef<PIF>(table, "tagged_PIF"); untagged_PIF = Marshalling.ParseRef<PIF>(table, "untagged_PIF"); tag = Marshalling.ParseLong(table, "tag"); other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(VLAN other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._tagged_PIF, other._tagged_PIF) && Helper.AreEqual2(this._untagged_PIF, other._untagged_PIF) && Helper.AreEqual2(this._tag, other._tag) && Helper.AreEqual2(this._other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, VLAN server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { VLAN.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given VLAN. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_vlan">The opaque_ref of the given vlan</param> public static VLAN get_record(Session session, string _vlan) { return new VLAN((Proxy_VLAN)session.proxy.vlan_get_record(session.uuid, _vlan ?? "").parse()); } /// <summary> /// Get a reference to the VLAN instance with the specified UUID. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<VLAN> get_by_uuid(Session session, string _uuid) { return XenRef<VLAN>.Create(session.proxy.vlan_get_by_uuid(session.uuid, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given VLAN. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_vlan">The opaque_ref of the given vlan</param> public static string get_uuid(Session session, string _vlan) { return (string)session.proxy.vlan_get_uuid(session.uuid, _vlan ?? "").parse(); } /// <summary> /// Get the tagged_PIF field of the given VLAN. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_vlan">The opaque_ref of the given vlan</param> public static XenRef<PIF> get_tagged_PIF(Session session, string _vlan) { return XenRef<PIF>.Create(session.proxy.vlan_get_tagged_pif(session.uuid, _vlan ?? "").parse()); } /// <summary> /// Get the untagged_PIF field of the given VLAN. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_vlan">The opaque_ref of the given vlan</param> public static XenRef<PIF> get_untagged_PIF(Session session, string _vlan) { return XenRef<PIF>.Create(session.proxy.vlan_get_untagged_pif(session.uuid, _vlan ?? "").parse()); } /// <summary> /// Get the tag field of the given VLAN. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_vlan">The opaque_ref of the given vlan</param> public static long get_tag(Session session, string _vlan) { return long.Parse((string)session.proxy.vlan_get_tag(session.uuid, _vlan ?? "").parse()); } /// <summary> /// Get the other_config field of the given VLAN. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_vlan">The opaque_ref of the given vlan</param> public static Dictionary<string, string> get_other_config(Session session, string _vlan) { return Maps.convert_from_proxy_string_string(session.proxy.vlan_get_other_config(session.uuid, _vlan ?? "").parse()); } /// <summary> /// Set the other_config field of the given VLAN. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_vlan">The opaque_ref of the given vlan</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _vlan, Dictionary<string, string> _other_config) { session.proxy.vlan_set_other_config(session.uuid, _vlan ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given VLAN. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_vlan">The opaque_ref of the given vlan</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _vlan, string _key, string _value) { session.proxy.vlan_add_to_other_config(session.uuid, _vlan ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given VLAN. If the key is not in that Map, then do nothing. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_vlan">The opaque_ref of the given vlan</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _vlan, string _key) { session.proxy.vlan_remove_from_other_config(session.uuid, _vlan ?? "", _key ?? "").parse(); } /// <summary> /// Create a VLAN mux/demuxer /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_tagged_pif">PIF which receives the tagged traffic</param> /// <param name="_tag">VLAN tag to use</param> /// <param name="_network">Network to receive the untagged traffic</param> public static XenRef<VLAN> create(Session session, string _tagged_pif, long _tag, string _network) { return XenRef<VLAN>.Create(session.proxy.vlan_create(session.uuid, _tagged_pif ?? "", _tag.ToString(), _network ?? "").parse()); } /// <summary> /// Create a VLAN mux/demuxer /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_tagged_pif">PIF which receives the tagged traffic</param> /// <param name="_tag">VLAN tag to use</param> /// <param name="_network">Network to receive the untagged traffic</param> public static XenRef<Task> async_create(Session session, string _tagged_pif, long _tag, string _network) { return XenRef<Task>.Create(session.proxy.async_vlan_create(session.uuid, _tagged_pif ?? "", _tag.ToString(), _network ?? "").parse()); } /// <summary> /// Destroy a VLAN mux/demuxer /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_vlan">The opaque_ref of the given vlan</param> public static void destroy(Session session, string _vlan) { session.proxy.vlan_destroy(session.uuid, _vlan ?? "").parse(); } /// <summary> /// Destroy a VLAN mux/demuxer /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_vlan">The opaque_ref of the given vlan</param> public static XenRef<Task> async_destroy(Session session, string _vlan) { return XenRef<Task>.Create(session.proxy.async_vlan_destroy(session.uuid, _vlan ?? "").parse()); } /// <summary> /// Return a list of all the VLANs known to the system. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> public static List<XenRef<VLAN>> get_all(Session session) { return XenRef<VLAN>.Create(session.proxy.vlan_get_all(session.uuid).parse()); } /// <summary> /// Get all the VLAN Records at once, in a single XML RPC call /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<VLAN>, VLAN> get_all_records(Session session) { return XenRef<VLAN>.Create<Proxy_VLAN>(session.proxy.vlan_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// interface on which traffic is tagged /// </summary> public virtual XenRef<PIF> tagged_PIF { get { return _tagged_PIF; } set { if (!Helper.AreEqual(value, _tagged_PIF)) { _tagged_PIF = value; Changed = true; NotifyPropertyChanged("tagged_PIF"); } } } private XenRef<PIF> _tagged_PIF; /// <summary> /// interface on which traffic is untagged /// </summary> public virtual XenRef<PIF> untagged_PIF { get { return _untagged_PIF; } set { if (!Helper.AreEqual(value, _untagged_PIF)) { _untagged_PIF = value; Changed = true; NotifyPropertyChanged("untagged_PIF"); } } } private XenRef<PIF> _untagged_PIF; /// <summary> /// VLAN tag in use /// </summary> public virtual long tag { get { return _tag; } set { if (!Helper.AreEqual(value, _tag)) { _tag = value; Changed = true; NotifyPropertyChanged("tag"); } } } private long _tag; /// <summary> /// additional configuration /// </summary> public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config; } }
using Lucene.Net.Support; using System; using ArrayUtil = Lucene.Net.Util.ArrayUtil; namespace Lucene.Net.Codecs.Compressing { /* * 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 CorruptIndexException = Lucene.Net.Index.CorruptIndexException; using IndexInput = Lucene.Net.Store.IndexInput; using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s; using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator; using SegmentInfo = Lucene.Net.Index.SegmentInfo; /// <summary> /// Random-access reader for <see cref="CompressingStoredFieldsIndexWriter"/>. /// <para/> /// @lucene.internal /// </summary> public sealed class CompressingStoredFieldsIndexReader #if FEATURE_CLONEABLE : System.ICloneable #endif { internal static long MoveLowOrderBitToSign(long n) { return (((long)((ulong)n >> 1)) ^ -(n & 1)); } internal readonly int maxDoc; internal readonly int[] docBases; internal readonly long[] startPointers; internal readonly int[] avgChunkDocs; internal readonly long[] avgChunkSizes; internal readonly PackedInt32s.Reader[] docBasesDeltas; // delta from the avg internal readonly PackedInt32s.Reader[] startPointersDeltas; // delta from the avg // It is the responsibility of the caller to close fieldsIndexIn after this constructor // has been called internal CompressingStoredFieldsIndexReader(IndexInput fieldsIndexIn, SegmentInfo si) { maxDoc = si.DocCount; int[] docBases = new int[16]; long[] startPointers = new long[16]; int[] avgChunkDocs = new int[16]; long[] avgChunkSizes = new long[16]; PackedInt32s.Reader[] docBasesDeltas = new PackedInt32s.Reader[16]; PackedInt32s.Reader[] startPointersDeltas = new PackedInt32s.Reader[16]; int packedIntsVersion = fieldsIndexIn.ReadVInt32(); int blockCount = 0; for (; ; ) { int numChunks = fieldsIndexIn.ReadVInt32(); if (numChunks == 0) { break; } if (blockCount == docBases.Length) { int newSize = ArrayUtil.Oversize(blockCount + 1, 8); docBases = Arrays.CopyOf(docBases, newSize); startPointers = Arrays.CopyOf(startPointers, newSize); avgChunkDocs = Arrays.CopyOf(avgChunkDocs, newSize); avgChunkSizes = Arrays.CopyOf(avgChunkSizes, newSize); docBasesDeltas = Arrays.CopyOf(docBasesDeltas, newSize); startPointersDeltas = Arrays.CopyOf(startPointersDeltas, newSize); } // doc bases docBases[blockCount] = fieldsIndexIn.ReadVInt32(); avgChunkDocs[blockCount] = fieldsIndexIn.ReadVInt32(); int bitsPerDocBase = fieldsIndexIn.ReadVInt32(); if (bitsPerDocBase > 32) { throw new CorruptIndexException("Corrupted bitsPerDocBase (resource=" + fieldsIndexIn + ")"); } docBasesDeltas[blockCount] = PackedInt32s.GetReaderNoHeader(fieldsIndexIn, PackedInt32s.Format.PACKED, packedIntsVersion, numChunks, bitsPerDocBase); // start pointers startPointers[blockCount] = fieldsIndexIn.ReadVInt64(); avgChunkSizes[blockCount] = fieldsIndexIn.ReadVInt64(); int bitsPerStartPointer = fieldsIndexIn.ReadVInt32(); if (bitsPerStartPointer > 64) { throw new CorruptIndexException("Corrupted bitsPerStartPointer (resource=" + fieldsIndexIn + ")"); } startPointersDeltas[blockCount] = PackedInt32s.GetReaderNoHeader(fieldsIndexIn, PackedInt32s.Format.PACKED, packedIntsVersion, numChunks, bitsPerStartPointer); ++blockCount; } this.docBases = Arrays.CopyOf(docBases, blockCount); this.startPointers = Arrays.CopyOf(startPointers, blockCount); this.avgChunkDocs = Arrays.CopyOf(avgChunkDocs, blockCount); this.avgChunkSizes = Arrays.CopyOf(avgChunkSizes, blockCount); this.docBasesDeltas = Arrays.CopyOf(docBasesDeltas, blockCount); this.startPointersDeltas = Arrays.CopyOf(startPointersDeltas, blockCount); } private int Block(int docID) { int lo = 0, hi = docBases.Length - 1; while (lo <= hi) { int mid = (int)((uint)(lo + hi) >> 1); int midValue = docBases[mid]; if (midValue == docID) { return mid; } else if (midValue < docID) { lo = mid + 1; } else { hi = mid - 1; } } return hi; } private int RelativeDocBase(int block, int relativeChunk) { int expected = avgChunkDocs[block] * relativeChunk; long delta = MoveLowOrderBitToSign(docBasesDeltas[block].Get(relativeChunk)); return expected + (int)delta; } private long RelativeStartPointer(int block, int relativeChunk) { long expected = avgChunkSizes[block] * relativeChunk; long delta = MoveLowOrderBitToSign(startPointersDeltas[block].Get(relativeChunk)); return expected + delta; } private int RelativeChunk(int block, int relativeDoc) { int lo = 0, hi = docBasesDeltas[block].Count - 1; while (lo <= hi) { int mid = (int)((uint)(lo + hi) >> 1); int midValue = RelativeDocBase(block, mid); if (midValue == relativeDoc) { return mid; } else if (midValue < relativeDoc) { lo = mid + 1; } else { hi = mid - 1; } } return hi; } internal long GetStartPointer(int docID) { if (docID < 0 || docID >= maxDoc) { throw new System.ArgumentException("docID out of range [0-" + maxDoc + "]: " + docID); } int block = Block(docID); int relativeChunk = RelativeChunk(block, docID - docBases[block]); return startPointers[block] + RelativeStartPointer(block, relativeChunk); } public object Clone() { return this; } internal long RamBytesUsed() { long res = 0; foreach (PackedInt32s.Reader r in docBasesDeltas) { res += r.RamBytesUsed(); } foreach (PackedInt32s.Reader r in startPointersDeltas) { res += r.RamBytesUsed(); } res += RamUsageEstimator.SizeOf(docBases); res += RamUsageEstimator.SizeOf(startPointers); res += RamUsageEstimator.SizeOf(avgChunkDocs); res += RamUsageEstimator.SizeOf(avgChunkSizes); return res; } } }
//------------------------------------------------------------------------------ // <copyright file="MergePropertyDescriptor.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* */ namespace System.Windows.Forms.PropertyGridInternal { using System.Runtime.Serialization.Formatters; using System.Runtime.Serialization.Formatters.Binary; using System.ComponentModel; using System.Diagnostics; using System; using System.IO; using System.Collections; using System.Globalization; using System.Reflection; using System.ComponentModel.Design; using System.ComponentModel.Design.Serialization; using System.Windows.Forms; using System.Drawing; using Microsoft.Win32; internal class MergePropertyDescriptor : PropertyDescriptor { private PropertyDescriptor[] descriptors; private enum TriState { Unknown, Yes, No } private TriState localizable = TriState.Unknown; private TriState readOnly = TriState.Unknown; private TriState canReset = TriState.Unknown; private MultiMergeCollection collection; public MergePropertyDescriptor(PropertyDescriptor[] descriptors) : base(descriptors[0].Name, null) { this.descriptors = descriptors; } /// <include file='doc\PropertyDescriptor.uex' path='docs/doc[@for="PropertyDescriptor.ComponentType"]/*' /> /// <devdoc> /// <para> /// When overridden in a derived class, gets the type of the /// component this property /// is bound to. /// </para> /// </devdoc> public override Type ComponentType { get { return descriptors[0].ComponentType; } } /// <include file='doc\PropertyDescriptor.uex' path='docs/doc[@for="PropertyDescriptor.Converter"]/*' /> /// <devdoc> /// <para> /// Gets the type converter for this property. /// </para> /// </devdoc> public override TypeConverter Converter { get { return descriptors[0].Converter; } } public override string DisplayName { get { return descriptors[0].DisplayName; } } /// <include file='doc\PropertyDescriptor.uex' path='docs/doc[@for="PropertyDescriptor.IsLocalizable"]/*' /> /// <devdoc> /// <para> /// Gets a value /// indicating whether this property should be localized, as /// specified in the <see cref='System.ComponentModel.LocalizableAttribute'/>. /// </para> /// </devdoc> public override bool IsLocalizable { get { if (localizable == TriState.Unknown) { localizable = TriState.Yes; foreach (PropertyDescriptor pd in descriptors) { if (!pd.IsLocalizable) { localizable = TriState.No; break; } } } return (localizable == TriState.Yes); } } /// <include file='doc\PropertyDescriptor.uex' path='docs/doc[@for="PropertyDescriptor.IsReadOnly"]/*' /> /// <devdoc> /// <para> /// When overridden in /// a derived class, gets a value /// indicating whether this property is read-only. /// </para> /// </devdoc> public override bool IsReadOnly { get { if (readOnly == TriState.Unknown) { readOnly = TriState.No; foreach (PropertyDescriptor pd in descriptors) { if (pd.IsReadOnly) { readOnly = TriState.Yes; break; } } } return (readOnly == TriState.Yes); } } /// <include file='doc\PropertyDescriptor.uex' path='docs/doc[@for="PropertyDescriptor.PropertyType"]/*' /> /// <devdoc> /// <para> /// When overridden in a derived class, /// gets the type of the property. /// </para> /// </devdoc> public override Type PropertyType { get { return descriptors[0].PropertyType; } } public PropertyDescriptor this[int index] { get { return descriptors[index]; } } /// <include file='doc\PropertyDescriptor.uex' path='docs/doc[@for="PropertyDescriptor.CanResetValue"]/*' /> /// <devdoc> /// <para> /// When overridden in a derived class, indicates whether /// resetting the <paramref name="component "/>will change the value of the /// <paramref name="component"/>. /// </para> /// </devdoc> public override bool CanResetValue(object component) { Debug.Assert(component is Array, "MergePropertyDescriptor::CanResetValue called with non-array value"); if (canReset == TriState.Unknown) { canReset = TriState.Yes; Array a = (Array)component; for (int i = 0; i < descriptors.Length; i++) { if (!descriptors[i].CanResetValue(GetPropertyOwnerForComponent(a, i))) { canReset = TriState.No; break; } } } return (canReset == TriState.Yes); } /// <devdoc> /// This method attempts to copy the given value so unique values are /// always passed to each object. If the object cannot be copied it /// will be returned. /// </devdoc> private object CopyValue(object value) { // null is always OK if (value == null) { return value; } Type type = value.GetType(); // value types are always copies if (type.IsValueType) { return value; } object clonedValue = null; // ICloneable is the next easiest thing ICloneable clone = value as ICloneable; if (clone != null) { clonedValue = clone.Clone(); } // Next, access the type converter if (clonedValue == null) { TypeConverter converter = TypeDescriptor.GetConverter(value); if (converter.CanConvertTo(typeof(InstanceDescriptor))) { // Instance descriptors provide full fidelity unless // they are marked as incomplete. InstanceDescriptor desc = (InstanceDescriptor)converter.ConvertTo(null, CultureInfo.InvariantCulture, value, typeof(InstanceDescriptor)); if (desc != null && desc.IsComplete) { clonedValue = desc.Invoke(); } } // If that didn't work, try conversion to/from string if (clonedValue == null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string))) { object stringRep = converter.ConvertToInvariantString(value); clonedValue = converter.ConvertFromInvariantString((string)stringRep); } } // How about serialization? if (clonedValue == null && type.IsSerializable) { BinaryFormatter f = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); f.Serialize(ms, value); ms.Position = 0; clonedValue = f.Deserialize(ms); } if (clonedValue != null) { return clonedValue; } // we failed. This object's reference will be set on each property. return value; } /// <include file='doc\MemberDescriptor.uex' path='docs/doc[@for="MemberDescriptor.CreateAttributeCollection"]/*' /> /// <devdoc> /// <para> /// Creates a collection of attributes using the /// array of attributes that you passed to the constructor. /// </para> /// </devdoc> protected override AttributeCollection CreateAttributeCollection() { return new MergedAttributeCollection(this); } private object GetPropertyOwnerForComponent(Array a, int i) { object propertyOwner = a.GetValue(i); if (propertyOwner is ICustomTypeDescriptor) { propertyOwner = ((ICustomTypeDescriptor) propertyOwner).GetPropertyOwner(descriptors[i]); } return propertyOwner; } /// <include file='doc\PropertyDescriptor.uex' path='docs/doc[@for="PropertyDescriptor.GetEditor"]/*' /> /// <devdoc> /// <para> /// Gets an editor of the specified type. /// </para> /// </devdoc> public override object GetEditor(Type editorBaseType) { return descriptors[0].GetEditor(editorBaseType); } /// <include file='doc\PropertyDescriptor.uex' path='docs/doc[@for="PropertyDescriptor.GetValue"]/*' /> /// <devdoc> /// <para> /// When overridden in a derived class, gets the current /// value /// of the /// property on a component. /// </para> /// </devdoc> public override object GetValue(object component) { Debug.Assert(component is Array, "MergePropertyDescriptor::GetValue called with non-array value"); bool temp; return GetValue((Array)component, out temp); } public object GetValue(Array components, out bool allEqual) { allEqual = true; object obj = descriptors[0].GetValue(GetPropertyOwnerForComponent(components, 0)); if (obj is ICollection) { if (collection == null) { collection = new MultiMergeCollection((ICollection)obj); } else if (collection.Locked) { return collection; } else { collection.SetItems((ICollection)obj); } } for (int i = 1; i < descriptors.Length; i++) { object objCur = descriptors[i].GetValue(GetPropertyOwnerForComponent(components, i)); if (collection != null) { if (!collection.MergeCollection((ICollection)objCur)){ allEqual = false; return null; } } else if ((obj == null && objCur == null) || (obj != null && obj.Equals(objCur))) { continue; } else { allEqual = false; return null; } } if (allEqual && collection != null && collection.Count == 0) { return null; } return (collection != null ? collection : obj); } internal object[] GetValues(Array components) { object[] values = new object[components.Length]; for (int i = 0; i < components.Length; i++) { values[i] = descriptors[i].GetValue(GetPropertyOwnerForComponent(components, i)); } return values; } /// <include file='doc\PropertyDescriptor.uex' path='docs/doc[@for="PropertyDescriptor.ResetValue"]/*' /> /// <devdoc> /// <para> /// When overridden in a derived class, resets the /// value /// for this property /// of the component. /// </para> /// </devdoc> public override void ResetValue(object component) { Debug.Assert(component is Array, "MergePropertyDescriptor::ResetValue called with non-array value"); Array a = (Array)component; for (int i = 0; i < descriptors.Length; i++) { descriptors[i].ResetValue(GetPropertyOwnerForComponent(a, i)); } } private void SetCollectionValues(Array a, IList listValue) { try { if (collection != null) { collection.Locked = true; } // now we have to copy the value into each property. object[] values = new object[listValue.Count]; listValue.CopyTo(values, 0); for (int i = 0; i < descriptors.Length; i++) { IList propList = descriptors[i].GetValue(GetPropertyOwnerForComponent(a, i)) as IList; if (propList == null) { continue; } propList.Clear(); foreach (object val in values) { propList.Add(val); } } } finally { if (collection != null) { collection.Locked = false; } } } /// <include file='doc\PropertyDescriptor.uex' path='docs/doc[@for="PropertyDescriptor.SetValue"]/*' /> /// <devdoc> /// <para> /// When overridden in a derived class, sets the value of /// the component to a different value. /// </para> /// </devdoc> public override void SetValue(object component, object value) { Debug.Assert(component is Array, "MergePropertyDescriptor::SetValue called with non-array value"); Array a = (Array)component; if (value is IList && typeof(IList).IsAssignableFrom(PropertyType)) { SetCollectionValues(a, (IList)value); } else { for (int i = 0; i < descriptors.Length; i++) { object clonedValue = CopyValue(value); descriptors[i].SetValue(GetPropertyOwnerForComponent(a, i), clonedValue); } } } /// <include file='doc\PropertyDescriptor.uex' path='docs/doc[@for="PropertyDescriptor.ShouldSerializeValue"]/*' /> /// <devdoc> /// <para> /// When overridden in a derived class, indicates whether the /// value of /// this property needs to be persisted. /// </para> /// </devdoc> public override bool ShouldSerializeValue(object component) { Debug.Assert(component is Array, "MergePropertyDescriptor::ShouldSerializeValue called with non-array value"); Array a = (Array)component; for (int i = 0; i < descriptors.Length; i++) { if (!descriptors[i].ShouldSerializeValue(GetPropertyOwnerForComponent(a, i))) { return false; } } return true; } private class MultiMergeCollection : ICollection { private object[] items; private bool locked; public MultiMergeCollection(ICollection original) { SetItems(original); } /// <include file='doc\MultiSelectPropertyGridEntry.uex' path='docs/doc[@for="MultiSelectPropertyGridEntry.MultiMergeCollection.Count"]/*' /> /// <devdoc> /// Retrieves the number of items. /// </devdoc> public int Count { get { if (items != null) { return items.Length; } else { return 0; } } } /// <include file='doc\MultiSelectPropertyGridEntry.uex' path='docs/doc[@for="MultiSelectPropertyGridEntry.MultiMergeCollection.Locked"]/*' /> /// <devdoc> /// Prevents the contents of the collection from being re-initialized; /// </devdoc> public bool Locked { get { return locked; } set { this.locked = value; } } object ICollection.SyncRoot { get { return this; } } bool ICollection.IsSynchronized { get { return false; } } public void CopyTo(Array array, int index) { if (items == null) return; Array.Copy(items, 0, array, index, items.Length); } public IEnumerator GetEnumerator(){ if (items != null) { return items.GetEnumerator(); } else { return new object[0].GetEnumerator(); } } /// <include file='doc\MultiSelectPropertyGridEntry.uex' path='docs/doc[@for="MultiSelectPropertyGridEntry.MultiMergeCollection.MergeCollection"]/*' /> /// <devdoc> /// Ensures that the new collection equals the exisitng one. /// Otherwise, it wipes out the contents of the new collection. /// </devdoc> public bool MergeCollection(ICollection newCollection) { if (locked) { return true; } if (items.Length != newCollection.Count) { items = new object[0]; return false; } object[] newItems = new object[newCollection.Count]; newCollection.CopyTo(newItems, 0); for (int i = 0;i < newItems.Length; i++) { if (((newItems[i] == null) != (items[i] == null)) || (items[i] != null && !items[i].Equals(newItems[i]))){ items = new object[0]; return false; } } return true; } public void SetItems(ICollection collection) { if (locked) { return; } items = new object[collection.Count]; collection.CopyTo(items, 0); } } private class MergedAttributeCollection : AttributeCollection { private MergePropertyDescriptor owner; private AttributeCollection[] attributeCollections = null; private IDictionary foundAttributes = null; public MergedAttributeCollection(MergePropertyDescriptor owner) : base((Attribute[])null) { this.owner = owner; } public override Attribute this[Type attributeType] { get { return GetCommonAttribute(attributeType); } } #if false private void FullMerge() { Attribute[][] collections = new Attribute[owner.descriptors.Length][]; for (int i = 0; i < owner.descriptors.Length; i++) { AttributeCollection attrCollection = owner.descriptors[i].Attributes; collections[i] = new Attribute[attrCollection.Count]; attrCollection.CopyTo(collections[i], 0); Array.Sort(collections[i], GridEntry.AttributeTypeSorter); } ArrayList mergedList = new ArrayList(); // merge the sorted lists -- note that lists aren't fully sorted just by // Attribute.TypeId // int[] posArray = new int[collections.Length]; for (int i = 0; i < collections[0].Length; i++) { Attribute pivotAttr = collections[0][i]; bool match = true; for (int j = 1; j < collections.Length; j++) { if (posArray[j] >= collections[j].Length) { match = false; break; } // check to see if we're on a match // if (pivotAttr.Equals(collections[j][posArray[j]])) { posArray[j] += 1; continue; } int jPos = posArray[j]; Attribute jAttr = collections[j][jPos]; match = false; // if we aren't on a match, check all the items until we're past // where the matching item would be while (GridEntry.AttributeTypeSorter.Compare(jAttr, pivotAttr) <= 0) { // got a match! if (pivotAttr.Equals(jAttr)) { posArray[j] = jPos + 1; match = true; break; } // try again jPos++; if (jPos < collections[j].Length) { jAttr = collections[j][jPos]; } else { break; } } // if we got here, there is no match, quit for this guy if (!match) { posArray[j] = jPos; break; } } // do we have a match? if (match) { mergedList.Add(pivotAttr); } } // create our merged array Attribute[] mergedAttrs = new Attribute[mergedList.Count]; mergedList.CopyTo(mergedAttrs, 0); } #endif private Attribute GetCommonAttribute(Type attributeType) { if (attributeCollections == null) { attributeCollections = new AttributeCollection[owner.descriptors.Length]; for (int i = 0; i < owner.descriptors.Length; i++) { attributeCollections[i] = owner.descriptors[i].Attributes; } } if (attributeCollections.Length == 0) { return GetDefaultAttribute(attributeType); } Attribute value; if (foundAttributes != null) { value = foundAttributes[attributeType] as Attribute; if (value != null) { return value; } } value = attributeCollections[0][attributeType]; if (value == null) { return null; } for (int i = 1; i < attributeCollections.Length; i++) { Attribute newValue = attributeCollections[i][attributeType]; if (!value.Equals(newValue)) { value = GetDefaultAttribute(attributeType); break; } } if (foundAttributes == null) { foundAttributes = new Hashtable(); } foundAttributes[attributeType] = value; return value; } } } }
using System.Text; using System.Linq; using System.Linq.Expressions; using System.Collections.Generic; using System; namespace Mastersign.Expressions.Language { internal enum OperatorType { Numeric, Boolean, String, Relation, } internal class Operator { public string Name { get; private set; } public string Source { get; private set; } public OperatorType OpType { get; private set; } public int PriorityLevel { get; private set; } public Func<object, object, object> Function { get; private set; } private Operator(string name, string source, OperatorType opType, int priority, Func<object, object, object> func) { Name = name; Source = source; OpType = opType; PriorityLevel = priority; Function = func; } public override string ToString() { return Source; } public static readonly Operator NumPower = new Operator("power", "^", OperatorType.Numeric, 0, NumPowerFunc); private static object NumPowerFunc(object l, object r) { return Math.Pow(Convert.ToDouble(l), Convert.ToDouble(r)); } public static readonly Operator NumMultiplication = new Operator("multiplication", " * ", OperatorType.Numeric, 1, NumMultiplicationFunc); private static object NumMultiplicationFunc(object l, object r) { object l2, r2; var type = NumericHelper.HarmonizeValues( NumericHelper.AutoUpgradeNumericValue(l), NumericHelper.AutoUpgradeNumericValue(r), out l2, out r2); checked { if (type == typeof(Int32)) return (Int32)l2 * (Int32)r2; if (type == typeof(UInt32)) return (UInt32)l2 * (UInt32)r2; if (type == typeof(Int64)) return (Int64)l2 * (Int64)r2; if (type == typeof(UInt64)) return (UInt64)l2 * (UInt64)r2; if (type == typeof(Single)) return (Single)l2 * (Single)r2; if (type == typeof(Double)) return (Double)l2 * (Double)r2; if (type == typeof(Decimal)) return (Decimal)l2 * (Decimal)r2; } throw new NotSupportedException(); } public static readonly Operator NumDivision = new Operator("division", " / ", OperatorType.Numeric, 1, NumDivisionFunc); private static object NumDivisionFunc(object l, object r) { object l2, r2; var type = NumericHelper.HarmonizeValues( NumericHelper.AutoUpgradeNumericValue(l), NumericHelper.AutoUpgradeNumericValue(r), out l2, out r2); checked { if (type == typeof(Int32)) return (Int32)l2 / (Int32)r2; if (type == typeof(UInt32)) return (UInt32)l2 / (UInt32)r2; if (type == typeof(Int64)) return (Int64)l2 / (Int64)r2; if (type == typeof(UInt64)) return (UInt64)l2 / (UInt64)r2; if (type == typeof(Single)) return (Single)l2 / (Single)r2; if (type == typeof(Double)) return (Double)l2 / (Double)r2; if (type == typeof(Decimal)) return (Decimal)l2 / (Decimal)r2; } throw new NotSupportedException(); } public static readonly Operator NumAddition = new Operator("addition", " + ", OperatorType.Numeric, 2, NumAdditionFunc); private static object NumAdditionFunc(object l, object r) { object l2, r2; var type = NumericHelper.HarmonizeValues( NumericHelper.AutoUpgradeNumericValue(l), NumericHelper.AutoUpgradeNumericValue(r), out l2, out r2); checked { if (type == typeof(Int32)) return (Int32)l2 + (Int32)r2; if (type == typeof(UInt32)) return (UInt32)l2 + (UInt32)r2; if (type == typeof(Int64)) return (Int64)l2 + (Int64)r2; if (type == typeof(UInt64)) return (UInt64)l2 + (UInt64)r2; if (type == typeof(Single)) return (Single)l2 + (Single)r2; if (type == typeof(Double)) return (Double)l2 + (Double)r2; if (type == typeof(Decimal)) return (Decimal)l2 + (Decimal)r2; } throw new NotSupportedException(); } public static readonly Operator NumSubtraction = new Operator("subtraction", " - ", OperatorType.Numeric, 2, NumSubtractionFunc); private static object NumSubtractionFunc(object l, object r) { object l2, r2; var type = NumericHelper.HarmonizeValues( NumericHelper.AutoUpgradeNumericValue(l), NumericHelper.AutoUpgradeNumericValue(r), out l2, out r2); checked { if (type == typeof(Int32)) return (Int32)l2 - (Int32)r2; if (type == typeof(UInt32)) return (UInt32)l2 - (UInt32)r2; if (type == typeof(Int64)) return (Int64)l2 - (Int64)r2; if (type == typeof(UInt64)) return (UInt64)l2 - (UInt64)r2; if (type == typeof(Single)) return (Single)l2 - (Single)r2; if (type == typeof(Double)) return (Double)l2 - (Double)r2; if (type == typeof(Decimal)) return (Decimal)l2 - (Decimal)r2; } throw new NotSupportedException(); } public static readonly Operator StringConcat = new Operator("concatenation", " & ", OperatorType.String, 3, StringConcatFunc); private static object StringConcatFunc(object l, object r) { return string.Concat(l, r); } public static readonly Operator RelationLess = new Operator("less", " < ", OperatorType.Relation, 4, RelationLessFunc); private static object RelationLessFunc(object l, object r) { return Compare(l, r) < 0; } public static readonly Operator RelationLessOrEqual = new Operator("less or equal", " <= ", OperatorType.Relation, 4, RelationLessOrEqualFunc); private static object RelationLessOrEqualFunc(object l, object r) { return Compare(l, r) <= 0; } public static readonly Operator RelationEqual = new Operator("equal", " = ", OperatorType.Relation, 4, RelationEqualFunc); private static object RelationEqualFunc(object l, object r) { return AreEqual(l, r); } public static readonly Operator RelationUnequal = new Operator("unequal", " <> ", OperatorType.Relation, 4, RelationUnequalFunc); private static object RelationUnequalFunc(object l, object r) { return !AreEqual(l, r); } public static readonly Operator RelationGreaterOrEqual = new Operator("greater or equal", " >= ", OperatorType.Relation, 4, RelationGreaterOrEqualFunc); private static object RelationGreaterOrEqualFunc(object l, object r) { return Compare(l, r) >= 0; } public static readonly Operator RelationGreater = new Operator("greater", " > ", OperatorType.Relation, 4, RelationGreaterFunc); private static object RelationGreaterFunc(object l, object r) { return Compare(l, r) > 0; } public static readonly Operator BoolAnd = new Operator("and", " and ", OperatorType.Boolean, 5, BoolAndFunc); private static object BoolAndFunc(object l, object r) { return (bool)l && (bool)r; } public static readonly Operator BoolOr = new Operator("or", " or ", OperatorType.Boolean, 6, BoolOrFunc); private static object BoolOrFunc(object l, object r) { return (bool)l || (bool)r; } public static readonly Operator BoolXor = new Operator("xor", " xor ", OperatorType.Boolean, 6, BoolXorFunc); private static object BoolXorFunc(object l, object r) { return (bool)l ^ (bool)r; } private static object AutoUpgradeIfNumeric(object value) { return value != null ? (NumericHelper.IsNumeric(value.GetType()) ? NumericHelper.AutoUpgradeNumericValue(value) : value) : null; } private static bool AreEqual(object l, object r) { if (l == null && r == null) return true; if (l == null || r == null) return false; var lt = l.GetType(); var rt = r.GetType(); if (NumericHelper.IsNumeric(lt) && NumericHelper.IsNumeric(rt)) { l = NumericHelper.AutoUpgradeNumericValue(l); r = NumericHelper.AutoUpgradeNumericValue(r); Type t; if (NumericHelper.TryHarmonizeTypes(lt, rt, out t)) { var l2 = Convert.ChangeType(l, t); var r2 = Convert.ChangeType(r, t); return l2.Equals(r2); } throw new ArgumentException("Error comparing numeric values: The types are incompatible."); } return l.Equals(r); } private static int Compare(object l, object r) { if (l == null && r == null) return 0; if (l == null) return int.MinValue; if (r == null) return int.MaxValue; var lt = l.GetType(); var rt = r.GetType(); if (NumericHelper.IsNumeric(lt) && NumericHelper.IsNumeric(rt)) { l = NumericHelper.AutoUpgradeNumericValue(l); r = NumericHelper.AutoUpgradeNumericValue(r); Type t; if (NumericHelper.TryHarmonizeTypes(lt, rt, out t)) { var l2 = Convert.ChangeType(l, t); var r2 = Convert.ChangeType(r, t); return ((IComparable)l2).CompareTo(r2); } throw new ArgumentException("Error comparing numeric values: The types are incompatible."); } if (lt != rt) { throw new ArgumentException("Comparing values with different types is impossible."); } if (lt == typeof(string)) { return string.Compare((string)l, (string)r, StringComparison.InvariantCulture); } if (!(l is IComparable)) { throw new ArgumentException("The given values are not comparable."); } return ((IComparable)l).CompareTo(r); } public Expression GetExpression(EvaluationContext context, ExpressionElement left, ExpressionElement right) { var leftExpr = left.GetExpression(context); var rightExpr = right.GetExpression(context); if (OpType == OperatorType.Numeric) { HarmonizeNumericExpressions(ref leftExpr, ref rightExpr); if (this == NumAddition) return Expression.AddChecked(leftExpr, rightExpr); if (this == NumSubtraction) return Expression.Subtract(leftExpr, rightExpr); if (this == NumMultiplication) return Expression.Multiply(leftExpr, rightExpr); if (this == NumDivision) return Expression.Divide(leftExpr, rightExpr); if (this == NumPower) return Expression.Power(NumConvert(leftExpr, typeof(double)), NumConvert(rightExpr, typeof(double))); } if (this == BoolAnd) return Expression.And(leftExpr, rightExpr); if (this == BoolOr) return Expression.Or(leftExpr, rightExpr); if (this == BoolXor) return Expression.ExclusiveOr(leftExpr, rightExpr); if (this == StringConcat) return BuildConcatExpression(leftExpr, rightExpr); if (OpType == OperatorType.Relation) { if (NumericHelper.IsNumeric(leftExpr.Type)) { HarmonizeNumericExpressions(ref leftExpr, ref rightExpr); if (this == RelationLess) return Expression.LessThan(leftExpr, rightExpr); if (this == RelationLessOrEqual) return Expression.LessThanOrEqual(leftExpr, rightExpr); if (this == RelationEqual) return Expression.Equal(leftExpr, rightExpr); if (this == RelationUnequal) return Expression.NotEqual(leftExpr, rightExpr); if (this == RelationGreaterOrEqual) return Expression.GreaterThanOrEqual(leftExpr, rightExpr); if (this == RelationGreater) return Expression.GreaterThan(leftExpr, rightExpr); } else if (leftExpr.Type == typeof (bool) || rightExpr.Type == typeof(bool)) { if (this == RelationEqual) return Expression.Equal(leftExpr, rightExpr); if (this == RelationUnequal) return Expression.NotEqual(leftExpr, rightExpr); } else if (typeof(IComparable).IsAssignableFrom(leftExpr.Type)) { var compareExpr = Expression.Call( leftExpr, typeof (IComparable).GetMethod("CompareTo", new[] {typeof (object)}), typeof(object).IsAssignableFrom(rightExpr.Type) ? rightExpr : Expression.Convert(rightExpr, typeof(object))); return RelationFromComparation(compareExpr); } else { if (this == RelationEqual) return Expression.Equal(leftExpr, rightExpr); if (this == RelationUnequal) return Expression.NotEqual(leftExpr, rightExpr); throw new InvalidOperationException("The relation operation does not support the given operands."); } } throw new NotSupportedException(); } private Expression RelationFromComparation(Expression compareResult) { var zeroExpr = Expression.Constant(0, typeof (int)); if (this == RelationLess) return Expression.LessThan(compareResult, zeroExpr); if (this == RelationLessOrEqual) return Expression.LessThanOrEqual(compareResult, zeroExpr); if (this == RelationEqual) return Expression.Equal(compareResult, zeroExpr); if (this == RelationUnequal) return Expression.NotEqual(compareResult, zeroExpr); if (this == RelationGreaterOrEqual) return Expression.GreaterThanOrEqual(compareResult, zeroExpr); if (this == RelationGreater) return Expression.GreaterThan(compareResult, zeroExpr); throw new NotSupportedException(); } private static void HarmonizeNumericExpressions(ref Expression leftExpr, ref Expression rightExpr) { Type target; if (!NumericHelper.TryHarmonizeTypes(leftExpr.Type, rightExpr.Type, out target)) { throw new InvalidOperationException("The types are not compatible."); } leftExpr = NumConvert(leftExpr, target); rightExpr = NumConvert(rightExpr, target); } private static Expression BuildConcatExpression(Expression leftExpr, Expression rightExpr) { return Expression.Call( typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string) }), MakeString(leftExpr), MakeString(rightExpr)); } private static Expression MakeString(Expression expr) { return expr.Type == typeof(string) ? expr : expr.Type.IsValueType ? (Expression)Expression.Call(expr, typeof(object).GetMethod("ToString", new Type[0])) : (Expression)Expression.Condition( Expression.Equal(Expression.Constant(null), expr), Expression.Constant(null, typeof(string)), Expression.Call(expr, typeof(object).GetMethod("ToString", new Type[0]))); } private static Expression NumConvert(Expression expr, Type target) { return expr.Type == target ? expr : Expression.ConvertChecked(expr, target); } } internal class Operation : ExpressionNode { private readonly Operator op; private readonly ExpressionElement left; private readonly ExpressionElement right; public Operation(ExpressionElement left, Operator op, ExpressionElement right) { this.left = left; this.op = op; this.right = right; Name = op.Name; } public Operation AppendOperand(Operator newOp, ExpressionElement newTerm) { return newOp.PriorityLevel < op.PriorityLevel ? new Operation(left, op, right is Operation ? ((Operation)right).AppendOperand(newOp, newTerm) : new Operation(right, newOp, newTerm)) : new Operation(this, newOp, newTerm); } public override string Source { get { return "[" + left.Source + op + right.Source + "]"; } } public override bool CheckSemantic(EvaluationContext context, StringBuilder errMessages) { var checkL = left.CheckSemantic(context, errMessages); var checkR = right.CheckSemantic(context, errMessages); var res = checkL && checkR; if (!res) return false; var leftType = left.GetValueType(context); var rightType = right.GetValueType(context); Type resultType; switch (op.OpType) { case OperatorType.Boolean: if (leftType != typeof(bool)) { errMessages.AppendLine(string.Format( "The left operand of the boolean operation '{0}' is not a boolean value.", op.Name)); res = false; } if (rightType != typeof(bool)) { errMessages.AppendLine(string.Format( "The right operand of the boolean operation '{0}' is not a boolean value.", op.Name)); res = false; } break; case OperatorType.Numeric: if (!NumericHelper.IsNumeric(leftType)) { errMessages.AppendLine(string.Format( "The left operand of the numeric operation '{0}' is not a numeric value.", op.Name)); res = false; } if (!NumericHelper.IsNumeric(rightType)) { errMessages.AppendLine(string.Format( "The right operand of the numeric operation '{0}' is not a numeric value.", op.Name)); res = false; } if (res && op != Operator.NumPower) { if (!NumericHelper.TryHarmonizeTypes(leftType, rightType, out resultType)) { errMessages.AppendLine(string.Format( "The operands of the numeric operation '{0}' are not compatible.", op.Name)); res = false; } } break; case OperatorType.String: break; case OperatorType.Relation: if (leftType == typeof(string)) { if (rightType != typeof(string)) { errMessages.AppendLine(string.Format( "The left operand of the comparison '{0}' is a string but the right operand is not.", op.Name)); res = false; } } else if (NumericHelper.IsNumeric(leftType)) { if (!NumericHelper.IsNumeric(rightType)) { errMessages.AppendLine(string.Format( "The left operand of the comparison '{0}' is a numeric value but the right operand is not.", op.Name)); res = false; } else if (!NumericHelper.TryHarmonizeTypes(leftType, rightType, out resultType)) { errMessages.AppendLine(string.Format( "The numeric operands of the comparison '{0}' are not compatible.", op.Name)); res = false; } } else if ((op == Operator.RelationEqual || op == Operator.RelationUnequal)) { if (leftType == typeof(bool) && rightType != typeof(bool)) { errMessages.AppendLine(string.Format( "The left operand of the comparison '{0}' is a boolean value but the right operand is not.", op.Name)); res = false; } if (NumericHelper.IsNumeric(leftType) && !NumericHelper.IsNumeric(rightType)) { errMessages.AppendLine(string.Format( "The left operand of the comparison '{0}' is a numeric value but the right operand is not.", op.Name)); res = false; } if (IsValueType(leftType) && !IsValueType(rightType)) { errMessages.AppendLine(string.Format( "The left operand of the comparison '{0}' is a value but the right operand is a reference.", op.Name)); res = false; } if (!IsValueType(leftType) && IsValueType(rightType)) { errMessages.AppendLine(string.Format( "The left operand of the comparison '{0}' is a reference but the right operand is a value.", op.Name)); res = false; } } else { errMessages.AppendLine(string.Format( "The operands are not supported by the comparison operator '{0}'.", op.Name)); res = false; } break; } return res; } private static bool IsValueType(Type type) { return type != null && type.IsValueType; } public override Type GetValueType(EvaluationContext context) { switch (op.OpType) { case OperatorType.Numeric: if (op == Operator.NumPower) return typeof(double); var leftType = left.GetValueType(context); var rightType = right.GetValueType(context); Type resultType; if (!NumericHelper.TryHarmonizeTypes(leftType, rightType, out resultType)) { throw new InvalidOperationException("The operation is semantically incorrect. No type available."); } return resultType; case OperatorType.Relation: case OperatorType.Boolean: return typeof(bool); case OperatorType.String: return typeof(string); default: throw new ArgumentOutOfRangeException(); } } public override object GetValue(EvaluationContext context, object[] parameters) { var l = left.GetValue(context, parameters); var r = right.GetValue(context, parameters); var res = op.Function(l, r); return res; } public override Expression GetExpression(EvaluationContext context) { return op.GetExpression(context, left, right); } public override IEnumerator<ExpressionElement> GetEnumerator() { yield return left; yield return right; } } }
/////////////////////////////////////////////////////////////// // BrowseMonkey - An offline filesystem browser // // Shukri Adams (shukri.adams@gmail.com) // // https://github.com/shukriadams/browsemonkey // // MIT License (MIT) Copyright (c) 2014 Shukri Adams // /////////////////////////////////////////////////////////////// using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.IO; using System.Reflection; using System.Threading; using System.Windows.Forms; using System.Xml; using vcFramework.Assemblies; using vcFramework.Collections; using vcFramework.Delegates; using vcFramework.Diagnostics; using vcFramework.Interfaces; using vcFramework.Interop; using vcFramework.Windows.Forms; using vcFramework.Xml; using WeifenLuo.WinFormsUI.Docking; using BrowseMonkeyData; namespace BrowseMonkey { /// <summary> /// Main form of application - doesn't contain a lot of code specific to the /// application. Mostly holds everything together, handles app start and app /// close, etc etc. /// </summary> public class MainForm : Form { #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() { // // MainForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(256, 222); this.IsMdiContainer = true; this.Name = "MainForm"; this.Text = "[Set in code]"; this.Load += new System.EventHandler(this.MainForm_Load); // set up menus _topMenu = new MenuStrip(); _topMenu.Dock = DockStyle.Top; _dividerMenu = new ToolStripMenuItem("-"); // top level Menu items _fileMenu = new ToolStripMenuItem("&File"); _viewMenu = new ToolStripMenuItem("&View"); _helpMenu = new ToolStripMenuItem("&Help"); _topMenu.Items.AddRange(new ToolStripMenuItem[]{ _fileMenu, _viewMenu, _helpMenu }); // FILE _newVolumeMenu = new ToolStripMenuItem("&New Volume"); _openVolumeMenu = new ToolStripMenuItem("&Open Volume"); _closeAllMenu = new ToolStripMenuItem("&Close All"); _exitMenu = new ToolStripMenuItem("E&xit"); _saveMenu = new ToolStripMenuItem("&Save"); _saveAsMenu = new ToolStripMenuItem("S&ave As"); _exportMenu = new ToolStripMenuItem("&Export"); _recentVolumesMenu = new ToolStripMenuItem("Open &Recent"); _newVolumeMenu.ShortcutKeys = Keys.Control | Keys.N; _openVolumeMenu.ShortcutKeys = Keys.Control | Keys.O; _saveMenu.ShortcutKeys = Keys.Control | Keys.S; _closeAllMenu.Enabled = false; _saveMenu.Enabled = false; _saveAsMenu.Enabled = false; _exportMenu.Enabled = false; _recentVolumesMenu.Enabled = false; _newVolumeMenu.Click += new EventHandler(mnuNewVolume_Click); _openVolumeMenu.Click += new EventHandler(OpenVolume); _exitMenu.Click += new EventHandler(mnuQuit_Click); _saveMenu.Click += new EventHandler(mnuSave_Click); _saveAsMenu.Click += new EventHandler(mnuSaveAs_Click); _closeAllMenu.Click += new EventHandler(mnuCloseAll_Click); _fileMenu.DropDownItems.AddRange(new ToolStripMenuItem[]{ _newVolumeMenu, _openVolumeMenu, _recentVolumesMenu, _closeAllMenu, _dividerMenu, _saveMenu, _saveAsMenu, _exportMenu, _dividerMenu, _exitMenu }); // EXPORT _exportToFlatTextMenu = new ToolStripMenuItem("&Text"); _exportToXmlMenu = new ToolStripMenuItem("&Xml"); _exportToFlatTextMenu.Click += new EventHandler(mnuExportToFlatText_Click); _exportToXmlMenu.Click += new EventHandler(mnuExportToXml_Click); _exportMenu.DropDownItems.AddRange(new ToolStripMenuItem[]{ _exportToFlatTextMenu, _exportToXmlMenu }); // VIEW _consoleMenu = new ToolStripMenuItem("&Console"); _searchMenu = new ToolStripMenuItem("&Search"); _consoleMenu.Click += new EventHandler(mnuConsole_Click); _searchMenu.Click += new EventHandler(mnuSearch_Click); _viewMenu.DropDownItems.AddRange(new ToolStripMenuItem[]{ _consoleMenu, _searchMenu }); // HELP _aboutMenu = new ToolStripMenuItem("&About"); _aboutMenu.Click += new EventHandler(mnuAbout_Click); _helpMenu.DropDownItems.AddRange(new ToolStripMenuItem[]{ _aboutMenu }); this.MainMenuStrip = _topMenu; this.Controls.Add(_topMenu); this.ResumeLayout(false); this.PerformLayout(); } #endregion #region FIELDS private readonly Container _components = null; // MENUS-------------------------------------- private MenuStrip _topMenu; private ToolStripMenuItem _fileMenu; private ToolStripMenuItem _newVolumeMenu; private ToolStripMenuItem _openVolumeMenu; private ToolStripMenuItem _closeAllMenu; private ToolStripMenuItem _exitMenu; private ToolStripMenuItem _viewMenu; private ToolStripMenuItem _dividerMenu; private ToolStripMenuItem _consoleMenu; private ToolStripMenuItem _searchMenu; private ToolStripMenuItem _helpMenu; private ToolStripMenuItem _aboutMenu; private ToolStripMenuItem _saveMenu; private ToolStripMenuItem _saveAsMenu; private ToolStripMenuItem _exportMenu; private ToolStripMenuItem _exportToFlatTextMenu; private ToolStripMenuItem _exportToXmlMenu; private ToolStripMenuItem _recentVolumesMenu; //-------------------------------------------------------------------------- /// <summary> /// /// </summary> private static DockPanel _dockManager; /// <summary> /// Holds the array of file names application is started with. other /// arguments are filtered from list in the Main() method /// </summary> private static string[] _fileArgs; /// <summary> /// String messenger object used to send the names of volume files to an /// already-existing instance of this application. /// </summary> private static StringMessenger _stringMessenger; /// <summary> /// Static reference to the instantiated copy of this form - /// static ref is needed by static methods in this class. /// </summary> private static MainForm _this; /// <summary> /// Application-wide assembly accessor. Singleton. Exposed via /// static property of this form /// </summary> static private AssemblyAccessor _assemblyAccessor; /// <summary> /// Xml document containing listview configurations for several listviews /// in app. This doc is loaded up from an embedded assembly document. /// Singleton. Exposed via static property of this form /// </summary> static private XmlDocument m_dXmlListviewConfig = new XmlDocument(); /// <summary> /// Set to true if application has been started in debug mode. This is not /// the same debug mode as visual studios. A release build can also be /// started in debug mode, and would exhibit the samed debuggin behaviour. /// </summary> private static bool _debugMode; /// <summary> /// Used to store console messages which switching between threads. /// </summary> private static string _consoleMessage; /// <summary> /// Used to store exceptions for the console while switchign between /// threads /// </summary> private static Exception _e; /// <summary> /// Collection holding links to recently opened files. Singleton. Exposed /// via static property. /// </summary> private static FSLinksCollection _recentVolumes; /// <summary> /// Collection for holding links to recently searched folders /// </summary> private static FSLinksCollection _recentSearchFolders; /// <summary> /// Used to store the state of various objects. Singleton. Exposed via /// static property of this form /// </summary> private static StateHolder _stateholder; /// <summary> /// The number of unsaved volumes open at any given time. Incremented /// by 1 each time a new volume is created. When all unsaved volumes /// are either saved or destroyed, the number is set to 0 again. /// </summary> private static int _unsavedVolumesCount; #endregion #region PROPERTIES /// <summary> /// Gets or sets the number of unsaved volumes currently open. This number is reset to zero /// only when there are no more open unsaved volumes /// </summary> public static int UnsavedVolumesCount { get { return _unsavedVolumesCount; } set { _unsavedVolumesCount = value; } } /// <summary> /// Gets the instance of the applications's stateholder /// </summary> public static StateHolder StateBag { get { return _stateholder; } } /// <summary> /// /// </summary> public static DockPanel DockingManager { get { return _dockManager; } } /// <summary> /// Exposes xml document with volume explorer list view config /// </summary> public static XmlDocument XmlListViewConfig { get { return m_dXmlListviewConfig; } } /// <summary> /// Gets /// </summary> public static MainForm Instance { get { return _this; } } /// <summary> /// Gets the application-wide assembly accessor /// </summary> public static AssemblyAccessor AssemblyAccessor { get { return _assemblyAccessor; } } /// <summary> /// Gets a collection of recently opened volumes /// </summary> public static FSLinksCollection RecentVolumes { get { return _recentVolumes; } } /// <summary> /// Gets a collection of recently searched folders. This only /// applies to searches where the entire folder is specifed /// as a volume file holder /// </summary> public static FSLinksCollection RecentSearchFolders { get { return _recentSearchFolders; } } /// <summary> /// Gets the currently selected volumebrowser in the mdiparent. /// returns null if no volumebrowser is selected /// </summary> public static VolumeBrowser ActiveVolumeBrowser { get { if (_dockManager.ActiveDocument is VolumeBrowser) return (VolumeBrowser)_dockManager.ActiveDocument; return null; } } #endregion #region CONSTRUCTORS /// <summary> /// Constructor for MainForm. Note that very little application start /// logic is kept here. Most start logic is placed in the onload event /// handler for this form /// </summary> public MainForm( ) { InitializeComponent(); // ############################################################ // sets up Weifen's docking manager. all dockable content in // application will be added to this manager. note that manager // fills the client area of the mainform // ------------------------------------------------------------ _dockManager = new DockPanel(); _dockManager.ActiveAutoHideContent = null; _dockManager.Dock = System.Windows.Forms.DockStyle.Fill; _dockManager.Location = new System.Drawing.Point(0, 28); _dockManager.Name = "dockManager"; _dockManager.TabIndex = 1; this.Controls.Add( _dockManager); // ############################################################ // sets properties // ------------------------------------------------------------ this.Size = new Size(700,600); // default size this.AllowDrop = true; // ############################################################ // sets events // ------------------------------------------------------------ this.DragEnter += new DragEventHandler(this_DragEnter); this.DragDrop += new DragEventHandler(this_DragDrop); } #endregion #region DESTRUCTORS /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { bool proceed = true; IDirty[] dirty = FormFinderLib.GetIDirty(); // ############################################################ // explicitly tries to close all forms which can be dirty. if // there are still forms open after attempting to shut them // all down, application shutdown aborts // ------------------------------------------------------------ for (int i = 0 ; i < dirty.Length ; i ++) if (dirty[i].Dirty) { dirty[i].Dispose(); if (dirty[i].Created) { proceed = false; break; } } // ############################################################ // shut down app here // ------------------------------------------------------------ if (proceed && disposing) { // saves this forms state _stateholder.Add("MainForm.Location", this.Location); _stateholder.Add("MainForm.Size", this.Size); _stateholder.Add("MainForm.WindowState", this.WindowState); // saves weifen lo's dock manager state string configFile = Application.StartupPath + "\\" + Constants.INTERNAL_DATA_FOLDER + "\\" + Constants.DOCK_MANAGER_PERSISTENCE_FILE; _dockManager.SaveAsXml( configFile); if (_components != null) _components.Dispose(); base.Dispose( disposing ); } } #endregion #region MAIN /// <summary> Entry point for the application. Critical checks, ie, /// checks which will shutdown app if failed, are done here. </summary> [STAThread] static void Main( string[] args ) { string missingFile = String.Empty; try { // ############################################################## // Determines if app has been started in debug mode - use the // switch " -debug " when starting browsemonkey to enable debug. // -------------------------------------------------------------- _debugMode = false; for (int i = 0 ; i < args.Length ; i ++) if (args[i].ToLower().Trim() == "/debug" || args[i].ToLower().Trim() == "/d") { _debugMode = true; break; } // ############################################################## // remove all non-file name arguments from start args. // -------------------------------------------------------------- ArrayList fileArgs = new ArrayList(); foreach(string arg in args) if (!arg.StartsWith("/")) fileArgs.Add(arg); _fileArgs = (string[])fileArgs.ToArray(typeof(string)); // ############################################################## // need to instantiate string messenger object - this will be // used immediately if another instance of this application // already exists - if that is the case, the volume file argument // used for this instance will be sent to the first instance, // and this instance will terminate // // also does startup checks # 1 // Ensures that only one instance of this application is running // on this pc // -------------------------------------------------------------- _stringMessenger = new StringMessenger(); _stringMessenger.OnStringReceived += new EventHandler(OnMessageReceived); // gets a reference to the process of another instance // of this application Process otherProcess = ProcessLib.GetOtherRunningProcessOfCurrentApplication( Process.GetCurrentProcess()); if (otherProcess != null) { // if objProcess is not null, it means there is // another instance of browsemonkey running. must // therefore not proceed with loading this instnace // sends each of the file names which this // instance was supposed to open, to the // other instance, so that _that_instace // can handle the files instead. Note that switches start // with "/", so those are not sent for (int i = 0 ; i < args.Length ; i ++) if (!args[i].StartsWith("/")) _stringMessenger.SendMessage( otherProcess, args[i]); return; } // ############################################################## // sets up a "last chance" exception handler to trap an unhandled // exceptions in the application. This is ensure that the app // doesnt fail completely in the event of an unhanlded exception // -------------------------------------------------------------- AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MasterExceptionHandler); // ############################################################## // proceed with application running if startup checks passed // -------------------------------------------------------------- // VERY NB : Application.Run MUSTMUSTMUST be the LAST thing done in this method. // everything after application.run is unreachable Application.Run(new MainForm()); } catch(Exception ex) { if (_debugMode) MessageBox.Show( "Fatal error - " + Application.ProductName + " is shutting down \r\n\r\n"+ "Exception message : " + ex.Message + "\r\n" + "---------------------------------------------\r\n" + "Stack trace : " + ex.StackTrace); else MessageBox.Show( "Fatal error - " + Application.ProductName + " is shutting down. For a detailed " + "error description run the application in debug mode."); } } #endregion #region METHODS /// <summary> /// Need to override the base WndProc method to get access to /// message stream - messages must be passed to /// m_objStringMessenger to scan for incoming messages from /// other instances of BrowseMonkey /// </summary> /// <param name="message"></param> protected override void WndProc( ref Message message ) { _stringMessenger.ProcessMessage( this, message); //be sure to pass along all messages to the base also base.WndProc(ref message); } /// <summary> /// Invokes "export to xml" on the currently selected volume browser. /// </summary> private void ExportToXml( ) { VolumeBrowser b = MainForm.ActiveVolumeBrowser; if (b == null) return; FormFactory.SpawnXmlDump( b.Volume.VolumeData, b.ForcedName); } /// <summary> /// Invokes "export to text" on the currently selected volume browser /// </summary> private void ExportToText( ) { VolumeBrowser b = ActiveVolumeBrowser; if (b == null) return; FormFactory.ToggleFlatTextExport( b.Volume, b.ForcedName); } /// <summary> /// Opens a file select dialog and attempts to open the files /// selected in the dialog /// </summary> public void OpenVolumeWithDialog( ) { OpenFileDialog objDialog = new OpenFileDialog(); objDialog.Filter = Constants.FILE_DIALOGUE_FILTER; objDialog.Multiselect = true; objDialog.ShowDialog(); if (objDialog.FileNames != null) OpenFileBoundVolumes( objDialog.FileNames); objDialog.Dispose(); } /// <summary> /// Saves the active document in "save as..." mode /// </summary> private void SaveActiveDocumentAs( ) { if (MainForm.DockingManager.ActiveDocument is VolumeBrowser) { VolumeBrowser activeBrowser = (VolumeBrowser)MainForm.DockingManager.ActiveDocument; activeBrowser.SaveAs(); } else if (MainForm.DockingManager.ActiveDocument is ExportViewer) { ExportViewer textdump = (ExportViewer)MainForm.DockingManager.ActiveDocument; textdump.Save(); } } /// <summary> /// Saves the active document /// </summary> private void SaveActiveDocument( ) { if (MainForm.DockingManager.ActiveDocument is VolumeBrowser) { VolumeBrowser activeBrowser = (VolumeBrowser)MainForm.DockingManager.ActiveDocument; activeBrowser.Save(); } } /// <summary> /// Closes all open documents /// </summary> private void CloseAllDocuments() { foreach(Form document in _dockManager.Documents) document.Dispose(); } /// <summary> /// The top-level method for opening one or more file-bound volumes. All volume opening /// should be routed through this method, as it performs standard checks, and enforces /// version control on volumes too. Raw volume open requests can be sent here : ie, /// calls directly from open dialogues, drag and drop, app startup args etc. /// </summary> /// <param name="volumes"></param> private static void OpenFileBoundVolumes(string[] inVolumes) { // ################################################## // convert array to arraylist // -------------------------------------------------- ArrayList volumes = new ArrayList(); foreach(string volume in inVolumes) volumes.Add(volume); // ################################################## // removes any invalid files (non exist or non // volumes). moves invalid volume versions to // another arraylist // -------------------------------------------------- int count = volumes.Count; ArrayList invalidVolumes = new ArrayList(); for (int i = 0 ; i < count ; i ++) { // removes any files that are locked try { FileStream s = new FileStream( volumes[count - i - 1].ToString(), FileMode.Open); s.Close(); } catch { volumes.RemoveAt(count - i - 1); continue; } if(!File.Exists((string)volumes[count - i - 1]) || !VolumeIdentificationLib.FileIsVolume((string)volumes[count - i - 1])) volumes.RemoveAt(count - i - 1); else { string version = VolumeIdentificationLib.GetVolumeVersion((string)volumes[count - i - 1]); if (version == "1.01") { // moves volumes with invalid versions to "invalid" array invalidVolumes.Add(volumes[count - i - 1]); volumes.RemoveAt(count - i - 1); } else if (version == BrowseMonkeyData.Constants.CurrentVolumeVersion) { // do nothing } else { // volume is of a format not yet supported by this version of browsemonkey MainForm.ConsoleAdd( volumes[count - i - 1] + " requires a newer version of BrowseMonkey."); volumes.RemoveAt(count - i - 1); } } } // ################################################## // tries to update older volume versions // -------------------------------------------------- if (invalidVolumes.Count > 0) { VolumeConvertDialog dialog = new VolumeConvertDialog( (string[])invalidVolumes.ToArray(typeof(string))); FormLib.ScreenCenterForm(dialog); dialog.ShowDialog(); // gets a list of all volumes which have been // successfully converted and merges it back // into "volumes" array string[] updatedVolumes = dialog.ConvertedVolumes; foreach(string updateVolume in updatedVolumes) volumes.Add(updateVolume); } // ################################################## // open each volume - note that volumes is now a // list of CONVERTED volumes // -------------------------------------------------- foreach (string volume in volumes) FormFactory.SpawnVolumeBrowser( volume); } #endregion #region METHODS - CONSOLE /// <summary> /// Passes an exception to the console /// </summary> /// <param name="e"></param> public static void ConsoleAdd(Exception e) { bool consoleAvailable = false; _e = e; _consoleMessage = ""; // must be done - using zero length as indicator that there is no ConsoleMessageType. WinFormActionDelegate dlgyConsoleUpdate = new WinFormActionDelegate( ConsoleAdd_ThreadSafe); // checks if console is available if (FormFactory.Console != null && FormFactory.Console.Created) consoleAvailable = true; if (consoleAvailable) FormFactory.Console.messageConsole.Invoke( dlgyConsoleUpdate); else { if (_debugMode) MessageBox.Show(". Emessage : " + _e.Message + ". STrace : " + _e.StackTrace); else MessageBox.Show("An unexpected error occurred"); } } /// <summary> /// Passes a message to the console /// </summary> /// <param name="strMessage"></param> public static void ConsoleAdd(string strMessage) { bool consoleAvailable = false; _e = null; _consoleMessage = strMessage; WinFormActionDelegate dlgyConsoleUpdate = new WinFormActionDelegate( ConsoleAdd_ThreadSafe); // checks if console is available if (FormFactory.Console != null && FormFactory.Console.Created) consoleAvailable = true; if (consoleAvailable) FormFactory.Console.messageConsole.Invoke( dlgyConsoleUpdate); else // console is not available - need to use messagebox instead MessageBox.Show(strMessage); } /// <summary> /// Thread safe analogue to ConsoleAdd() - should be called only from that /// method, and only via a delegate. /// </summary> /// <param name="args"></param> private static void ConsoleAdd_ThreadSafe() { string strDebugModeMessage = ""; if (_debugMode) { if (_consoleMessage.Length > 0) strDebugModeMessage += _consoleMessage; if (_e != null) strDebugModeMessage += ". Emessage : " + _e.Message + ". STrace : " + _e.StackTrace; FormFactory.Console.messageConsole.Add( strDebugModeMessage); } else { if (_consoleMessage.Length == 0) FormFactory.Console.messageConsole.Add( "An unexpected error occurred."); else FormFactory.Console.messageConsole.Add( _consoleMessage); } } #endregion #region EVENTS /// <summary> /// Most of the default onload logic of the application is kept in this method /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainForm_Load(object sender, EventArgs e) { try { System.Globalization.CultureInfo c = new System.Globalization.CultureInfo( Application.CurrentCulture.Name); // ##################################################### // set form name // ----------------------------------------------------- this.Text = "BrowseMonkey"; if (_debugMode) this.Text += " (Debug mode)"; // ##################################################### // #2 - saves a reference to this form to a static // member. This is done so the static methods of // MainForm, which are used on application start up, can // have a working reference to the instantiated copy of // this form. // ----------------------------------------------------- _this = this; // ##################################################### // #3 - check for config file directory and if not exist, // create. This is where all config files, Xml state and // other application internal data files are stored. This // folder has got nothing to do with volume file storage // though // ----------------------------------------------------- if (!Directory.Exists(Application.StartupPath + "\\" + Constants.INTERNAL_DATA_FOLDER)) Directory.CreateDirectory( Application.StartupPath + "\\" + Constants.INTERNAL_DATA_FOLDER); // ##################################################### // instantiate application-wide objects // ----------------------------------------------------- // set up assembly accessor first, is several other objects require this one _assemblyAccessor = new AssemblyAccessor( Assembly.GetAssembly(typeof(MainForm))); _stateholder = new StateHolder( Application.StartupPath + "\\" + Constants.INTERNAL_DATA_FOLDER + "\\state.dat"); _recentVolumes = new FSLinksCollection( Application.StartupPath + "\\" + Constants.INTERNAL_DATA_FOLDER + "\\recentFiles.dat", Constants.MAX_RECENT_FILES); _recentVolumes.ValidFilesOnly = false; _recentVolumes.ItemCountChanged += new EventHandler(RecentFilesCollection_Changed); _recentSearchFolders = new FSLinksCollection( Application.StartupPath + "\\" + Constants.INTERNAL_DATA_FOLDER + "\\recentSearchFolders.dat", Constants.MAX_RECENT_SEARCH_FOLDERS); _recentSearchFolders.ValidFilesOnly = false; m_dXmlListviewConfig = MainForm.AssemblyAccessor.GetXmlDocument( _assemblyAccessor.RootName + ".Resources.Xml.listviewConfigs.xml"); // ##################################################### // restores the state of the main form (ie, this) // ----------------------------------------------------- if (_stateholder.Contains("MainForm.Location"))this.Location = (Point)_stateholder.Retrieve("MainForm.Location"); if (_stateholder.Contains("MainForm.Size"))this.Size = (Size)_stateholder.Retrieve("MainForm.Size"); if (_stateholder.Contains("MainForm.WindowState"))this.WindowState = (FormWindowState)_stateholder.Retrieve("MainForm.WindowState"); // ##################################################### // if the application is minimized when shut down, it // will restart in minimized state, which is NOT desired. // the problem is that the "normal" state will be set to // minimized too, which prevents the user from setting // the application to normal again ("normal" = minimized) // below is a "workaround" to this problem. // ----------------------------------------------------- if (this.WindowState == System.Windows.Forms.FormWindowState.Minimized) { this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Size = new Size(400,300); this.DesktopLocation = new Point(50,50); } string configFile = Application.StartupPath + "\\" + Constants.INTERNAL_DATA_FOLDER + "\\" + Constants.DOCK_MANAGER_PERSISTENCE_FILE; // loads weifen luo's form state data /* if (File.Exists(configFile)) _dockManager.LoadFromXml( configFile, new DockContentHandler("",)); */ if (FormFactory.Console == null) FormFactory.ToggleConsole(); if (FormFactory.SearchArgs == null) FormFactory.ToggleSearch(); // sets the icon of this application this.Icon = MainForm.AssemblyAccessor.GetIcon( Application.ProductName + ".Resources.Images.appIcon.ico"); // ##################################################### // throws up splash - when the splash is closed // (disposed), this application will continue loading // ----------------------------------------------------- FormFactory.ToggleSplash(); FormFactory.Splash.Disposed += new EventHandler(MainForm_Load_Continued); } catch(Exception ex) { MainForm.ConsoleAdd(ex); } } /// <summary> /// Invoked after splash screen closes down - continues application /// loading, handling all stuff after splash screen /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainForm_Load_Continued(object sender, EventArgs e) { try { // ###################################################### // Force the population of "recent files" menu items. do // this after creating menu, as menu reflects contents // of this collection // ------------------------------------------------------ RecentFilesCollection_Changed(null, null); // ###################################################### // enable event handling for docking content only after // menus are in place, as menu enabled properties will be // be handled by these event handlers, which start firing // the moment ANY forms are created. // ------------------------------------------------------ /* todo : fix this _dockManager.ContentAdded += new DockContentHandler(DockManager_ContentCountChanged); _dockManager.ContentRemoved += new DockContentHandler(DockManager_ContentCountChanged); */ _dockManager.ActiveDocumentChanged += DockManager_ActiveDocumentChanged; // ###################################################### // when reach here, application has finished loading. if // the application was opened to open a specified // BrowseMonkey file, can now open that file // ------------------------------------------------------ if (_fileArgs.Length > 0) OpenFileBoundVolumes( _fileArgs); } catch(Exception ex) { MainForm.ConsoleAdd(ex); } } /// <summary> /// Invoked when items are dragged onto the client area of the main /// application form (this form) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void this_DragEnter( object sender, DragEventArgs e ) { try { // checks if the items being dropped are files (or folders) - // dragging behaviour is only allowed for files and folders if( e.Data.GetDataPresent(DataFormats.FileDrop, false)) e.Effect = DragDropEffects.All; } catch(Exception ex) { MainForm.ConsoleAdd(ex); } } /// <summary> /// Invoked when dragged items are dropped on teh main application form (this form) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void this_DragDrop( object sender, DragEventArgs e ) { try { // gets array of items dropped on this form string[] droppedItems = (string[])e.Data.GetData(DataFormats.FileDrop); // if a single folder is dropped, we send that folder to the volume // path selector to be turned into a volume. Else, assume the droppe // items are files, and try to treat them as volume files to be // opened if (droppedItems.Length == 1 && Directory.Exists(droppedItems[0])) FormFactory.SpawnVolumePathSelector(droppedItems[0]); else OpenFileBoundVolumes(droppedItems); } catch(Exception ex) { MainForm.ConsoleAdd(ex); } } /// <summary> /// Invoked when another instance of this application sends a file name /// message to this instance as a signal that that file must be /// processed by this instance /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void OnMessageReceived( object sender, EventArgs e ) { try { StringMessageEventArgs args = (StringMessageEventArgs)e; string file = args.Message; OpenFileBoundVolumes( new string[]{file}); // ########################################### // receiving a window message can mess up the // window of this app - it is necessary to // manually redraw this app // ------------------------------------------- _this.Show(); } catch(Exception ex) { MainForm.ConsoleAdd(ex); } } /// <summary> /// Invoked by an unhandled exception - ensures /// that application doesnt fail in the event of something /// unplanned happening /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void MasterExceptionHandler( object sender, UnhandledExceptionEventArgs e ) { if(e.ExceptionObject is ThreadAbortException) { // do nothing - thread abort exceptions must // always be supressed } else MainForm.ConsoleAdd( (Exception)e.ExceptionObject); } /// <summary> /// Invoked when the number of files in the files collection is changed /// </summary> public void RecentFilesCollection_Changed( object sender, EventArgs e ) { // remove existing links from menu first _recentVolumesMenu.DropDownItems.Clear(); string[] files = _recentVolumes.Items; foreach (string file in files) { ToolStripMenuItem item = new ToolStripMenuItem( Path.GetFileName(file)); item.Click += new EventHandler(RecentFileLink_Clicked); _recentVolumesMenu.DropDownItems.Add( item); } // if there are are no recent files, disable the "recent items" // parent menu item _recentVolumesMenu.Enabled = true; if (_recentVolumesMenu.DropDownItems.Count == 0) _recentVolumesMenu.Enabled = false; } /// <summary> /// Invoked when the content in dock manager is added or removed. This is used /// in turn to set the properties of certain menu items which are dependant /// on active content in the dock manager /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void DockManager_ContentCountChanged( object sender, DockContentEventArgs e ) { // If there are any ISpawned forms open, // enable "close all" ISpawned[] forms = FormFinderLib.GetISpawned(); _closeAllMenu.Enabled = false; if (forms.Length > 0) _closeAllMenu.Enabled = true; } /// <summary> /// Invoked when the different active content is selected. Responsible for setting /// the enabled/disabled status of various menu items /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void DockManager_ActiveDocumentChanged( object sender, EventArgs e ) { // disable all volume-specific menu items _saveMenu.Enabled = false; _saveAsMenu.Enabled = false; _exportMenu.Enabled = false; // ################################################################## // if currently selected active content is a volumebrowser, re-enable // volumebrowser stuff // ------------------------------------------------------------------ if (_dockManager.ActiveDocument is VolumeBrowser) { _saveAsMenu.Enabled = true; _exportMenu.Enabled = true; // "save" should only ever be enable if the currently selected content // is a dirty volumbe browser VolumeBrowser b = _dockManager.ActiveDocument as VolumeBrowser; if (b.Dirty) _saveMenu.Enabled = true; } else if (_dockManager.ActiveDocument is ExportViewer) _saveAsMenu.Enabled = true; } /// <summary> /// Invoked whenever a volumebrowser changes its dirty status. This method /// </summary> public void VolumeBrowserDirtyChanged( object sender, EventArgs e ) { VolumeBrowser b = MainForm.ActiveVolumeBrowser; if (b == null) return; if (b.Dirty) _saveMenu.Enabled = true; else _saveMenu.Enabled = false; } /// <summary> /// Invoked when a volume is saved to file or closed. Responsible for setting /// _unsavedVolumesCount back to 0 if there are no more open unbound volumes /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public static void VolumeSavedOrClosed( object sender, EventArgs e ) { VolumeBrowser[] browsers = FormFinderLib.GetVolumeBrowsers(); Volume volume = (Volume)sender; bool unsavedVolumesOpen = false; foreach(VolumeBrowser browser in browsers) if (!browser.Volume.BoundToFile && browser.Volume != volume) { unsavedVolumesOpen = true; break; } if (!unsavedVolumesOpen) _unsavedVolumesCount = 0; } #endregion #region EVENTS - Menu /// <summary> /// Invoked when one of the recent file links in the menu are clicked. The menu items /// dont contain the actual paths to the files - only the files names. The order of /// the menu items matches the contents of the RecentFilesCollection however, so we /// know which path to extract from the collection by using the count of the menu /// item. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RecentFileLink_Clicked( object sender, EventArgs e ) { ToolStripItem clickedItem = sender as ToolStripItem; for (int i = 0; i < _recentVolumesMenu.DropDownItems.Count; i++) { if (clickedItem != _recentVolumesMenu.DropDownItems[i]) continue; string[] files = _recentVolumes.Items; // recent files collection can contain dead links // need to check for it here. this should not be // handled by the general volume opening logic, // because the error message given should be // "recent files" specific if (!File.Exists(files[i])) { MainForm.ConsoleAdd(Path.GetFileName(files[i]) + " no longer exists."); return; } OpenFileBoundVolumes( new[] { files[i] }); break; } } /// <summary> /// Invoked when the "save" menu is clicked. Invokes the "save" process for the currently /// selected volumebrowser's volume to be saved. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void mnuSave_Click(object sender, EventArgs e) { SaveActiveDocument(); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void mnuSaveAs_Click(object sender, EventArgs e) { SaveActiveDocumentAs(); } /// <summary> /// Menu click : Toggles visbility of search form /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void mnuSearch_Click(object sender, EventArgs e) { FormFactory.ToggleSearch(); } /// <summary> /// Menu click : Toggles visibility of console /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void mnuConsole_Click(object sender, System.EventArgs e) { FormFactory.ToggleConsole(); } /// <summary> /// Menu click : Closes this application down /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void mnuQuit_Click(object sender, System.EventArgs e) { this.Dispose(); } /// <summary> /// Menu click : Brings up "About" form /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void mnuAbout_Click(object sender, System.EventArgs e) { FormFactory.ToggleAbout(); } /// <summary> /// Menu click : Calls up Volume Creator form /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void mnuNewVolume_Click(object sender, System.EventArgs e) { FormFactory.SpawnVolumePathSelector(); } /// <summary> /// Menu click : Invokes "open volume" dialog and process /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OpenVolume(object sender, System.EventArgs e) { OpenVolumeWithDialog(); } /// <summary> /// Invoked when user click "Close all" menu item. Causes the closing of all /// volumebrowsers /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void mnuCloseAll_Click(object sender, System.EventArgs e) { CloseAllDocuments(); } /// <summary> /// Invoked when the "export to flat text" menu item is clicked. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void mnuExportToFlatText_Click(object sender, System.EventArgs e) { ExportToText(); } /// <summary> /// Invoked when the "export to Xml" menu item is clicked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void mnuExportToXml_Click(object sender, System.EventArgs e) { ExportToXml(); } #endregion } }
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using FSLib = Microsoft.FSharp.Compiler.AbstractIL.Internal.Library; using System; using System.Runtime.InteropServices; using System.Collections; using System.IO; using System.Windows.Forms; using System.Diagnostics; using System.Globalization; using System.Text; using System.Threading; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants; using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID; using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID; using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; namespace Microsoft.VisualStudio.FSharp.ProjectSystem { [CLSCompliant(false)] [ComVisible(true)] public class FolderNode : HierarchyNode { /// <summary> /// Constructor for the FolderNode /// </summary> /// <param name="root">Root node of the hierarchy</param> /// <param name="relativePath">relative path from root i.e.: "NewFolder1\\NewFolder2\\NewFolder3</param> /// <param name="element">Associated project element</param> internal FolderNode(ProjectNode root, string relativePath, ProjectElement element) : base(root, element) { this.VirtualNodeName = relativePath.TrimEnd('\\'); } /// <summary> /// This relates to the SCC glyph /// </summary> public override VsStateIcon StateIconIndex { get { // The SCC manager does not support being asked for the state icon of a folder (result of the operation is undefined) return VsStateIcon.STATEICON_NOSTATEICON; } } public override NodeProperties CreatePropertiesObject() { return new FolderNodeProperties(this); } public override void DeleteFromStorage(string path) { this.DeleteFolder(path); } /// <summary> /// Get the automation object for the FolderNode /// </summary> /// <returns>An instance of the Automation.OAFolderNode type if succeeded</returns> public override object GetAutomationObject() { if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) { return null; } return new Automation.OAFolderItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this); } public override object GetIconHandle(bool open) { return this.ProjectMgr.ImageHandler.GetIconHandle(open ? (int)ProjectNode.ImageName.OpenFolder : (int)ProjectNode.ImageName.Folder); } /// <summary> /// Rename Folder /// </summary> /// <param name="label">new Name of Folder</param> /// <returns>VSConstants.S_OK, if succeeded</returns> public override int SetEditLabel(string label) { if (String.Compare(Path.GetFileName(this.Url.TrimEnd('\\')), label, StringComparison.Ordinal) == 0) { // Label matches current Name return VSConstants.S_OK; } string newPath = Path.Combine(new DirectoryInfo(this.Url).Parent.FullName, label); // Verify that No Directory/file already exists with the new name among current children for (HierarchyNode n = Parent.FirstChild; n != null; n = n.NextSibling) { if (n != this && String.Compare(n.Caption, label, StringComparison.OrdinalIgnoreCase) == 0) { return ShowFileOrFolderAlreadExistsErrorMessage(newPath); } } // Verify that No Directory/file already exists with the new name on disk if (Directory.Exists(newPath) || FSLib.Shim.FileSystem.SafeExists(newPath)) { return ShowFileOrFolderAlreadExistsErrorMessage(newPath); } try { RenameFolder(label); //Refresh the properties in the properties window IVsUIShell shell = this.ProjectMgr.GetService(typeof(SVsUIShell)) as IVsUIShell; Debug.Assert(shell != null, "Could not get the ui shell from the project"); ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0)); // Notify the listeners that the name of this folder is changed. This will // also force a refresh of the SolutionExplorer's node. this.OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_Caption, 0); } catch (Exception e) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.RenameFolder, CultureInfo.CurrentUICulture), e.Message)); } return VSConstants.S_OK; } public override int MenuCommandId { get { return VsMenus.IDM_VS_CTXT_FOLDERNODE; } } public override Guid ItemTypeGuid { get { return VSConstants.GUID_ItemType_PhysicalFolder; } } public override string Url { get { return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(this.ProjectMgr.Url), this.VirtualNodeName)) + "\\"; } } public override string Caption { get { // it might have a backslash at the end... // and it might consist of Grandparent\parent\this\ string caption = this.VirtualNodeName; string[] parts; parts = caption.Split(Path.DirectorySeparatorChar); caption = parts[parts.GetUpperBound(0)]; return caption; } } public override string GetMkDocument() { Debug.Assert(this.Url != null, "No url sepcified for this node"); return this.Url; } /// <summary> /// Enumerate the files associated with this node. /// A folder node is not a file and as such no file to enumerate. /// </summary> /// <param name="files">The list of files to be placed under source control.</param> /// <param name="flags">The flags that are associated to the files.</param> public override void GetSccFiles(System.Collections.Generic.IList<string> files, System.Collections.Generic.IList<tagVsSccFilesFlags> flags) { return; } /// <summary> /// This method should be overridden to provide the list of special files and associated flags for source control. /// </summary> /// <param name="sccFile">One of the file associated to the node.</param> /// <param name="files">The list of files to be placed under source control.</param> /// <param name="flags">The flags that are associated to the files.</param> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Scc")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "scc")] public override void GetSccSpecialFiles(string sccFile, IList<string> files, IList<tagVsSccFilesFlags> flags) { if (this.ExcludeNodeFromScc) { return; } if (files == null) { throw new ArgumentNullException("files"); } if (flags == null) { throw new ArgumentNullException("flags"); } if (string.IsNullOrEmpty(sccFile)) { throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "sccFile"); } } /// <summary> /// Recursevily walks the folder nodes and redraws the state icons /// </summary> public override void UpdateSccStateIcons() { for (HierarchyNode child = this.FirstChild; child != null; child = child.NextSibling) { child.UpdateSccStateIcons(); } } internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) { if (cmdGroup == VsMenus.guidStandardCommandSet97) { switch ((VsCommands)cmd) { case VsCommands.Copy: case VsCommands.Paste: case VsCommands.Cut: case VsCommands.Rename: result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; case VsCommands.NewFolder: case VsCommands.AddNewItem: case VsCommands.AddExistingItem: result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; } } else if (cmdGroup == VsMenus.guidStandardCommandSet2K) { if ((VsCommands2K)cmd == VsCommands2K.EXCLUDEFROMPROJECT) { result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; } if ((VsCommands2K) cmd == VsMenus.OpenFolderInExplorerCmdId) { result |= QueryStatusResult.SUPPORTED; result |= CanOpenFolderInExplorer()? QueryStatusResult.ENABLED : QueryStatusResult.INVISIBLE; return VSConstants.S_OK; } } else { return (int)OleConstants.OLECMDERR_E_UNKNOWNGROUP; } return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result); } public bool CanOpenFolderInExplorer() { return Directory.Exists(this.Url); } public void OpenFolderInExplorer() { if (CanOpenFolderInExplorer()) Process.Start(this.Url); } public override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (cmdGroup == VsMenus.guidStandardCommandSet2K) { if ((VsCommands2K) cmd == VsMenus.OpenFolderInExplorerCmdId) { OpenFolderInExplorer(); return VSConstants.S_OK; } } return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut); } public override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) { if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage) { return this.ProjectMgr.CanProjectDeleteItems; } return false; } /// <summary> /// Override if your node is not a file system folder so that /// it does nothing or it deletes it from your storage location. /// </summary> /// <param name="path">Path to the folder to delete</param> public virtual void DeleteFolder(string path) { if (Directory.Exists(path)) Directory.Delete(path, true); } /// <summary> /// creates the physical directory for a folder node /// Override if your node does not use file system folder /// </summary> public virtual void CreateDirectory() { try { if (Directory.Exists(this.Url) == false) { Directory.CreateDirectory(this.Url); } } //TODO - this should not digest all exceptions. catch (System.Exception e) { CCITracing.Trace(e); throw; } } /// <summary> /// Creates a folder nodes physical directory /// Override if your node does not use file system folder /// </summary> /// <param name="newName"></param> /// <returns></returns> public virtual void CreateDirectory(string newName) { if (String.IsNullOrEmpty(newName)) { throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "newName"); } try { // on a new dir && enter, we get called with the same name (so do nothing if name is the same char[] dummy = new char[1]; dummy[0] = Path.DirectorySeparatorChar; string oldDir = this.Url; oldDir = oldDir.TrimEnd(dummy); string strNewDir = Path.Combine(Path.GetDirectoryName(oldDir), newName); if (String.Compare(strNewDir, oldDir, StringComparison.OrdinalIgnoreCase) != 0) { if (Directory.Exists(strNewDir)) { throw new InvalidOperationException(SR.GetString(SR.DirectoryExistError, CultureInfo.CurrentUICulture)); } Directory.CreateDirectory(strNewDir); } } //TODO - this should not digest all exceptions. catch (System.Exception e) { CCITracing.Trace(e); throw; } } /// <summary> /// Rename the physical directory for a folder node /// Override if your node does not use file system folder /// </summary> /// <returns></returns> public virtual void RenameDirectory(string newPath) { if (Directory.Exists(this.Url)) { if (Directory.Exists(newPath)) { ShowFileOrFolderAlreadExistsErrorMessage(newPath); } Directory.Move(this.Url, newPath); } } private void RenameFolder(string newName) { // Do the rename (note that we only do the physical rename if the leaf name changed) string newPath = Path.Combine(this.Parent.VirtualNodeName, newName); if (String.Compare(Path.GetFileName(VirtualNodeName), newName, StringComparison.Ordinal) != 0) { this.RenameDirectory(Path.Combine(this.ProjectMgr.ProjectFolder, newPath)); } this.VirtualNodeName = newPath; this.ItemNode.Rename(VirtualNodeName); // Let all children know of the new path for (HierarchyNode child = this.FirstChild; child != null; child = child.NextSibling) { if (!(child is FolderNode)) { child.SetEditLabel(child.Caption); } else { FolderNode childFolderNode = (FolderNode)child; childFolderNode.RenameFolder(childFolderNode.Caption); } } // Some of the previous operation may have changed the selection so set it back to us IVsUIHierarchyWindow uiWindow = UIHierarchyUtilities.GetUIHierarchyWindow(this.ProjectMgr.Site, SolutionExplorer); ErrorHandler.ThrowOnFailure(uiWindow.ExpandItem(this.ProjectMgr.InteropSafeIVsUIHierarchy, this.ID, EXPANDFLAGS.EXPF_SelectItem)); } /// <summary> /// Show error message if not in automation mode, otherwise throw exception /// </summary> /// <param name="newPath">path of file or folder already existing on disk</param> /// <returns>S_OK</returns> private int ShowFileOrFolderAlreadExistsErrorMessage(string newPath) { //A file or folder with the name '{0}' already exists on disk at this location. Please choose another name. //If this file or folder does not appear in the Solution Explorer, then it is not currently part of your project. To view files which exist on disk, but are not in the project, select Show All Files from the Project menu. string errorMessage = (String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FileOrFolderAlreadyExists, CultureInfo.CurrentUICulture), newPath)); if (!Utilities.IsInAutomationFunction(this.ProjectMgr.Site)) { string title = null; OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL; OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK; OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST; VsShellUtilities.ShowMessageBox(this.ProjectMgr.Site, title, errorMessage, icon, buttons, defaultButton); return VSConstants.S_OK; } else { throw new InvalidOperationException(errorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; public struct VT { public long[,] long2darr; public long[, ,] long3darr; public long[,] long2darr_b; public long[, ,] long3darr_b; public long[,] long2darr_c; public long[, ,] long3darr_c; } public class CL { public long[,] long2darr = { { 0, -1 }, { 0, 0 } }; public long[, ,] long3darr = { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } }; public long[,] long2darr_b = { { 0, 1 }, { 0, 0 } }; public long[, ,] long3darr_b = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; public long[,] long2darr_c = { { 0, 49 }, { 0, 0 } }; public long[, ,] long3darr_c = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; } public class longMDArrTest { static long[,] long2darr = { { 0, -1 }, { 0, 0 } }; static long[, ,] long3darr = { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } }; static long[,] long2darr_b = { { 0, 1 }, { 0, 0 } }; static long[, ,] long3darr_b = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; static long[,] long2darr_c = { { 0, 49 }, { 0, 0 } }; static long[, ,] long3darr_c = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; static long[][,] ja1 = new long[2][,]; static long[][, ,] ja2 = new long[2][, ,]; static long[][,] ja1_b = new long[2][,]; static long[][, ,] ja2_b = new long[2][, ,]; static long[][,] ja1_c = new long[2][,]; static long[][, ,] ja2_c = new long[2][, ,]; public static int Main() { bool pass = true; VT vt1; vt1.long2darr = new long[,] { { 0, -1 }, { 0, 0 } }; vt1.long3darr = new long[,,] { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } }; vt1.long2darr_b = new long[,] { { 0, 1 }, { 0, 0 } }; vt1.long3darr_b = new long[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; vt1.long2darr_c = new long[,] { { 0, 49 }, { 0, 0 } }; vt1.long3darr_c = new long[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; CL cl1 = new CL(); ja1[0] = new long[,] { { 0, -1 }, { 0, 0 } }; ja2[1] = new long[,,] { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } }; ja1_b[0] = new long[,] { { 0, 1 }, { 0, 0 } }; ja2_b[1] = new long[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; ja1_c[0] = new long[,] { { 0, 49 }, { 0, 0 } }; ja2_c[1] = new long[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; long result = -1; // 2D if (result != long2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != vt1.long2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != cl1.long2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != ja1[0][0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (result != long3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != vt1.long3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != cl1.long3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != ja2[1][1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToBool bool Bool_result = true; // 2D if (Bool_result != Convert.ToBoolean(long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(vt1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(cl1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Bool_result != Convert.ToBoolean(long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(vt1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(cl1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToByte tests byte Byte_result = 1; // 2D if (Byte_result != Convert.ToByte(long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(vt1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(cl1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Byte_result != Convert.ToByte(long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(vt1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(cl1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToChar tests char Char_result = '1'; // 2D if (Char_result != Convert.ToChar(long2darr_c[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr_c[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(vt1.long2darr_c[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("vt1.long2darr_c[0, 1] is: {0}", vt1.long2darr_c[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(cl1.long2darr_c[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("cl1.long2darr_c[0, 1] is: {0}", cl1.long2darr_c[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(ja1_c[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("ja1_c[0][0, 1] is: {0}", ja1_c[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Char_result != Convert.ToChar(long3darr_c[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("long3darr_c[1,0,1] is: {0}", long3darr_c[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(vt1.long3darr_c[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("vt1.long3darr_c[1,0,1] is: {0}", vt1.long3darr_c[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(cl1.long3darr_c[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("cl1.long3darr_c[1,0,1] is: {0}", cl1.long3darr_c[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(ja2_c[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("ja2_c[1][1,0,1] is: {0}", ja2_c[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToDecimal tests decimal Decimal_result = -1; // 2D if (Decimal_result != Convert.ToDecimal(long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(vt1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(cl1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Decimal_result != Convert.ToDecimal(long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(vt1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(cl1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToDouble double Double_result = -1; // 2D if (Double_result != Convert.ToDouble(long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(vt1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(cl1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Double_result != Convert.ToDouble(long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(vt1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(cl1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToSingle tests float Single_result = -1; // 2D if (Single_result != Convert.ToSingle(long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(vt1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(cl1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Single_result != Convert.ToSingle(long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(vt1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(cl1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToInt32 tests int Int32_result = -1; // 2D if (Int32_result != Convert.ToInt32(long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(vt1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(cl1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Int32_result != Convert.ToInt32(long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(vt1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(cl1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToSByte tests sbyte SByte_result = -1; // 2D if (SByte_result != Convert.ToSByte(long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(vt1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(cl1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (SByte_result != Convert.ToSByte(long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(vt1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(cl1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToInt16 tests short Int16_result = -1; // 2D if (Int16_result != Convert.ToInt16(long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(vt1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(cl1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Int16_result != Convert.ToInt16(long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(vt1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(cl1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToUInt32 tests uint UInt32_result = 1; // 2D if (UInt32_result != Convert.ToUInt32(long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(vt1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(cl1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt32_result != Convert.ToUInt32(long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(vt1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(cl1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToUInt64 tests ulong UInt64_result = 1; // 2D if (UInt64_result != Convert.ToUInt64(long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(vt1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(cl1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt64_result != Convert.ToUInt64(long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(vt1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(cl1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToUInt16 tests ushort UInt16_result = 1; // 2D if (UInt16_result != Convert.ToUInt16(long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(vt1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(cl1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt16_result != Convert.ToUInt16(long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(vt1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(cl1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (!pass) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); return 100; } } };
// // Test the generated API selectors against typos or non-existing cases // // Authors: // Sebastien Pouliot <sebastien@xamarin.com> // // Copyright 2012-2013 Xamarin Inc. // // 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.Runtime.InteropServices; using System.Reflection; using System.Text; using NUnit.Framework; #if MONOMAC using MonoMac.Foundation; using MonoMac.ObjCRuntime; #else using MonoTouch.Foundation; using MonoTouch.ObjCRuntime; #endif namespace TouchUnit.Bindings { public abstract class ApiSignatureTest : ApiBaseTest { [DllImport ("/usr/lib/libobjc.dylib")] // note: the returned string is not ours to free static extern IntPtr objc_getClass (string name); [DllImport ("/usr/lib/libobjc.dylib")] // note: the returned string is not ours to free static extern IntPtr method_getTypeEncoding (IntPtr method); [DllImport ("/usr/lib/libobjc.dylib")] static extern IntPtr class_getClassMethod (IntPtr klass, IntPtr selector); [DllImport ("/usr/lib/libobjc.dylib")] static extern IntPtr class_getInstanceMethod (IntPtr klass, IntPtr selector); protected int Errors; protected string[] Split (string encoded, out int size) { List<string> elements = new List<string> (); int pos = 0; string s = Next (encoded, ref pos); int end = pos; while (Char.IsDigit (encoded [end])) end++; size = Int32.Parse (encoded.Substring (pos, end - pos)); if (encoded [end] != '@' || encoded [end + 1] != '0' || encoded [end + 2] != ':') { if (!ContinueOnFailure) Assert.Fail ("Unexpected format, missing '@0:', inside '{0}'", encoded); return null; } pos = end + 3; while (s != null) { elements.Add (s); s = Next (encoded, ref pos); } return elements.ToArray (); } static string Next (string encoded, ref int pos) { // skip digits while (pos < encoded.Length && Char.IsDigit (encoded [pos])) pos++; if (pos >= encoded.Length) return null; StringBuilder sb = new StringBuilder (); int acc = 0; char c = encoded [pos]; while (!Char.IsDigit (c) || acc > 0) { sb.Append (c); if (c == '{' || c == '(') acc++; else if (c == '}' || c == ')') acc--; if (++pos >= encoded.Length) break; c = encoded [pos]; } return sb.ToString (); } protected virtual int Size (Type t) { if (!t.IsValueType) return IntPtr.Size; // platform if (t.IsEnum) { // Gendarme code has better (and more complex) logic switch (t.Name) { case "NSAlignmentOptions": case "NSEventMask": case "NSTextCheckingType": case "NSTextCheckingTypes": return 8; // [u]long default: return 4; } } int size = Marshal.SizeOf (t); return t.IsPrimitive && size < 4 ? 4 : size; } protected virtual bool Skip (Type type) { return false; } protected virtual bool Skip (Type type, MethodBase method, string selector) { return false; } public int CurrentParameter { get; private set; } public MethodBase CurrentMethod { get; private set; } public string CurrentSelector { get; private set; } public Type CurrentType { get; private set; } [Test] public void Signatures () { int n = 0; Errors = 0; foreach (Type t in Assembly.GetTypes ()) { if (t.IsNested || !NSObjectType.IsAssignableFrom (t)) continue; if (Skip (t)) continue; CurrentType = t; FieldInfo fi = t.GetField ("class_ptr", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); if (fi == null) continue; // e.g. *Delegate IntPtr class_ptr = (IntPtr) fi.GetValue (null); foreach (MethodBase m in t.GetMethods (BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance)) CheckMemberSignature (m, t, class_ptr, ref n); foreach (MethodBase m in t.GetConstructors (BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance)) CheckMemberSignature (m, t, class_ptr, ref n); } Assert.AreEqual (0, Errors, "{0} errors found in {1} signatures validated", Errors, n); } void CheckMemberSignature (MethodBase m, Type t, IntPtr class_ptr, ref int n) { var methodinfo = m as MethodInfo; var constructorinfo = m as ConstructorInfo; if (methodinfo == null && constructorinfo == null) return; if (m.DeclaringType != t) return; CurrentMethod = m; foreach (object ca in m.GetCustomAttributes (true)) { if (ca is ExportAttribute) { string name = (ca as ExportAttribute).Selector; if (Skip (t, m, name)) continue; CurrentSelector = name; IntPtr sel = Selector.GetHandle (name); IntPtr method; if (methodinfo != null) method = m.IsStatic ? class_getClassMethod (class_ptr, sel) : class_getInstanceMethod (class_ptr, sel); else method = class_getInstanceMethod (class_ptr, sel); IntPtr tenc = method_getTypeEncoding (method); string encoded = Marshal.PtrToStringAuto (tenc); if (LogProgress) Console.WriteLine ("{0} {1} '{2} {3}' selector: {4} == {5}", ++n, t.Name, methodinfo != null ? methodinfo.IsStatic ? "static" : "instance" : "ctor", m, name, encoded); // NSObject has quite a bit of stuff that's not usable (except by some class that inherits from it) if (String.IsNullOrEmpty (encoded)) continue; int encoded_size = -1; string [] elements = null; try { elements = Split (encoded, out encoded_size); } catch { } if (elements == null) { if (LogProgress) Console.WriteLine ("[WARNING] Could not parse encoded signature for {0} : {1}", name, encoded); continue; } bool result; CurrentParameter = 0; if (methodinfo != null) { // check return value result = Check (elements [CurrentParameter], methodinfo.ReturnType); if (!ContinueOnFailure) Assert.IsTrue (result, "Return Value"); else if (!result) { Console.WriteLine ("[FAIL] Return Value: {0}", name); Errors++; } } int size = 2 * IntPtr.Size; // self + selector (@0:) var parameters = m.GetParameters (); foreach (var p in parameters) { CurrentParameter++; var pt = p.ParameterType; if (n == 719) Console.WriteLine (); result = Check (elements [CurrentParameter], pt); if (!ContinueOnFailure) Assert.IsTrue (result, "Parameter {0}", CurrentParameter); else if (!result) { Console.WriteLine ("[FAIL] Parameter {0}: {1}", CurrentParameter, name); Errors++; } size += Size (pt); } // also ensure the encoded size match what MT (or XM) provides // catch API errors (and should catch most 64bits issues as well) result = size == encoded_size; if (!ContinueOnFailure) Assert.IsTrue (result, "Size {0} != {1}", encoded_size, size); else if (!result) { Console.WriteLine ("[FAIL] Size {0} != {1} for {2}", encoded_size, size, name); Errors++; } } } } protected virtual bool IsValidStruct (Type type, string structName) { switch (structName) { // MKPolygon 'static MonoTouch.MapKit.MKPolygon _FromPoints(IntPtr, Int32)' selector: polygonWithPoints:count: == @16@0:4^{?=dd}8I12 // NSValue 'static MonoTouch.Foundation.NSValue FromCMTime(CMTime)' selector: valueWithCMTime: == @32@0:4{?=qiIq}8 case "?": return type.IsValueType; // || (type.FullName == "System.IntPtr"); case "CGRect": return type.FullName == "System.Drawing.RectangleF"; case "CGSize": return type.FullName == "System.Drawing.SizeF"; case "CGPoint": return type.FullName == "System.Drawing.PointF"; case "opaqueCMFormatDescription": structName = "CMFormatDescription"; break; case "opaqueCMSampleBuffer": structName = "CMSampleBuffer"; break; case "_NSRange": structName = "NSRange"; break; // textureWithContentsOfFile:options:queue:completionHandler: == v24@0:4@8@12^{dispatch_queue_s=}16@?20 case "dispatch_queue_s": structName = "DispatchQueue"; break; case "OpaqueCMClock": structName = "CMClock"; break; case "OpaqueCMTimebase": structName = "CMTimebase"; break; case "__CFRunLoop": structName = "CFRunLoop"; break; case "_GLKVector4": structName = "Vector4"; break; case "_GLKVector3": structName = "Vector3"; break; case "_GLKMatrix3": structName = "Matrix3"; break; case "_GLKMatrix4": structName = "Matrix4"; break; case "__CVPixelBufferPool": structName = "CVPixelBufferPool"; break; case "opaqueMTAudioProcessingTap": structName = "MTAudioProcessingTap"; break; case "OpaqueMIDIEndpoint": structName = "MidiEndpoint"; break; case "__CFDictionary": structName = "NSDictionary"; break; case "_CGLContextObject": structName = "CGLContext"; break; case "_CGLPixelFormatObject": structName = "CGLPixelFormat"; break; } return type.Name == structName; } static Type inativeobject = typeof (INativeObject); bool Check (string encodedType, Type type) { char c = encodedType [0]; if (encodedType.Length == 1) return Check (c, type); switch (c) { // GLKBaseEffect 'instance Vector4 get_LightModelAmbientColor()' selector: lightModelAmbientColor == (_GLKVector4={?=ffff}{?=ffff}{?=ffff}[4f])8@0:4 case '(': case '{': string struct_name = encodedType.Substring (1, encodedType.IndexOf ('=') - 1); return IsValidStruct (type, struct_name); case '@': switch (encodedType [1]) { case '?': return (type.Name == "NSAction") || type.BaseType.FullName == "System.MulticastDelegate"; default: return false; } case '^': switch (encodedType [1]) { case 'v': // NSOpenGLContext 'instance MonoMac.OpenGL.CGLContext get_CGLContext()' selector: CGLContextObj == ^v8@0:4 if ((CurrentType.Name == "NSOpenGLContext") && (type.Name == "CGLContext")) return true; // NSOpenGLPixelFormat 'instance MonoMac.OpenGL.CGLPixelFormat get_CGLPixelFormat()' selector: CGLPixelFormatObj == ^v8@0:4 if ((CurrentType.Name == "NSOpenGLPixelFormat") && (type.Name == "CGLPixelFormat")) return true; return (type.FullName == "System.IntPtr"); case 'd': case 'f': case 'I': case 'i': case 'c': case 'q': case 'Q': return (type.FullName == "System.IntPtr") || Check (encodedType.Substring (1), type.GetElementType ()); // NSInputStream 'instance Boolean GetBuffer(IntPtr ByRef, UInt32 ByRef)' selector: getBuffer:length: == c16@0:4^*8^I12 case '*': case '{': // 10.7 only: NSArray 'static MonoMac.Foundation.NSArray FromObjects(IntPtr, Int32)' selector: arrayWithObjects:count: == @16@0:4^r@8I12 case 'r': if (type.FullName == "System.IntPtr") return true; return Check (encodedType.Substring (1), type.IsByRef ? type.GetElementType () : type); case '@': return Check ('@', type.IsByRef ? type.GetElementType () : type); case '^': return (type.FullName == "System.IntPtr"); default: return false; } case 'r': // const -> ignore // e.g. vectorWithValues:count: == @16@0:4r^f8L12 case 'o': // out -> ignore // e.g. validateValue:forKey:error: == c20@0:4N^@8@12o^@16 case 'N': // inout -> ignore // e.g. validateValue:forKey:error: == c20@0:4N^@8@12o^@16 case 'V': // oneway -> ignore // e.g. NSObject 'instance Void NativeRelease()' selector: release == Vv8@0:4 return Check (encodedType.Substring (1), type); default: return false; } } /// <summary> /// Check that specified encodedType match the type and caller. /// </summary> /// <param name="encodedType">Encoded type from the ObjC signature.</param> /// <param name="type">Managed type representing the encoded type.</param> /// <param name="caller">Caller's type. Useful to limit any special case.</param> protected virtual bool Check (char encodedType, Type type) { switch (encodedType) { case '@': return (type.IsArray || // NSArray (type.Name == "NSArray") || // NSArray (type.FullName == "System.String") || // NSString (type.FullName == "System.IntPtr") || // unbinded, e.g. internal (type.BaseType.FullName == "System.MulticastDelegate") || // completion handler -> delegate NSObjectType.IsAssignableFrom (type)) || // NSObject derived inativeobject.IsAssignableFrom (type); // e.g. CGImage case 'c': // char, used for C# bool switch (type.FullName) { case "System.Boolean": case "System.SByte": return true; default: return false; } case 'C': switch (type.FullName) { case "System.Byte": // GLKBaseEffect 'instance Boolean get_ColorMaterialEnabled()' selector: colorMaterialEnabled == C8@0:4 case "System.Boolean": return true; default: return false; } case 'd': return type.FullName == "System.Double"; case 'f': return type.FullName == "System.Single"; case 'i': return type.FullName == "System.Int32" || type.BaseType.FullName == "System.Enum"; case 'I': return type.FullName == "System.UInt32" || type.BaseType.FullName == "System.Enum"; case 'l': return type.FullName == "System.Int32"; case 'L': return type.FullName == "System.UInt32"; case 'q': return type.FullName == "System.Int64"; case 'Q': return type.FullName == "System.UInt64"; case 's': return type.FullName == "System.Int16"; // unsigned 16 bits case 'S': switch (type.FullName) { case "System.UInt16": // NSString 'instance Char _characterAtIndex(Int32)' selector: characterAtIndex: == S12@0:4I8 case "System.Char": return true; default: return false; } case ':': return type.Name == "Selector"; case 'v': return type.FullName == "System.Void"; case '?': return type.BaseType.FullName == "System.MulticastDelegate"; // completion handler -> delegate case '#': return type.FullName == "System.IntPtr" || type.Name == "Class"; // CAMediaTimingFunction 'instance Void GetControlPointAtIndex(Int32, IntPtr)' selector: getControlPointAtIndex:values: == v16@0:4L8[2f]12 case '[': return type.FullName == "System.IntPtr"; // const uint8_t * -> IntPtr // NSCoder 'instance Void EncodeBlock(IntPtr, Int32, System.String)' selector: encodeBytes:length:forKey: == v20@0:4r*8I12@16 case '*': return type.FullName == "System.IntPtr"; default: return false; } } } }
// created on 10/12/2002 at 20:37 using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace NAudio.Mixer { /// <summary> /// Represents a mixer line (source or destination) /// </summary> public class MixerLine { private readonly IntPtr mixerHandle; private readonly MixerFlags mixerHandleType; private MixerInterop.MIXERLINE mixerLine; /// <summary> /// Creates a new mixer destination /// </summary> /// <param name="mixerHandle">Mixer Handle</param> /// <param name="destinationIndex">Destination Index</param> /// <param name="mixerHandleType">Mixer Handle Type</param> public MixerLine(IntPtr mixerHandle, int destinationIndex, MixerFlags mixerHandleType) { this.mixerHandle = mixerHandle; this.mixerHandleType = mixerHandleType; mixerLine = new MixerInterop.MIXERLINE(); mixerLine.cbStruct = Marshal.SizeOf(mixerLine); mixerLine.dwDestination = destinationIndex; MmException.Try( MixerInterop.mixerGetLineInfo(mixerHandle, ref mixerLine, mixerHandleType | MixerFlags.GetLineInfoOfDestination), "mixerGetLineInfo"); } /// <summary> /// Creates a new Mixer Source For a Specified Source /// </summary> /// <param name="mixerHandle">Mixer Handle</param> /// <param name="destinationIndex">Destination Index</param> /// <param name="sourceIndex">Source Index</param> /// <param name="mixerHandleType">Flag indicating the meaning of mixerHandle</param> public MixerLine(IntPtr mixerHandle, int destinationIndex, int sourceIndex, MixerFlags mixerHandleType) { this.mixerHandle = mixerHandle; this.mixerHandleType = mixerHandleType; mixerLine = new MixerInterop.MIXERLINE(); mixerLine.cbStruct = Marshal.SizeOf(mixerLine); mixerLine.dwDestination = destinationIndex; mixerLine.dwSource = sourceIndex; MmException.Try( MixerInterop.mixerGetLineInfo(mixerHandle, ref mixerLine, mixerHandleType | MixerFlags.GetLineInfoOfSource), "mixerGetLineInfo"); } /// <summary> /// Mixer Line Name /// </summary> public String Name { get { return mixerLine.szName; } } /// <summary> /// Mixer Line short name /// </summary> public String ShortName { get { return mixerLine.szShortName; } } /// <summary> /// The line ID /// </summary> public int LineId { get { return mixerLine.dwLineID; } } /// <summary> /// Component Type /// </summary> public MixerLineComponentType ComponentType { get { return mixerLine.dwComponentType; } } /// <summary> /// Mixer destination type description /// </summary> public String TypeDescription { get { switch (mixerLine.dwComponentType) { // destinations case MixerLineComponentType.DestinationUndefined: return "Undefined Destination"; case MixerLineComponentType.DestinationDigital: return "Digital Destination"; case MixerLineComponentType.DestinationLine: return "Line Level Destination"; case MixerLineComponentType.DestinationMonitor: return "Monitor Destination"; case MixerLineComponentType.DestinationSpeakers: return "Speakers Destination"; case MixerLineComponentType.DestinationHeadphones: return "Headphones Destination"; case MixerLineComponentType.DestinationTelephone: return "Telephone Destination"; case MixerLineComponentType.DestinationWaveIn: return "Wave Input Destination"; case MixerLineComponentType.DestinationVoiceIn: return "Voice Recognition Destination"; // sources case MixerLineComponentType.SourceUndefined: return "Undefined Source"; case MixerLineComponentType.SourceDigital: return "Digital Source"; case MixerLineComponentType.SourceLine: return "Line Level Source"; case MixerLineComponentType.SourceMicrophone: return "Microphone Source"; case MixerLineComponentType.SourceSynthesizer: return "Synthesizer Source"; case MixerLineComponentType.SourceCompactDisc: return "Compact Disk Source"; case MixerLineComponentType.SourceTelephone: return "Telephone Source"; case MixerLineComponentType.SourcePcSpeaker: return "PC Speaker Source"; case MixerLineComponentType.SourceWaveOut: return "Wave Out Source"; case MixerLineComponentType.SourceAuxiliary: return "Auxiliary Source"; case MixerLineComponentType.SourceAnalog: return "Analog Source"; default: return "Invalid Component Type"; } } } /// <summary> /// Number of channels /// </summary> public int Channels { get { return mixerLine.cChannels; } } /// <summary> /// Number of sources /// </summary> public int SourceCount { get { return mixerLine.cConnections; } } /// <summary> /// Number of controls /// </summary> public int ControlsCount { get { return mixerLine.cControls; } } /// <summary> /// Is this destination active /// </summary> public bool IsActive { get { return (mixerLine.fdwLine & MixerInterop.MIXERLINE_LINEF.MIXERLINE_LINEF_ACTIVE) != 0; } } /// <summary> /// Is this destination disconnected /// </summary> public bool IsDisconnected { get { return (mixerLine.fdwLine & MixerInterop.MIXERLINE_LINEF.MIXERLINE_LINEF_DISCONNECTED) != 0; } } /// <summary> /// Is this destination a source /// </summary> public bool IsSource { get { return (mixerLine.fdwLine & MixerInterop.MIXERLINE_LINEF.MIXERLINE_LINEF_SOURCE) != 0; } } /// <summary> /// Enumerator for the controls on this Mixer Limne /// </summary> public IEnumerable<MixerControl> Controls { get { return MixerControl.GetMixerControls(mixerHandle, this, mixerHandleType); } } /// <summary> /// Enumerator for the sources on this Mixer Line /// </summary> public IEnumerable<MixerLine> Sources { get { for (int source = 0; source < SourceCount; source++) { yield return GetSource(source); } } } /// <summary> /// The name of the target output device /// </summary> public string TargetName { get { return mixerLine.szPname; } } /// <summary> /// Creates a new Mixer Source /// </summary> /// <param name="waveInDevice">Wave In Device</param> public static int GetMixerIdForWaveIn(int waveInDevice) { int mixerId = -1; MmException.Try(MixerInterop.mixerGetID((IntPtr) waveInDevice, out mixerId, MixerFlags.WaveIn), "mixerGetID"); return mixerId; } /// <summary> /// Gets the specified source /// </summary> public MixerLine GetSource(int sourceIndex) { if (sourceIndex < 0 || sourceIndex >= SourceCount) { throw new ArgumentOutOfRangeException("sourceIndex"); } return new MixerLine(mixerHandle, mixerLine.dwDestination, sourceIndex, mixerHandleType); } /// <summary> /// Describes this Mixer Line (for diagnostic purposes) /// </summary> public override string ToString() { return String.Format("{0} {1} ({2} controls, ID={3})", Name, TypeDescription, ControlsCount, mixerLine.dwLineID); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using MS.Internal.Xml.Cache; using System.Collections.Generic; using System.Diagnostics; using System.IO; namespace System.Xml.XPath { /// <summary> /// XDocument follows the XPath/XQuery data model. All nodes in the tree reference the document, /// and the document references the root node of the tree. All namespaces are stored out-of-line, /// in an Element --> In-Scope-Namespaces map. /// </summary> public class XPathDocument : IXPathNavigable { private XPathNode[] _pageText, _pageRoot, _pageXmlNmsp; private int _idxText, _idxRoot, _idxXmlNmsp; private XmlNameTable _nameTable; private bool _hasLineInfo; private Dictionary<XPathNodeRef, XPathNodeRef> _mapNmsp; private Dictionary<string, XPathNodeRef> _idValueMap = null; /// <summary> /// Flags that control Load behavior. /// </summary> internal enum LoadFlags { None = 0, AtomizeNames = 1, // Do not assume that names passed to XPathDocumentBuilder have been pre-atomized, and atomize them Fragment = 2, // Create a document with no document node } //----------------------------------------------- // Creation Methods //----------------------------------------------- /// <summary> /// Create a new empty document. /// </summary> internal XPathDocument() { _nameTable = new NameTable(); } /// <summary> /// Create a new document and load the content from the reader. /// </summary> public XPathDocument(XmlReader reader) : this(reader, XmlSpace.Default) { } /// <summary> /// Create a new document from "reader", with whitespace handling controlled according to "space". /// </summary> public XPathDocument(XmlReader reader, XmlSpace space) { if (reader == null) throw new ArgumentNullException("reader"); LoadFromReader(reader, space); } /// <summary> /// Create a new document and load the content from the text reader. /// </summary> public XPathDocument(TextReader textReader) { using (XmlReader reader = XmlReader.Create(textReader)) { LoadFromReader(reader, XmlSpace.Default); } } /// <summary> /// Create a new document and load the content from the stream. /// </summary> public XPathDocument(Stream stream) { using (XmlReader reader = XmlReader.Create(stream)) { LoadFromReader(reader, XmlSpace.Default); } } /// <summary> /// Create a new document and load the content from the Uri. /// </summary> public XPathDocument(string uri) : this(uri, XmlSpace.Default) { } /// <summary> /// Create a new document and load the content from the Uri, with whitespace handling controlled according to "space". /// </summary> public XPathDocument(string uri, XmlSpace space) { using (XmlReader reader = XmlReader.Create(uri)) { LoadFromReader(reader, space); } } /// <summary> /// Create a writer that can be used to create nodes in this document. The root node will be assigned "baseUri", and flags /// can be passed to indicate that names should be atomized by the builder and/or a fragment should be created. /// </summary> internal void LoadFromReader(XmlReader reader, XmlSpace space) { XPathDocumentBuilder builder; IXmlLineInfo lineInfo; string xmlnsUri; bool topLevelReader; int initialDepth; if (reader == null) throw new ArgumentNullException("reader"); // Determine line number provider lineInfo = reader as IXmlLineInfo; if (lineInfo == null || !lineInfo.HasLineInfo()) lineInfo = null; _hasLineInfo = (lineInfo != null); _nameTable = reader.NameTable; builder = new XPathDocumentBuilder(this, lineInfo, reader.BaseURI, LoadFlags.None); try { // Determine whether reader is in initial state topLevelReader = (reader.ReadState == ReadState.Initial); initialDepth = reader.Depth; // Get atomized xmlns uri Debug.Assert((object)_nameTable.Get(string.Empty) == (object)string.Empty, "NameTable must contain atomized string.Empty"); xmlnsUri = _nameTable.Get(XmlConst.ReservedNsXmlNs); // Read past Initial state; if there are no more events then load is complete if (topLevelReader && !reader.Read()) return; // Read all events do { // If reader began in intermediate state, return when all siblings have been read if (!topLevelReader && reader.Depth < initialDepth) return; switch (reader.NodeType) { case XmlNodeType.Element: { bool isEmptyElement = reader.IsEmptyElement; builder.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI, reader.BaseURI); // Add attribute and namespace nodes to element while (reader.MoveToNextAttribute()) { string namespaceUri = reader.NamespaceURI; if ((object)namespaceUri == (object)xmlnsUri) { if (reader.Prefix.Length == 0) { // Default namespace declaration "xmlns" Debug.Assert(reader.LocalName == "xmlns"); builder.WriteNamespaceDeclaration(string.Empty, reader.Value); } else { Debug.Assert(reader.Prefix == "xmlns"); builder.WriteNamespaceDeclaration(reader.LocalName, reader.Value); } } else { builder.WriteStartAttribute(reader.Prefix, reader.LocalName, namespaceUri); builder.WriteString(reader.Value, TextBlockType.Text); builder.WriteEndAttribute(); } } if (isEmptyElement) builder.WriteEndElement(true); break; } case XmlNodeType.EndElement: builder.WriteEndElement(false); break; case XmlNodeType.Text: case XmlNodeType.CDATA: builder.WriteString(reader.Value, TextBlockType.Text); break; case XmlNodeType.SignificantWhitespace: if (reader.XmlSpace == XmlSpace.Preserve) builder.WriteString(reader.Value, TextBlockType.SignificantWhitespace); else // Significant whitespace without xml:space="preserve" is not significant in XPath/XQuery data model goto case XmlNodeType.Whitespace; break; case XmlNodeType.Whitespace: // We intentionally ignore the reader.XmlSpace property here and blindly trust // the reported node type. If the reported information is not in sync // (in this case if the reader.XmlSpace == Preserve) then we make the choice // to trust the reported node type. Since we have no control over the input reader // we can't even assert here. // Always filter top-level whitespace if (space == XmlSpace.Preserve && (!topLevelReader || reader.Depth != 0)) builder.WriteString(reader.Value, TextBlockType.Whitespace); break; case XmlNodeType.Comment: builder.WriteComment(reader.Value); break; case XmlNodeType.ProcessingInstruction: builder.WriteProcessingInstruction(reader.LocalName, reader.Value, reader.BaseURI); break; case XmlNodeType.EntityReference: reader.ResolveEntity(); break; case XmlNodeType.DocumentType: case XmlNodeType.EndEntity: case XmlNodeType.None: case XmlNodeType.XmlDeclaration: break; } } while (reader.Read()); } finally { builder.CloseWithoutDisposing(); } } /// <summary> /// Create a navigator positioned on the root node of the document. /// </summary> public XPathNavigator CreateNavigator() { return new XPathDocumentNavigator(_pageRoot, _idxRoot, null, 0); } //----------------------------------------------- // Document Properties //----------------------------------------------- /// <summary> /// Return the name table used to atomize all name parts (local name, namespace uri, prefix). /// </summary> internal XmlNameTable NameTable { get { return _nameTable; } } /// <summary> /// Return true if line number information is recorded in the cache. /// </summary> internal bool HasLineInfo { get { return _hasLineInfo; } } /// <summary> /// Return the singleton collapsed text node associated with the document. One physical text node /// represents each logical text node in the document that is the only content-typed child of its /// element parent. /// </summary> internal int GetCollapsedTextNode(out XPathNode[] pageText) { pageText = _pageText; return _idxText; } /// <summary> /// Set the page and index where the singleton collapsed text node is stored. /// </summary> internal void SetCollapsedTextNode(XPathNode[] pageText, int idxText) { _pageText = pageText; _idxText = idxText; } /// <summary> /// Return the root node of the document. This may not be a node of type XPathNodeType.Root if this /// is a document fragment. /// </summary> internal int GetRootNode(out XPathNode[] pageRoot) { pageRoot = _pageRoot; return _idxRoot; } /// <summary> /// Set the page and index where the root node is stored. /// </summary> internal void SetRootNode(XPathNode[] pageRoot, int idxRoot) { _pageRoot = pageRoot; _idxRoot = idxRoot; } /// <summary> /// Every document has an implicit xmlns:xml namespace node. /// </summary> internal int GetXmlNamespaceNode(out XPathNode[] pageXmlNmsp) { pageXmlNmsp = _pageXmlNmsp; return _idxXmlNmsp; } /// <summary> /// Set the page and index where the implicit xmlns:xml node is stored. /// </summary> internal void SetXmlNamespaceNode(XPathNode[] pageXmlNmsp, int idxXmlNmsp) { _pageXmlNmsp = pageXmlNmsp; _idxXmlNmsp = idxXmlNmsp; } /// <summary> /// Associate a namespace node with an element. /// </summary> internal void AddNamespace(XPathNode[] pageElem, int idxElem, XPathNode[] pageNmsp, int idxNmsp) { Debug.Assert(pageElem[idxElem].NodeType == XPathNodeType.Element && pageNmsp[idxNmsp].NodeType == XPathNodeType.Namespace); if (_mapNmsp == null) _mapNmsp = new Dictionary<XPathNodeRef, XPathNodeRef>(); _mapNmsp.Add(new XPathNodeRef(pageElem, idxElem), new XPathNodeRef(pageNmsp, idxNmsp)); } /// <summary> /// Lookup the namespace nodes associated with an element. /// </summary> internal int LookupNamespaces(XPathNode[] pageElem, int idxElem, out XPathNode[] pageNmsp) { XPathNodeRef nodeRef = new XPathNodeRef(pageElem, idxElem); Debug.Assert(pageElem[idxElem].NodeType == XPathNodeType.Element); // Check whether this element has any local namespaces if (_mapNmsp == null || !_mapNmsp.ContainsKey(nodeRef)) { pageNmsp = null; return 0; } // Yes, so return the page and index of the first local namespace node nodeRef = _mapNmsp[nodeRef]; pageNmsp = nodeRef.Page; return nodeRef.Index; } /// <summary> /// Lookup the element node associated with the specified ID value. /// </summary> internal int LookupIdElement(string id, out XPathNode[] pageElem) { XPathNodeRef nodeRef; if (_idValueMap == null || !_idValueMap.ContainsKey(id)) { pageElem = null; return 0; } // Extract page and index from XPathNodeRef nodeRef = _idValueMap[id]; pageElem = nodeRef.Page; return nodeRef.Index; } } }
// // Copyright (c) 2003-2006 Jaroslaw Kowalski <jaak@jkowalski.net> // Copyright (c) 2006-2014 Piotr Fusik <piotr@fusik.info> // // 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 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 NUnit.Framework; using Sooda.UnitTests.BaseObjects; using System; namespace Sooda.UnitTests.TestCases.ObjectMapper { [TestFixture] public class CollectionTest { bool predicate1(SoodaObject c0) { Contact c = (Contact)c0; return (string)c.Name != "Mary Manager"; } [Test] public void GetListTest() { using (TestSqlDataSource testDataSource = new TestSqlDataSource("default")) { testDataSource.Open(); using (SoodaTransaction tran = new SoodaTransaction()) { tran.RegisterDataSource(testDataSource); Contact mary = Contact.Load(1); //mary.Name = "Ala ma kota"; Contact ed = Contact.Load(2); ed.PrimaryGroup = null; ContactList list = Contact.GetList(tran, new SoodaWhereClause("PrimaryGroup.Manager.Name = 'Mary Manager'"), SoodaSnapshotOptions.Default); Console.WriteLine("Len: {0}", list.Count); SoodaObjectMultiFieldComparer comparer = new SoodaObjectMultiFieldComparer(); comparer.AddField(new string[] { "PrimaryGroup", "Name" }, SortOrder.Ascending); comparer.AddField("LastSalary", SortOrder.Ascending); comparer.AddField("Name", SortOrder.Descending); foreach (Contact c in list.Sort(comparer).Filter(new SoodaObjectFilter(predicate1))) { Console.WriteLine("Member: {0} - {2} - {1}", c.Evaluate("PrimaryGroup.Name"), c.Name, c.LastSalary); } tran.Commit(); } } } [Test] public void Collection1toNTest() { Collection1toNTest(false); } [Test] [Ignore("not implemented yet")] public void SharedCollection1ToNTest() { using (SoodaTransaction tran = new SoodaTransaction()) { Group g1 = Group.GetRef(10); Contact newManager = new Contact(); newManager.Type = ContactType.Manager; Assert.AreEqual(g1.Managers.Count, 1); Assert.IsTrue(g1.Members.Contains(Contact.Mary)); Assert.IsTrue(g1.Managers.Contains(Contact.Mary)); g1.Managers.Remove(Contact.Mary); Assert.AreEqual(g1.Managers.Count, 0); Assert.IsTrue(!g1.Members.Contains(Contact.Mary)); Assert.IsTrue(!g1.Managers.Contains(Contact.Mary)); g1.Managers.Add(Contact.Mary); Assert.AreEqual(g1.Managers.Count, 1); Assert.IsTrue(g1.Members.Contains(Contact.Mary)); Assert.IsTrue(g1.Managers.Contains(Contact.Mary)); g1.Members.Add(newManager); Assert.AreEqual(g1.Managers.Count, 2); } } public void Collection1toNTest(bool quiet) { string serialized; using (TestSqlDataSource testDataSource = new TestSqlDataSource("default")) { testDataSource.Open(); using (SoodaTransaction tran = new SoodaTransaction()) { tran.RegisterDataSource(testDataSource); Contact c1; Group g = Group.Load(10); Assert.AreEqual((string)g.Manager.Name, "Mary Manager"); Assert.AreEqual(g.Members.Count, 4); Assert.IsTrue(g.Members.Contains(Contact.GetRef(53))); g.Members.Remove(Contact.GetRef(53)); Assert.AreEqual(g.Members.Count, 3); Assert.IsTrue(!g.Members.Contains(Contact.GetRef(53))); g.Members.Add(c1 = new Contact()); c1.Name = "Nancy Newcomer"; c1.Active = true; Assert.AreEqual(g.Members.Count, 4); c1.Type = ContactType.Employee; Assert.IsTrue(g.Members.Contains(Contact.GetRef(51))); Assert.IsTrue(g.Members.Contains(Contact.GetRef(1))); Assert.IsTrue(g.Members.Contains(Contact.GetRef(2))); int times = 0; foreach (Contact c in g.Members) { if (!quiet) Console.WriteLine("Got {0} [{1}]", c.Name, c.ContactId); times++; Assert.IsTrue( c == Contact.GetRef(51) || c == Contact.GetRef(1) || c == c1 || c == Contact.GetRef(2)); }; Assert.AreEqual(times, 4, "foreach() loop gets called 4 times"); Assert.IsTrue(!g.Members.Contains(Contact.GetRef(53))); Assert.IsTrue(g.Members.Contains(Contact.GetRef(51))); Assert.IsTrue(g.Members.Contains(Contact.GetRef(1))); Assert.IsTrue(g.Members.Contains(Contact.GetRef(2))); Assert.IsTrue(g.Members.Contains(c1)); Assert.AreEqual(g.Members.Count, 4); foreach (Contact c in g.Members) { if (!quiet) Console.WriteLine("before serialization, member: {0}", c.Name); } serialized = tran.Serialize(SoodaSerializeOptions.IncludeNonDirtyFields | SoodaSerializeOptions.IncludeNonDirtyObjects | SoodaSerializeOptions.Canonical); //serialized = tran.Serialize(); if (!quiet) Console.WriteLine("Serialized as\n{0}", serialized); } using (SoodaTransaction tran = new SoodaTransaction()) { tran.RegisterDataSource(testDataSource); tran.Deserialize(serialized); string serialized2 = tran.Serialize(SoodaSerializeOptions.IncludeNonDirtyFields | SoodaSerializeOptions.IncludeNonDirtyObjects | SoodaSerializeOptions.Canonical); //string serialized2 = tran.Serialize(); if (serialized == serialized2) { if (!quiet) Console.WriteLine("Serialization is stable"); } else { if (!quiet) Console.WriteLine("Serialized again as\n{0}", serialized2); } Assert.AreEqual(serialized, serialized2, "Serialization preserves state"); Group g = Group.Load(10); foreach (Contact c in g.Members) { //if (!quiet) Console.WriteLine("after deserialization, member: {0}", c.Name); } Assert.AreEqual("Mary Manager", g.Manager.Name); Assert.AreEqual(4, g.Members.Count); Assert.IsTrue(!g.Members.Contains(Contact.GetRef(53))); Assert.IsTrue(g.Members.Contains(Contact.GetRef(51))); Assert.IsTrue(g.Members.Contains(Contact.GetRef(1))); Assert.IsTrue(g.Members.Contains(Contact.GetRef(2))); int times = 0; foreach (Contact c in g.Members) { times++; Assert.IsTrue( c == Contact.GetRef(51) || c == Contact.GetRef(1) || (string)c.Name == "Nancy Newcomer" || c == Contact.GetRef(2)); }; Assert.AreEqual(times, 4, "foreach() loop gets called 4 times"); Assert.IsTrue(!g.Members.Contains(Contact.GetRef(53))); Assert.IsTrue(g.Members.Contains(Contact.GetRef(51))); Assert.IsTrue(g.Members.Contains(Contact.GetRef(1))); Assert.IsTrue(g.Members.Contains(Contact.GetRef(2))); Assert.AreEqual(g.Members.Count, 4); tran.Commit(); } } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; using StandardFilter = Lucene.Net.Analysis.Standard.StandardFilter; using StandardTokenizer = Lucene.Net.Analysis.Standard.StandardTokenizer; using English = Lucene.Net.Util.English; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Analysis { /// <summary> tests for the TeeTokenFilter and SinkTokenizer</summary> [TestFixture] public class TestTeeTokenFilter:LuceneTestCase { private class AnonymousClassSinkTokenizer:SinkTokenizer { private void InitBlock(TestTeeTokenFilter enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestTeeTokenFilter enclosingInstance; public TestTeeTokenFilter Enclosing_Instance { get { return enclosingInstance; } } internal AnonymousClassSinkTokenizer(TestTeeTokenFilter enclosingInstance, System.Collections.IList Param1):base(Param1) { InitBlock(enclosingInstance); } public override void Add(Token t) { if (t != null && t.Term().ToUpper().Equals("The".ToUpper())) { base.Add(t); } } } private class AnonymousClassSinkTokenizer1:SinkTokenizer { private void InitBlock(TestTeeTokenFilter enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestTeeTokenFilter enclosingInstance; public TestTeeTokenFilter Enclosing_Instance { get { return enclosingInstance; } } internal AnonymousClassSinkTokenizer1(TestTeeTokenFilter enclosingInstance, System.Collections.IList Param1):base(Param1) { InitBlock(enclosingInstance); } public override void Add(Token t) { if (t != null && t.Term().ToUpper().Equals("The".ToUpper())) { base.Add(t); } } } private class AnonymousClassSinkTokenizer2:SinkTokenizer { private void InitBlock(TestTeeTokenFilter enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestTeeTokenFilter enclosingInstance; public TestTeeTokenFilter Enclosing_Instance { get { return enclosingInstance; } } internal AnonymousClassSinkTokenizer2(TestTeeTokenFilter enclosingInstance, System.Collections.IList Param1):base(Param1) { InitBlock(enclosingInstance); } public override void Add(Token t) { if (t != null && t.Term().ToUpper().Equals("Dogs".ToUpper())) { base.Add(t); } } } protected internal System.Text.StringBuilder buffer1; protected internal System.Text.StringBuilder buffer2; protected internal System.String[] tokens1; protected internal System.String[] tokens2; public TestTeeTokenFilter(System.String s):base(s) { } public TestTeeTokenFilter() { } [SetUp] public override void SetUp() { base.SetUp(); tokens1 = new System.String[]{"The", "quick", "Burgundy", "Fox", "jumped", "over", "the", "lazy", "Red", "Dogs"}; tokens2 = new System.String[]{"The", "Lazy", "Dogs", "should", "stay", "on", "the", "porch"}; buffer1 = new System.Text.StringBuilder(); for (int i = 0; i < tokens1.Length; i++) { buffer1.Append(tokens1[i]).Append(' '); } buffer2 = new System.Text.StringBuilder(); for (int i = 0; i < tokens2.Length; i++) { buffer2.Append(tokens2[i]).Append(' '); } } [Test] public virtual void Test() { SinkTokenizer sink1 = new AnonymousClassSinkTokenizer(this, null); TokenStream source = new TeeTokenFilter(new WhitespaceTokenizer(new System.IO.StringReader(buffer1.ToString())), sink1); int i = 0; Token reusableToken = new Token(); for (Token nextToken = source.Next(reusableToken); nextToken != null; nextToken = source.Next(reusableToken)) { Assert.IsTrue(nextToken.Term().Equals(tokens1[i]) == true, nextToken.Term() + " is not equal to " + tokens1[i]); i++; } Assert.IsTrue(i == tokens1.Length, i + " does not equal: " + tokens1.Length); Assert.IsTrue(sink1.GetTokens().Count == 2, "sink1 Size: " + sink1.GetTokens().Count + " is not: " + 2); i = 0; for (Token token = sink1.Next(reusableToken); token != null; token = sink1.Next(reusableToken)) { Assert.IsTrue(token.Term().ToUpper().Equals("The".ToUpper()) == true, token.Term() + " is not equal to " + "The"); i++; } Assert.IsTrue(i == sink1.GetTokens().Count, i + " does not equal: " + sink1.GetTokens().Count); } [Test] public virtual void TestMultipleSources() { SinkTokenizer theDetector = new AnonymousClassSinkTokenizer1(this, null); SinkTokenizer dogDetector = new AnonymousClassSinkTokenizer2(this, null); TokenStream source1 = new CachingTokenFilter(new TeeTokenFilter(new TeeTokenFilter(new WhitespaceTokenizer(new System.IO.StringReader(buffer1.ToString())), theDetector), dogDetector)); TokenStream source2 = new TeeTokenFilter(new TeeTokenFilter(new WhitespaceTokenizer(new System.IO.StringReader(buffer2.ToString())), theDetector), dogDetector); int i = 0; Token reusableToken = new Token(); for (Token nextToken = source1.Next(reusableToken); nextToken != null; nextToken = source1.Next(reusableToken)) { Assert.IsTrue(nextToken.Term().Equals(tokens1[i]) == true, nextToken.Term() + " is not equal to " + tokens1[i]); i++; } Assert.IsTrue(i == tokens1.Length, i + " does not equal: " + tokens1.Length); Assert.IsTrue(theDetector.GetTokens().Count == 2, "theDetector Size: " + theDetector.GetTokens().Count + " is not: " + 2); Assert.IsTrue(dogDetector.GetTokens().Count == 1, "dogDetector Size: " + dogDetector.GetTokens().Count + " is not: " + 1); i = 0; for (Token nextToken = source2.Next(reusableToken); nextToken != null; nextToken = source2.Next(reusableToken)) { Assert.IsTrue(nextToken.Term().Equals(tokens2[i]) == true, nextToken.Term() + " is not equal to " + tokens2[i]); i++; } Assert.IsTrue(i == tokens2.Length, i + " does not equal: " + tokens2.Length); Assert.IsTrue(theDetector.GetTokens().Count == 4, "theDetector Size: " + theDetector.GetTokens().Count + " is not: " + 4); Assert.IsTrue(dogDetector.GetTokens().Count == 2, "dogDetector Size: " + dogDetector.GetTokens().Count + " is not: " + 2); i = 0; for (Token nextToken = theDetector.Next(reusableToken); nextToken != null; nextToken = theDetector.Next(reusableToken)) { Assert.IsTrue(nextToken.Term().ToUpper().Equals("The".ToUpper()) == true, nextToken.Term() + " is not equal to " + "The"); i++; } Assert.IsTrue(i == theDetector.GetTokens().Count, i + " does not equal: " + theDetector.GetTokens().Count); i = 0; for (Token nextToken = dogDetector.Next(reusableToken); nextToken != null; nextToken = dogDetector.Next(reusableToken)) { Assert.IsTrue(nextToken.Term().ToUpper().Equals("Dogs".ToUpper()) == true, nextToken.Term() + " is not equal to " + "Dogs"); i++; } Assert.IsTrue(i == dogDetector.GetTokens().Count, i + " does not equal: " + dogDetector.GetTokens().Count); source1.Reset(); TokenStream lowerCasing = new LowerCaseFilter(source1); i = 0; for (Token nextToken = lowerCasing.Next(reusableToken); nextToken != null; nextToken = lowerCasing.Next(reusableToken)) { Assert.IsTrue(nextToken.Term().Equals(tokens1[i].ToLower()) == true, nextToken.Term() + " is not equal to " + tokens1[i].ToLower()); i++; } Assert.IsTrue(i == tokens1.Length, i + " does not equal: " + tokens1.Length); } /// <summary> Not an explicit test, just useful to print out some info on performance /// /// </summary> /// <throws> Exception </throws> public virtual void Performance() { int[] tokCount = new int[]{100, 500, 1000, 2000, 5000, 10000}; int[] modCounts = new int[]{1, 2, 5, 10, 20, 50, 100, 200, 500}; for (int k = 0; k < tokCount.Length; k++) { System.Text.StringBuilder buffer = new System.Text.StringBuilder(); System.Console.Out.WriteLine("-----Tokens: " + tokCount[k] + "-----"); for (int i = 0; i < tokCount[k]; i++) { buffer.Append(English.IntToEnglish(i).ToUpper()).Append(' '); } //make sure we produce the same tokens ModuloSinkTokenizer sink = new ModuloSinkTokenizer(this, tokCount[k], 100); Token reusableToken = new Token(); TokenStream stream = new TeeTokenFilter(new StandardFilter(new StandardTokenizer(new System.IO.StringReader(buffer.ToString()))), sink); while (stream.Next(reusableToken) != null) { } stream = new ModuloTokenFilter(this, new StandardFilter(new StandardTokenizer(new System.IO.StringReader(buffer.ToString()))), 100); System.Collections.IList tmp = new System.Collections.ArrayList(); for (Token nextToken = stream.Next(reusableToken); nextToken != null; nextToken = stream.Next(reusableToken)) { tmp.Add(nextToken.Clone()); } System.Collections.IList sinkList = sink.GetTokens(); Assert.IsTrue(tmp.Count == sinkList.Count, "tmp Size: " + tmp.Count + " is not: " + sinkList.Count); for (int i = 0; i < tmp.Count; i++) { Token tfTok = (Token) tmp[i]; Token sinkTok = (Token) sinkList[i]; Assert.IsTrue(tfTok.Term().Equals(sinkTok.Term()) == true, tfTok.Term() + " is not equal to " + sinkTok.Term() + " at token: " + i); } //simulate two fields, each being analyzed once, for 20 documents for (int j = 0; j < modCounts.Length; j++) { int tfPos = 0; long start = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond); for (int i = 0; i < 20; i++) { stream = new StandardFilter(new StandardTokenizer(new System.IO.StringReader(buffer.ToString()))); for (Token nextToken = stream.Next(reusableToken); nextToken != null; nextToken = stream.Next(reusableToken)) { tfPos += nextToken.GetPositionIncrement(); } stream = new ModuloTokenFilter(this, new StandardFilter(new StandardTokenizer(new System.IO.StringReader(buffer.ToString()))), modCounts[j]); for (Token nextToken = stream.Next(reusableToken); nextToken != null; nextToken = stream.Next(reusableToken)) { tfPos += nextToken.GetPositionIncrement(); } } long finish = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond); System.Console.Out.WriteLine("ModCount: " + modCounts[j] + " Two fields took " + (finish - start) + " ms"); int sinkPos = 0; //simulate one field with one sink start = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond); for (int i = 0; i < 20; i++) { sink = new ModuloSinkTokenizer(this, tokCount[k], modCounts[j]); stream = new TeeTokenFilter(new StandardFilter(new StandardTokenizer(new System.IO.StringReader(buffer.ToString()))), sink); for (Token nextToken = stream.Next(reusableToken); nextToken != null; nextToken = stream.Next(reusableToken)) { sinkPos += nextToken.GetPositionIncrement(); } //System.out.println("Modulo--------"); stream = sink; for (Token nextToken = stream.Next(reusableToken); nextToken != null; nextToken = stream.Next(reusableToken)) { sinkPos += nextToken.GetPositionIncrement(); } } finish = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond); System.Console.Out.WriteLine("ModCount: " + modCounts[j] + " Tee fields took " + (finish - start) + " ms"); Assert.IsTrue(sinkPos == tfPos, sinkPos + " does not equal: " + tfPos); } System.Console.Out.WriteLine("- End Tokens: " + tokCount[k] + "-----"); } } internal class ModuloTokenFilter:TokenFilter { private void InitBlock(TestTeeTokenFilter enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestTeeTokenFilter enclosingInstance; public TestTeeTokenFilter Enclosing_Instance { get { return enclosingInstance; } } internal int modCount; internal ModuloTokenFilter(TestTeeTokenFilter enclosingInstance, TokenStream input, int mc):base(input) { InitBlock(enclosingInstance); modCount = mc; } internal int count = 0; //return every 100 tokens public override Token Next(Token reusableToken) { Token nextToken = null; for (nextToken = input.Next(reusableToken); nextToken != null && count % modCount != 0; nextToken = input.Next(reusableToken)) { count++; } count++; return nextToken; } } internal class ModuloSinkTokenizer:SinkTokenizer { private void InitBlock(TestTeeTokenFilter enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestTeeTokenFilter enclosingInstance; public TestTeeTokenFilter Enclosing_Instance { get { return enclosingInstance; } } internal int count = 0; internal int modCount; internal ModuloSinkTokenizer(TestTeeTokenFilter enclosingInstance, int numToks, int mc) { InitBlock(enclosingInstance); modCount = mc; lst = new System.Collections.ArrayList(numToks % mc); } public override void Add(Token t) { if (t != null && count % modCount == 0) { base.Add(t); } count++; } } } }
// 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.Text; using System.Threading; using System.Globalization; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; namespace System.Globalization { internal partial class FormatProvider { /* Customized format patterns: P.S. Format in the table below is the internal number format used to display the pattern. Patterns Format Description Example ========= ========== ===================================== ======== "h" "0" hour (12-hour clock)w/o leading zero 3 "hh" "00" hour (12-hour clock)with leading zero 03 "hh*" "00" hour (12-hour clock)with leading zero 03 "H" "0" hour (24-hour clock)w/o leading zero 8 "HH" "00" hour (24-hour clock)with leading zero 08 "HH*" "00" hour (24-hour clock) 08 "m" "0" minute w/o leading zero "mm" "00" minute with leading zero "mm*" "00" minute with leading zero "s" "0" second w/o leading zero "ss" "00" second with leading zero "ss*" "00" second with leading zero "f" "0" second fraction (1 digit) "ff" "00" second fraction (2 digit) "fff" "000" second fraction (3 digit) "ffff" "0000" second fraction (4 digit) "fffff" "00000" second fraction (5 digit) "ffffff" "000000" second fraction (6 digit) "fffffff" "0000000" second fraction (7 digit) "F" "0" second fraction (up to 1 digit) "FF" "00" second fraction (up to 2 digit) "FFF" "000" second fraction (up to 3 digit) "FFFF" "0000" second fraction (up to 4 digit) "FFFFF" "00000" second fraction (up to 5 digit) "FFFFFF" "000000" second fraction (up to 6 digit) "FFFFFFF" "0000000" second fraction (up to 7 digit) "t" first character of AM/PM designator A "tt" AM/PM designator AM "tt*" AM/PM designator PM "d" "0" day w/o leading zero 1 "dd" "00" day with leading zero 01 "ddd" short weekday name (abbreviation) Mon "dddd" full weekday name Monday "dddd*" full weekday name Monday "M" "0" month w/o leading zero 2 "MM" "00" month with leading zero 02 "MMM" short month name (abbreviation) Feb "MMMM" full month name Febuary "MMMM*" full month name Febuary "y" "0" two digit year (year % 100) w/o leading zero 0 "yy" "00" two digit year (year % 100) with leading zero 00 "yyy" "D3" year 2000 "yyyy" "D4" year 2000 "yyyyy" "D5" year 2000 ... "z" "+0;-0" timezone offset w/o leading zero -8 "zz" "+00;-00" timezone offset with leading zero -08 "zzz" "+00;-00" for hour offset, "00" for minute offset full timezone offset -07:30 "zzz*" "+00;-00" for hour offset, "00" for minute offset full timezone offset -08:00 "K" -Local "zzz", e.g. -08:00 -Utc "'Z'", representing UTC -Unspecified "" -DateTimeOffset "zzzzz" e.g -07:30:15 "g*" the current era name A.D. ":" time separator : -- DEPRECATED - Insert separator directly into pattern (eg: "H.mm.ss") "/" date separator /-- DEPRECATED - Insert separator directly into pattern (eg: "M-dd-yyyy") "'" quoted string 'ABC' will insert ABC into the formatted string. '"' quoted string "ABC" will insert ABC into the formatted string. "%" used to quote a single pattern characters E.g.The format character "%y" is to print two digit year. "\" escaped character E.g. '\d' insert the character 'd' into the format string. other characters insert the character into the format string. Pre-defined format characters: (U) to indicate Universal time is used. (G) to indicate Gregorian calendar is used. Format Description Real format Example ========= ================================= ====================== ======================= "d" short date culture-specific 10/31/1999 "D" long data culture-specific Sunday, October 31, 1999 "f" full date (long date + short time) culture-specific Sunday, October 31, 1999 2:00 AM "F" full date (long date + long time) culture-specific Sunday, October 31, 1999 2:00:00 AM "g" general date (short date + short time) culture-specific 10/31/1999 2:00 AM "G" general date (short date + long time) culture-specific 10/31/1999 2:00:00 AM "m"/"M" Month/Day date culture-specific October 31 (G) "o"/"O" Round Trip XML "yyyy-MM-ddTHH:mm:ss.fffffffK" 1999-10-31 02:00:00.0000000Z (G) "r"/"R" RFC 1123 date, "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'" Sun, 31 Oct 1999 10:00:00 GMT (G) "s" Sortable format, based on ISO 8601. "yyyy-MM-dd'T'HH:mm:ss" 1999-10-31T02:00:00 ('T' for local time) "t" short time culture-specific 2:00 AM "T" long time culture-specific 2:00:00 AM (G) "u" Universal time with sortable format, "yyyy'-'MM'-'dd HH':'mm':'ss'Z'" 1999-10-31 10:00:00Z based on ISO 8601. (U) "U" Universal time with full culture-specific Sunday, October 31, 1999 10:00:00 AM (long date + long time) format "y"/"Y" Year/Month day culture-specific October, 1999 */ //This class contains only static members and does not require the serializable attribute. internal static class DateTimeFormat { internal const int MaxSecondsFractionDigits = 7; internal static readonly TimeSpan NullOffset = TimeSpan.MinValue; internal static char[] allStandardFormats = { 'd', 'D', 'f', 'F', 'g', 'G', 'm', 'M', 'o', 'O', 'r', 'R', 's', 't', 'T', 'u', 'U', 'y', 'Y', }; private const int DEFAULT_ALL_DATETIMES_SIZE = 132; internal static readonly DateTimeFormatInfo InvariantFormatInfo = CultureInfo.InvariantCulture.DateTimeFormat; internal static readonly string[] InvariantAbbreviatedMonthNames = InvariantFormatInfo.AbbreviatedMonthNames; internal static readonly string[] InvariantAbbreviatedDayNames = InvariantFormatInfo.AbbreviatedDayNames; internal const string Gmt = "GMT"; internal static String[] fixedNumberFormats = new String[] { "0", "00", "000", "0000", "00000", "000000", "0000000", }; //////////////////////////////////////////////////////////////////////////// // // Format the positive integer value to a string and perfix with assigned // length of leading zero. // // Parameters: // value: The value to format // len: The maximum length for leading zero. // If the digits of the value is greater than len, no leading zero is added. // // Notes: // The function can format to Int32.MaxValue. // //////////////////////////////////////////////////////////////////////////// internal static void FormatDigits(StringBuilder outputBuffer, int value, int len) { FormatDigits(outputBuffer, value, len, false); } // auto-generated internal static unsafe void FormatDigits(StringBuilder outputBuffer, int value, int len, bool overrideLengthLimit) { // Limit the use of this function to be two-digits, so that we have the same behavior // as RTM bits. if (!overrideLengthLimit && len > 2) { len = 2; } int index; int digits; char[] charBuff = new char[16]; fixed (char* buffer = &charBuff[0]) { char* p = buffer + 16; int n = value; do { *--p = (char)(n % 10 + '0'); n /= 10; } while ((n != 0) && (p > buffer)); digits = (int)(buffer + 16 - p); //If the repeat count is greater than 0, we're trying //to emulate the "00" format, so we have to prepend //a zero if the string only has one character. while ((digits < len) && (p > buffer)) { *--p = '0'; digits++; } index = (int)(p - buffer); } outputBuffer.Append(charBuff, index, digits); } private static void HebrewFormatDigits(StringBuilder outputBuffer, int digits) { outputBuffer.Append(HebrewNumber.ToString(digits)); } internal static int ParseRepeatPattern(String format, int pos, char patternChar) { int len = format.Length; int index = pos + 1; while ((index < len) && (format[index] == patternChar)) { index++; } return (index - pos); } private static String FormatDayOfWeek(int dayOfWeek, int repeat, DateTimeFormatInfo dtfi) { if (repeat == 3) { return (dtfi.GetAbbreviatedDayName((DayOfWeek)dayOfWeek)); } // Call dtfi.GetDayName() here, instead of accessing DayNames property, because we don't // want a clone of DayNames, which will hurt perf. return (dtfi.GetDayName((DayOfWeek)dayOfWeek)); } private static String FormatMonth(int month, int repeatCount, DateTimeFormatInfo dtfi) { if (repeatCount == 3) { return (dtfi.GetAbbreviatedMonthName(month)); } // Call GetMonthName() here, instead of accessing MonthNames property, because we don't // want a clone of MonthNames, which will hurt perf. return (dtfi.GetMonthName(month)); } // // FormatHebrewMonthName // // Action: Return the Hebrew month name for the specified DateTime. // Returns: The month name string for the specified DateTime. // Arguments: // time the time to format // month The month is the value of HebrewCalendar.GetMonth(time). // repeat Return abbreviated month name if repeat=3, or full month name if repeat=4 // dtfi The DateTimeFormatInfo which uses the Hebrew calendars as its calendar. // Exceptions: None. // /* Note: If DTFI is using Hebrew calendar, GetMonthName()/GetAbbreviatedMonthName() will return month names like this: 1 Hebrew 1st Month 2 Hebrew 2nd Month .. ... 6 Hebrew 6th Month 7 Hebrew 6th Month II (used only in a leap year) 8 Hebrew 7th Month 9 Hebrew 8th Month 10 Hebrew 9th Month 11 Hebrew 10th Month 12 Hebrew 11th Month 13 Hebrew 12th Month Therefore, if we are in a regular year, we have to increment the month name if moth is greater or eqaul to 7. */ private static String FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi) { if (dtfi.Calendar.IsLeapYear(dtfi.Calendar.GetYear(time))) { // This month is in a leap year return (dtfi.internalGetMonthName(month, MonthNameStyles.LeapYear, (repeatCount == 3))); } // This is in a regular year. if (month >= 7) { month++; } if (repeatCount == 3) { return (dtfi.GetAbbreviatedMonthName(month)); } return (dtfi.GetMonthName(month)); } // // The pos should point to a quote character. This method will // append to the result StringBuilder the string encloed by the quote character. // internal static int ParseQuoteString(String format, int pos, StringBuilder result) { // // NOTE : pos will be the index of the quote character in the 'format' string. // int formatLen = format.Length; int beginPos = pos; char quoteChar = format[pos++]; // Get the character used to quote the following string. bool foundQuote = false; while (pos < formatLen) { char ch = format[pos++]; if (ch == quoteChar) { foundQuote = true; break; } else if (ch == '\\') { // The following are used to support escaped character. // Escaped character is also supported in the quoted string. // Therefore, someone can use a format like "'minute:' mm\"" to display: // minute: 45" // because the second double quote is escaped. if (pos < formatLen) { result.Append(format[pos++]); } else { // // This means that '\' is at the end of the formatting string. // throw new FormatException(SR.Format_InvalidString); } } else { result.Append(ch); } } if (!foundQuote) { // Here we can't find the matching quote. throw new FormatException( String.Format( CultureInfo.CurrentCulture, SR.Format_BadQuote, quoteChar)); } // // Return the character count including the begin/end quote characters and enclosed string. // return (pos - beginPos); } // // Get the next character at the index of 'pos' in the 'format' string. // Return value of -1 means 'pos' is already at the end of the 'format' string. // Otherwise, return value is the int value of the next character. // internal static int ParseNextChar(String format, int pos) { if (pos >= format.Length - 1) { return (-1); } return ((int)format[pos + 1]); } // // IsUseGenitiveForm // // Actions: Check the format to see if we should use genitive month in the formatting. // Starting at the position (index) in the (format) string, look back and look ahead to // see if there is "d" or "dd". In the case like "d MMMM" or "MMMM dd", we can use // genitive form. Genitive form is not used if there is more than two "d". // Arguments: // format The format string to be scanned. // index Where we should start the scanning. This is generally where "M" starts. // tokenLen The len of the current pattern character. This indicates how many "M" that we have. // patternToMatch The pattern that we want to search. This generally uses "d" // private static bool IsUseGenitiveForm(String format, int index, int tokenLen, char patternToMatch) { int i; int repeat = 0; // // Look back to see if we can find "d" or "ddd" // // Find first "d". for (i = index - 1; i >= 0 && format[i] != patternToMatch; i--) { /*Do nothing here */ }; if (i >= 0) { // Find a "d", so look back to see how many "d" that we can find. while (--i >= 0 && format[i] == patternToMatch) { repeat++; } // // repeat == 0 means that we have one (patternToMatch) // repeat == 1 means that we have two (patternToMatch) // if (repeat <= 1) { return (true); } // Note that we can't just stop here. We may find "ddd" while looking back, and we have to look // ahead to see if there is "d" or "dd". } // // If we can't find "d" or "dd" by looking back, try look ahead. // // Find first "d" for (i = index + tokenLen; i < format.Length && format[i] != patternToMatch; i++) { /* Do nothing here */ }; if (i < format.Length) { repeat = 0; // Find a "d", so contine the walk to see how may "d" that we can find. while (++i < format.Length && format[i] == patternToMatch) { repeat++; } // // repeat == 0 means that we have one (patternToMatch) // repeat == 1 means that we have two (patternToMatch) // if (repeat <= 1) { return (true); } } return (false); } // // FormatCustomized // // Actions: Format the DateTime instance using the specified format. // private static String FormatCustomized(DateTime dateTime, String format, DateTimeFormatInfo dtfi, TimeSpan offset) { Calendar cal = dtfi.Calendar; StringBuilder result = StringBuilderCache.Acquire(InternalGloablizationHelper.StringBuilderDefaultCapacity); // This is a flag to indicate if we are format the dates using Hebrew calendar. bool isHebrewCalendar = (cal.ID == CalendarId.HEBREW); // This is a flag to indicate if we are formating hour/minute/second only. bool bTimeOnly = true; int i = 0; int tokenLen, hour12; while (i < format.Length) { char ch = format[i]; int nextChar; switch (ch) { case 'g': tokenLen = ParseRepeatPattern(format, i, ch); result.Append(dtfi.GetEraName(cal.GetEra(dateTime))); break; case 'h': tokenLen = ParseRepeatPattern(format, i, ch); hour12 = dateTime.Hour % 12; if (hour12 == 0) { hour12 = 12; } FormatDigits(result, hour12, tokenLen); break; case 'H': tokenLen = ParseRepeatPattern(format, i, ch); FormatDigits(result, dateTime.Hour, tokenLen); break; case 'm': tokenLen = ParseRepeatPattern(format, i, ch); FormatDigits(result, dateTime.Minute, tokenLen); break; case 's': tokenLen = ParseRepeatPattern(format, i, ch); FormatDigits(result, dateTime.Second, tokenLen); break; case 'f': case 'F': tokenLen = ParseRepeatPattern(format, i, ch); if (tokenLen <= MaxSecondsFractionDigits) { long fraction = (dateTime.Ticks % Calendar.TicksPerSecond); fraction = fraction / (long)Math.Pow(10, 7 - tokenLen); if (ch == 'f') { result.Append(((int)fraction).ToString(fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture)); } else { int effectiveDigits = tokenLen; while (effectiveDigits > 0) { if (fraction % 10 == 0) { fraction = fraction / 10; effectiveDigits--; } else { break; } } if (effectiveDigits > 0) { result.Append(((int)fraction).ToString(fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture)); } else { // No fraction to emit, so see if we should remove decimal also. if (result.Length > 0 && result[result.Length - 1] == '.') { result.Remove(result.Length - 1, 1); } } } } else { throw new FormatException(SR.Format_InvalidString); } break; case 't': tokenLen = ParseRepeatPattern(format, i, ch); if (tokenLen == 1) { if (dateTime.Hour < 12) { if (dtfi.AMDesignator.Length >= 1) { result.Append(dtfi.AMDesignator[0]); } } else { if (dtfi.PMDesignator.Length >= 1) { result.Append(dtfi.PMDesignator[0]); } } } else { result.Append((dateTime.Hour < 12 ? dtfi.AMDesignator : dtfi.PMDesignator)); } break; case 'd': // // tokenLen == 1 : Day of month as digits with no leading zero. // tokenLen == 2 : Day of month as digits with leading zero for single-digit months. // tokenLen == 3 : Day of week as a three-leter abbreviation. // tokenLen >= 4 : Day of week as its full name. // tokenLen = ParseRepeatPattern(format, i, ch); if (tokenLen <= 2) { int day = cal.GetDayOfMonth(dateTime); if (isHebrewCalendar) { // For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values. HebrewFormatDigits(result, day); } else { FormatDigits(result, day, tokenLen); } } else { int dayOfWeek = (int)cal.GetDayOfWeek(dateTime); result.Append(FormatDayOfWeek(dayOfWeek, tokenLen, dtfi)); } bTimeOnly = false; break; case 'M': // // tokenLen == 1 : Month as digits with no leading zero. // tokenLen == 2 : Month as digits with leading zero for single-digit months. // tokenLen == 3 : Month as a three-letter abbreviation. // tokenLen >= 4 : Month as its full name. // tokenLen = ParseRepeatPattern(format, i, ch); int month = cal.GetMonth(dateTime); if (tokenLen <= 2) { if (isHebrewCalendar) { // For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values. HebrewFormatDigits(result, month); } else { FormatDigits(result, month, tokenLen); } } else { if (isHebrewCalendar) { result.Append(FormatHebrewMonthName(dateTime, month, tokenLen, dtfi)); } else { if ((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0 && tokenLen >= 4) { result.Append( dtfi.internalGetMonthName( month, IsUseGenitiveForm(format, i, tokenLen, 'd') ? MonthNameStyles.Genitive : MonthNameStyles.Regular, false)); } else { result.Append(FormatMonth(month, tokenLen, dtfi)); } } } bTimeOnly = false; break; case 'y': // Notes about OS behavior: // y: Always print (year % 100). No leading zero. // yy: Always print (year % 100) with leading zero. // yyy/yyyy/yyyyy/... : Print year value. No leading zero. int year = cal.GetYear(dateTime); tokenLen = ParseRepeatPattern(format, i, ch); if (dtfi.HasForceTwoDigitYears) { FormatDigits(result, year, tokenLen <= 2 ? tokenLen : 2); } else if (cal.ID == CalendarId.HEBREW) { HebrewFormatDigits(result, year); } else { if (tokenLen <= 2) { FormatDigits(result, year % 100, tokenLen); } else { String fmtPattern = "D" + tokenLen.ToString(); result.Append(year.ToString(fmtPattern, CultureInfo.InvariantCulture)); } } bTimeOnly = false; break; case 'z': tokenLen = ParseRepeatPattern(format, i, ch); FormatCustomizedTimeZone(dateTime, offset, format, tokenLen, bTimeOnly, result); break; case 'K': tokenLen = 1; FormatCustomizedRoundripTimeZone(dateTime, offset, result); break; case ':': result.Append(dtfi.TimeSeparator); tokenLen = 1; break; case '/': result.Append(dtfi.DateSeparator); tokenLen = 1; break; case '\'': case '\"': tokenLen = ParseQuoteString(format, i, result); break; case '%': // Optional format character. // For example, format string "%d" will print day of month // without leading zero. Most of the cases, "%" can be ignored. nextChar = ParseNextChar(format, i); // nextChar will be -1 if we already reach the end of the format string. // Besides, we will not allow "%%" appear in the pattern. if (nextChar >= 0 && nextChar != (int)'%') { result.Append(FormatCustomized(dateTime, ((char)nextChar).ToString(), dtfi, offset)); tokenLen = 2; } else { // // This means that '%' is at the end of the format string or // "%%" appears in the format string. // throw new FormatException(SR.Format_InvalidString); } break; case '\\': // Escaped character. Can be used to insert character into the format string. // For exmple, "\d" will insert the character 'd' into the string. // // NOTENOTE : we can remove this format character if we enforce the enforced quote // character rule. // That is, we ask everyone to use single quote or double quote to insert characters, // then we can remove this character. // nextChar = ParseNextChar(format, i); if (nextChar >= 0) { result.Append(((char)nextChar)); tokenLen = 2; } else { // // This means that '\' is at the end of the formatting string. // throw new FormatException(SR.Format_InvalidString); } break; default: // NOTENOTE : we can remove this rule if we enforce the enforced quote // character rule. // That is, if we ask everyone to use single quote or double quote to insert characters, // then we can remove this default block. result.Append(ch); tokenLen = 1; break; } i += tokenLen; } return StringBuilderCache.GetStringAndRelease(result); } // output the 'z' famliy of formats, which output a the offset from UTC, e.g. "-07:30" private static void FormatCustomizedTimeZone(DateTime dateTime, TimeSpan offset, String format, Int32 tokenLen, Boolean timeOnly, StringBuilder result) { // See if the instance already has an offset Boolean dateTimeFormat = (offset == NullOffset); if (dateTimeFormat) { // No offset. The instance is a DateTime and the output should be the local time zone if (timeOnly && dateTime.Ticks < Calendar.TicksPerDay) { // For time only format and a time only input, the time offset on 0001/01/01 is less // accurate than the system's current offset because of daylight saving time. offset = TimeZoneInfo.Local.GetUtcOffset(DateTime.Now); } else if (dateTime.Kind == DateTimeKind.Utc) { offset = TimeSpan.Zero; } else { offset = TimeZoneInfo.Local.GetUtcOffset(dateTime); } } if (offset >= TimeSpan.Zero) { result.Append('+'); } else { result.Append('-'); // get a positive offset, so that you don't need a separate code path for the negative numbers. offset = offset.Negate(); } if (tokenLen <= 1) { // 'z' format e.g "-7" result.AppendFormat(CultureInfo.InvariantCulture, "{0:0}", offset.Hours); } else { // 'zz' or longer format e.g "-07" result.AppendFormat(CultureInfo.InvariantCulture, "{0:00}", offset.Hours); if (tokenLen >= 3) { // 'zzz*' or longer format e.g "-07:30" result.AppendFormat(CultureInfo.InvariantCulture, ":{0:00}", offset.Minutes); } } } // output the 'K' format, which is for round-tripping the data private static void FormatCustomizedRoundripTimeZone(DateTime dateTime, TimeSpan offset, StringBuilder result) { // The objective of this format is to round trip the data in the type // For DateTime it should round-trip the Kind value and preserve the time zone. // DateTimeOffset instance, it should do so by using the internal time zone. if (offset == NullOffset) { // source is a date time, so behavior depends on the kind. switch (dateTime.Kind) { case DateTimeKind.Local: // This should output the local offset, e.g. "-07:30" offset = TimeZoneInfo.Local.GetUtcOffset(dateTime); // fall through to shared time zone output code break; case DateTimeKind.Utc: // The 'Z' constant is a marker for a UTC date result.Append('Z'); return; default: // If the kind is unspecified, we output nothing here return; } } if (offset >= TimeSpan.Zero) { result.Append('+'); } else { result.Append('-'); // get a positive offset, so that you don't need a separate code path for the negative numbers. offset = offset.Negate(); } AppendNumber(result, offset.Hours, 2); result.Append(':'); AppendNumber(result, offset.Minutes, 2); } internal static String GetRealFormat(String format, DateTimeFormatInfo dtfi) { String realFormat = null; switch (format[0]) { case 'd': // Short Date realFormat = dtfi.ShortDatePattern; break; case 'D': // Long Date realFormat = dtfi.LongDatePattern; break; case 'f': // Full (long date + short time) realFormat = dtfi.LongDatePattern + " " + dtfi.ShortTimePattern; break; case 'F': // Full (long date + long time) realFormat = dtfi.FullDateTimePattern; break; case 'g': // General (short date + short time) realFormat = dtfi.GeneralShortTimePattern; break; case 'G': // General (short date + long time) realFormat = dtfi.GeneralLongTimePattern; break; case 'm': case 'M': // Month/Day Date realFormat = dtfi.MonthDayPattern; break; case 'o': case 'O': realFormat = DateTimeFormatInfo.RoundtripFormat; break; case 'r': case 'R': // RFC 1123 Standard realFormat = dtfi.RFC1123Pattern; break; case 's': // Sortable without Time Zone Info realFormat = dtfi.SortableDateTimePattern; break; case 't': // Short Time realFormat = dtfi.ShortTimePattern; break; case 'T': // Long Time realFormat = dtfi.LongTimePattern; break; case 'u': // Universal with Sortable format realFormat = dtfi.UniversalSortableDateTimePattern; break; case 'U': // Universal with Full (long date + long time) format realFormat = dtfi.FullDateTimePattern; break; case 'y': case 'Y': // Year/Month Date realFormat = dtfi.YearMonthPattern; break; default: throw new FormatException(SR.Format_InvalidString); } return (realFormat); } // Expand a pre-defined format string (like "D" for long date) to the real format that // we are going to use in the date time parsing. // This method also convert the dateTime if necessary (e.g. when the format is in Universal time), // and change dtfi if necessary (e.g. when the format should use invariant culture). // private static String ExpandPredefinedFormat(String format, ref DateTime dateTime, ref DateTimeFormatInfo dtfi, ref TimeSpan offset) { switch (format[0]) { case 'o': case 'O': // Round trip format dtfi = DateTimeFormatInfo.InvariantInfo; break; case 'r': case 'R': // RFC 1123 Standard if (offset != NullOffset) { // Convert to UTC invariants mean this will be in range dateTime = dateTime - offset; } else if (dateTime.Kind == DateTimeKind.Local) { InvalidFormatForLocal(format, dateTime); } dtfi = DateTimeFormatInfo.InvariantInfo; break; case 's': // Sortable without Time Zone Info dtfi = DateTimeFormatInfo.InvariantInfo; break; case 'u': // Universal time in sortable format. if (offset != NullOffset) { // Convert to UTC invariants mean this will be in range dateTime = dateTime - offset; } else if (dateTime.Kind == DateTimeKind.Local) { InvalidFormatForLocal(format, dateTime); } dtfi = DateTimeFormatInfo.InvariantInfo; break; case 'U': // Universal time in culture dependent format. if (offset != NullOffset) { // This format is not supported by DateTimeOffset throw new FormatException(SR.Format_InvalidString); } // Universal time is always in Greogrian calendar. // // Change the Calendar to be Gregorian Calendar. // dtfi = (DateTimeFormatInfo)dtfi.Clone(); if (dtfi.Calendar.GetType() != typeof(GregorianCalendar)) { dtfi.Calendar = GregorianCalendar.GetDefaultInstance(); } dateTime = dateTime.ToUniversalTime(); break; } format = GetRealFormat(format, dtfi); return (format); } internal static String Format(DateTime dateTime, String format, IFormatProvider dtfi) { return Format(dateTime, format, dtfi, NullOffset); } internal static String Format(DateTime dateTime, String format, IFormatProvider provider, TimeSpan offset) { DateTimeFormatInfo dtfi = provider == null ? DateTimeFormatInfo.CurrentInfo : DateTimeFormatInfo.GetInstance(provider); if (format == null || format.Length == 0) { Boolean timeOnlySpecialCase = false; if (dateTime.Ticks < Calendar.TicksPerDay) { // If the time is less than 1 day, consider it as time of day. // Just print out the short time format. // // This is a workaround for VB, since they use ticks less then one day to be // time of day. In cultures which use calendar other than Gregorian calendar, these // alternative calendar may not support ticks less than a day. // For example, Japanese calendar only supports date after 1868/9/8. // This will pose a problem when people in VB get the time of day, and use it // to call ToString(), which will use the general format (short date + long time). // Since Japanese calendar does not support Gregorian year 0001, an exception will be // thrown when we try to get the Japanese year for Gregorian year 0001. // Therefore, the workaround allows them to call ToString() for time of day from a DateTime by // formatting as ISO 8601 format. switch (dtfi.Calendar.ID) { case CalendarId.JAPAN: case CalendarId.TAIWAN: case CalendarId.HIJRI: case CalendarId.HEBREW: case CalendarId.JULIAN: case CalendarId.UMALQURA: case CalendarId.PERSIAN: timeOnlySpecialCase = true; dtfi = DateTimeFormatInfo.InvariantInfo; break; } } if (offset == NullOffset) { // Default DateTime.ToString case. if (timeOnlySpecialCase) { format = "s"; } else { format = "G"; } } else { // Default DateTimeOffset.ToString case. if (timeOnlySpecialCase) { format = DateTimeFormatInfo.RoundtripDateTimeUnfixed; } else { format = dtfi.DateTimeOffsetPattern; } } } if (format.Length == 1) { switch (format[0]) { case 'O': case 'o': return FastFormatRoundtrip(dateTime, offset); case 'R': case 'r': return FastFormatRfc1123(dateTime, offset, dtfi); } format = ExpandPredefinedFormat(format, ref dateTime, ref dtfi, ref offset); } return (FormatCustomized(dateTime, format, dtfi, offset)); } internal static string FastFormatRfc1123(DateTime dateTime, TimeSpan offset, DateTimeFormatInfo dtfi) { // ddd, dd MMM yyyy HH:mm:ss GMT const int Rfc1123FormatLength = 29; StringBuilder result = StringBuilderCache.Acquire(Rfc1123FormatLength); if (offset != NullOffset) { // Convert to UTC invariants dateTime = dateTime - offset; } result.Append(InvariantAbbreviatedDayNames[(int)dateTime.DayOfWeek]); result.Append(','); result.Append(' '); AppendNumber(result, dateTime.Day, 2); result.Append(' '); result.Append(InvariantAbbreviatedMonthNames[dateTime.Month - 1]); result.Append(' '); AppendNumber(result, dateTime.Year, 4); result.Append(' '); AppendHHmmssTimeOfDay(result, dateTime); result.Append(' '); result.Append(Gmt); return StringBuilderCache.GetStringAndRelease(result); } internal static string FastFormatRoundtrip(DateTime dateTime, TimeSpan offset) { // yyyy-MM-ddTHH:mm:ss.fffffffK const int roundTrimFormatLength = 28; StringBuilder result = StringBuilderCache.Acquire(roundTrimFormatLength); AppendNumber(result, dateTime.Year, 4); result.Append('-'); AppendNumber(result, dateTime.Month, 2); result.Append('-'); AppendNumber(result, dateTime.Day, 2); result.Append('T'); AppendHHmmssTimeOfDay(result, dateTime); result.Append('.'); long fraction = dateTime.Ticks % TimeSpan.TicksPerSecond; AppendNumber(result, fraction, 7); FormatCustomizedRoundripTimeZone(dateTime, offset, result); return StringBuilderCache.GetStringAndRelease(result); } private static void AppendHHmmssTimeOfDay(StringBuilder result, DateTime dateTime) { // HH:mm:ss AppendNumber(result, dateTime.Hour, 2); result.Append(':'); AppendNumber(result, dateTime.Minute, 2); result.Append(':'); AppendNumber(result, dateTime.Second, 2); } internal static void AppendNumber(StringBuilder builder, long val, int digits) { for (int i = 0; i < digits; i++) { builder.Append('0'); } int index = 1; while (val > 0 && index <= digits) { builder[builder.Length - index] = (char)('0' + (val % 10)); val = val / 10; index++; } Debug.Assert(val == 0, "DateTimeFormat.AppendNumber(): digits less than size of val"); } // This is a placeholder for an MDA to detect when the user is using a // local DateTime with a format that will be interpreted as UTC. internal static void InvalidFormatForLocal(String format, DateTime dateTime) { } internal static String[] GetAllDateTimes(DateTime dateTime, char format, IFormatProvider provider) { DateTimeFormatInfo dtfi = provider == null ? DateTimeFormatInfo.CurrentInfo : DateTimeFormatInfo.GetInstance(provider); String[] allFormats = null; String[] results = null; switch (format) { case 'd': case 'D': case 'f': case 'F': case 'g': case 'G': case 'm': case 'M': case 't': case 'T': case 'y': case 'Y': allFormats = dtfi.GetAllDateTimePatterns(format); results = new String[allFormats.Length]; for (int i = 0; i < allFormats.Length; i++) { results[i] = Format(dateTime, allFormats[i], dtfi); } break; case 'U': DateTime universalTime = dateTime.ToUniversalTime(); allFormats = dtfi.GetAllDateTimePatterns(format); results = new String[allFormats.Length]; for (int i = 0; i < allFormats.Length; i++) { results[i] = Format(universalTime, allFormats[i], dtfi); } break; // // The following ones are special cases because these patterns are read-only in // DateTimeFormatInfo. // case 'r': case 'R': case 'o': case 'O': case 's': case 'u': results = new String[] { Format(dateTime, new String(format, 1), dtfi) }; break; default: throw new FormatException(SR.Format_InvalidString); } return (results); } internal static String[] GetAllDateTimes(DateTime dateTime, IFormatProvider dtfi) { LowLevelList<String> results = new LowLevelList<String>(DEFAULT_ALL_DATETIMES_SIZE); for (int i = 0; i < allStandardFormats.Length; i++) { String[] strings = GetAllDateTimes(dateTime, allStandardFormats[i], dtfi); for (int j = 0; j < strings.Length; j++) { results.Add(strings[j]); } } String[] value = new String[results.Count]; results.CopyTo(0, value, 0, results.Count); return (value); } } } }
// 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 Microsoft.Win32.SafeHandles; using System; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Runtime.InteropServices; using Internals = System.Net.Internals; internal static partial class Interop { internal static partial class IpHlpApi { // TODO: #3562 - Replace names with the ones from the Windows SDK. [Flags] internal enum AdapterFlags { DnsEnabled = 0x01, RegisterAdapterSuffix = 0x02, DhcpEnabled = 0x04, ReceiveOnly = 0x08, NoMulticast = 0x10, Ipv6OtherStatefulConfig = 0x20, NetBiosOverTcp = 0x40, IPv4Enabled = 0x80, IPv6Enabled = 0x100, IPv6ManagedAddressConfigurationSupported = 0x200, } [Flags] internal enum AdapterAddressFlags { DnsEligible = 0x1, Transient = 0x2 } [Flags] internal enum GetAdaptersAddressesFlags { SkipUnicast = 0x0001, SkipAnycast = 0x0002, SkipMulticast = 0x0004, SkipDnsServer = 0x0008, IncludePrefix = 0x0010, SkipFriendlyName = 0x0020, IncludeWins = 0x0040, IncludeGateways = 0x0080, IncludeAllInterfaces = 0x0100, IncludeAllCompartments = 0x0200, IncludeTunnelBindingOrder = 0x0400, } [StructLayout(LayoutKind.Sequential)] internal struct IpSocketAddress { internal IntPtr address; internal int addressLength; internal IPAddress MarshalIPAddress() { // Determine the address family used to create the IPAddress. AddressFamily family = (addressLength > Internals.SocketAddress.IPv4AddressSize) ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork; Internals.SocketAddress sockAddress = new Internals.SocketAddress(family, addressLength); Marshal.Copy(address, sockAddress.Buffer, 0, addressLength); return sockAddress.GetIPAddress(); } } // IP_ADAPTER_ANYCAST_ADDRESS // IP_ADAPTER_MULTICAST_ADDRESS // IP_ADAPTER_DNS_SERVER_ADDRESS // IP_ADAPTER_WINS_SERVER_ADDRESS // IP_ADAPTER_GATEWAY_ADDRESS [StructLayout(LayoutKind.Sequential)] internal struct IpAdapterAddress { internal uint length; internal AdapterAddressFlags flags; internal IntPtr next; internal IpSocketAddress address; internal static InternalIPAddressCollection MarshalIpAddressCollection(IntPtr ptr) { InternalIPAddressCollection addressList = new InternalIPAddressCollection(); while (ptr != IntPtr.Zero) { IpAdapterAddress addressStructure = Marshal.PtrToStructure<IpAdapterAddress>(ptr); IPAddress address = addressStructure.address.MarshalIPAddress(); addressList.InternalAdd(address); ptr = addressStructure.next; } return addressList; } internal static IPAddressInformationCollection MarshalIpAddressInformationCollection(IntPtr ptr) { IPAddressInformationCollection addressList = new IPAddressInformationCollection(); while (ptr != IntPtr.Zero) { IpAdapterAddress addressStructure = Marshal.PtrToStructure<IpAdapterAddress>(ptr); IPAddress address = addressStructure.address.MarshalIPAddress(); addressList.InternalAdd(new SystemIPAddressInformation(address, addressStructure.flags)); ptr = addressStructure.next; } return addressList; } } [StructLayout(LayoutKind.Sequential)] internal struct IpAdapterUnicastAddress { internal uint length; internal AdapterAddressFlags flags; internal IntPtr next; internal IpSocketAddress address; internal PrefixOrigin prefixOrigin; internal SuffixOrigin suffixOrigin; internal DuplicateAddressDetectionState dadState; internal uint validLifetime; internal uint preferredLifetime; internal uint leaseLifetime; internal byte prefixLength; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct IpAdapterAddresses { internal const int MAX_ADAPTER_ADDRESS_LENGTH = 8; internal uint length; internal uint index; internal IntPtr next; // Needs to be ANSI. [MarshalAs(UnmanagedType.LPStr)] internal string AdapterName; internal IntPtr firstUnicastAddress; internal IntPtr firstAnycastAddress; internal IntPtr firstMulticastAddress; internal IntPtr firstDnsServerAddress; internal string dnsSuffix; internal string description; internal string friendlyName; [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_ADAPTER_ADDRESS_LENGTH)] internal byte[] address; internal uint addressLength; internal AdapterFlags flags; internal uint mtu; internal NetworkInterfaceType type; internal OperationalStatus operStatus; internal uint ipv6Index; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] internal uint[] zoneIndices; internal IntPtr firstPrefix; internal ulong transmitLinkSpeed; internal ulong receiveLinkSpeed; internal IntPtr firstWinsServerAddress; internal IntPtr firstGatewayAddress; internal uint ipv4Metric; internal uint ipv6Metric; internal ulong luid; internal IpSocketAddress dhcpv4Server; internal uint compartmentId; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] internal byte[] networkGuid; internal InterfaceConnectionType connectionType; internal InterfaceTunnelType tunnelType; internal IpSocketAddress dhcpv6Server; // Never available in Windows. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 130)] internal byte[] dhcpv6ClientDuid; internal uint dhcpv6ClientDuidLength; internal uint dhcpV6Iaid; /* Windows 2008 + PIP_ADAPTER_DNS_SUFFIX FirstDnsSuffix; * */ } internal enum InterfaceConnectionType : int { Dedicated = 1, Passive = 2, Demand = 3, Maximum = 4, } internal enum InterfaceTunnelType : int { None = 0, Other = 1, Direct = 2, SixToFour = 11, Isatap = 13, Teredo = 14, IpHttps = 15, } /// <summary> /// IP_PER_ADAPTER_INFO - per-adapter IP information such as DNS server list. /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] internal struct IpPerAdapterInfo { internal bool autoconfigEnabled; internal bool autoconfigActive; internal IntPtr currentDnsServer; /* IpAddressList* */ internal IpAddrString dnsServerList; }; /// <summary> /// Store an IP address with its corresponding subnet mask, /// both as dotted decimal strings. /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] internal struct IpAddrString { internal IntPtr Next; /* struct _IpAddressList* */ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] internal string IpAddress; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] internal string IpMask; internal uint Context; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct MibIfRow2 // MIB_IF_ROW2 { private const int GuidLength = 16; private const int IfMaxStringSize = 256; private const int IfMaxPhysAddressLength = 32; internal ulong interfaceLuid; internal uint interfaceIndex; [MarshalAs(UnmanagedType.ByValArray, SizeConst = GuidLength)] internal byte[] interfaceGuid; [MarshalAs(UnmanagedType.ByValArray, SizeConst = IfMaxStringSize + 1)] internal char[] alias; // Null terminated string. [MarshalAs(UnmanagedType.ByValArray, SizeConst = IfMaxStringSize + 1)] internal char[] description; // Null terminated string. internal uint physicalAddressLength; [MarshalAs(UnmanagedType.ByValArray, SizeConst = IfMaxPhysAddressLength)] internal byte[] physicalAddress; // ANSI [MarshalAs(UnmanagedType.ByValArray, SizeConst = IfMaxPhysAddressLength)] internal byte[] permanentPhysicalAddress; // ANSI internal uint mtu; internal NetworkInterfaceType type; internal InterfaceTunnelType tunnelType; internal uint mediaType; // Enum internal uint physicalMediumType; // Enum internal uint accessType; // Enum internal uint directionType; // Enum internal byte interfaceAndOperStatusFlags; // Flags Enum internal OperationalStatus operStatus; internal uint adminStatus; // Enum internal uint mediaConnectState; // Enum [MarshalAs(UnmanagedType.ByValArray, SizeConst = GuidLength)] internal byte[] networkGuid; internal InterfaceConnectionType connectionType; internal ulong transmitLinkSpeed; internal ulong receiveLinkSpeed; internal ulong inOctets; internal ulong inUcastPkts; internal ulong inNUcastPkts; internal ulong inDiscards; internal ulong inErrors; internal ulong inUnknownProtos; internal ulong inUcastOctets; internal ulong inMulticastOctets; internal ulong inBroadcastOctets; internal ulong outOctets; internal ulong outUcastPkts; internal ulong outNUcastPkts; internal ulong outDiscards; internal ulong outErrors; internal ulong outUcastOctets; internal ulong outMulticastOctets; internal ulong outBroadcastOctets; internal ulong outQLen; } [StructLayout(LayoutKind.Sequential)] internal struct MibUdpStats { internal uint datagramsReceived; internal uint incomingDatagramsDiscarded; internal uint incomingDatagramsWithErrors; internal uint datagramsSent; internal uint udpListeners; } [StructLayout(LayoutKind.Sequential)] internal struct MibTcpStats { internal uint reTransmissionAlgorithm; internal uint minimumRetransmissionTimeOut; internal uint maximumRetransmissionTimeOut; internal uint maximumConnections; internal uint activeOpens; internal uint passiveOpens; internal uint failedConnectionAttempts; internal uint resetConnections; internal uint currentConnections; internal uint segmentsReceived; internal uint segmentsSent; internal uint segmentsResent; internal uint errorsReceived; internal uint segmentsSentWithReset; internal uint cumulativeConnections; } [StructLayout(LayoutKind.Sequential)] internal struct MibIpStats { internal bool forwardingEnabled; internal uint defaultTtl; internal uint packetsReceived; internal uint receivedPacketsWithHeaderErrors; internal uint receivedPacketsWithAddressErrors; internal uint packetsForwarded; internal uint receivedPacketsWithUnknownProtocols; internal uint receivedPacketsDiscarded; internal uint receivedPacketsDelivered; internal uint packetOutputRequests; internal uint outputPacketRoutingDiscards; internal uint outputPacketsDiscarded; internal uint outputPacketsWithNoRoute; internal uint packetReassemblyTimeout; internal uint packetsReassemblyRequired; internal uint packetsReassembled; internal uint packetsReassemblyFailed; internal uint packetsFragmented; internal uint packetsFragmentFailed; internal uint packetsFragmentCreated; internal uint interfaces; internal uint ipAddresses; internal uint routes; } [StructLayout(LayoutKind.Sequential)] internal struct MibIcmpInfo { internal MibIcmpStats inStats; internal MibIcmpStats outStats; } [StructLayout(LayoutKind.Sequential)] internal struct MibIcmpStats { internal uint messages; internal uint errors; internal uint destinationUnreachables; internal uint timeExceeds; internal uint parameterProblems; internal uint sourceQuenches; internal uint redirects; internal uint echoRequests; internal uint echoReplies; internal uint timestampRequests; internal uint timestampReplies; internal uint addressMaskRequests; internal uint addressMaskReplies; } [StructLayout(LayoutKind.Sequential)] internal struct MibIcmpInfoEx { internal MibIcmpStatsEx inStats; internal MibIcmpStatsEx outStats; } [StructLayout(LayoutKind.Sequential)] internal struct MibIcmpStatsEx { internal uint dwMsgs; internal uint dwErrors; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] internal uint[] rgdwTypeCount; } [StructLayout(LayoutKind.Sequential)] internal struct MibTcpTable { internal uint numberOfEntries; } [StructLayout(LayoutKind.Sequential)] internal struct MibTcpRow { internal TcpState state; internal uint localAddr; internal byte localPort1; internal byte localPort2; // Ports are only 16 bit values (in network WORD order, 3,4,1,2). // There are reports where the high order bytes have garbage in them. internal byte ignoreLocalPort3; internal byte ignoreLocalPort4; internal uint remoteAddr; internal byte remotePort1; internal byte remotePort2; // Ports are only 16 bit values (in network WORD order, 3,4,1,2). // There are reports where the high order bytes have garbage in them. internal byte ignoreRemotePort3; internal byte ignoreRemotePort4; } [StructLayout(LayoutKind.Sequential)] internal struct MibTcp6TableOwnerPid { internal uint numberOfEntries; } [StructLayout(LayoutKind.Sequential)] internal struct MibTcp6RowOwnerPid { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] internal byte[] localAddr; internal uint localScopeId; internal byte localPort1; internal byte localPort2; // Ports are only 16 bit values (in network WORD order, 3,4,1,2). // There are reports where the high order bytes have garbage in them. internal byte ignoreLocalPort3; internal byte ignoreLocalPort4; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] internal byte[] remoteAddr; internal uint remoteScopeId; internal byte remotePort1; internal byte remotePort2; // Ports are only 16 bit values (in network WORD order, 3,4,1,2). // There are reports where the high order bytes have garbage in them. internal byte ignoreRemotePort3; internal byte ignoreRemotePort4; internal TcpState state; internal uint owningPid; } internal enum TcpTableClass { TcpTableBasicListener = 0, TcpTableBasicConnections = 1, TcpTableBasicAll = 2, TcpTableOwnerPidListener = 3, TcpTableOwnerPidConnections = 4, TcpTableOwnerPidAll = 5, TcpTableOwnerModuleListener = 6, TcpTableOwnerModuleConnections = 7, TcpTableOwnerModuleAll = 8 } [StructLayout(LayoutKind.Sequential)] internal struct MibUdpTable { internal uint numberOfEntries; } [StructLayout(LayoutKind.Sequential)] internal struct MibUdpRow { internal uint localAddr; internal byte localPort1; internal byte localPort2; // Ports are only 16 bit values (in network WORD order, 3,4,1,2). // There are reports where the high order bytes have garbage in them. internal byte ignoreLocalPort3; internal byte ignoreLocalPort4; } internal enum UdpTableClass { UdpTableBasic = 0, UdpTableOwnerPid = 1, UdpTableOwnerModule = 2 } [StructLayout(LayoutKind.Sequential)] internal struct MibUdp6TableOwnerPid { internal uint numberOfEntries; } [StructLayout(LayoutKind.Sequential)] internal struct MibUdp6RowOwnerPid { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] internal byte[] localAddr; internal uint localScopeId; internal byte localPort1; internal byte localPort2; // Ports are only 16 bit values (in network WORD order, 3,4,1,2). // There are reports where the high order bytes have garbage in them. internal byte ignoreLocalPort3; internal byte ignoreLocalPort4; internal uint owningPid; } internal delegate void StableUnicastIpAddressTableDelegate(IntPtr context, IntPtr table); [DllImport(Interop.Libraries.IpHlpApi)] internal static extern uint GetAdaptersAddresses( AddressFamily family, uint flags, IntPtr pReserved, SafeLocalAllocHandle adapterAddresses, ref uint outBufLen); [DllImport(Interop.Libraries.IpHlpApi)] internal static extern uint GetBestInterfaceEx(byte[] ipAddress, out int index); [DllImport(Interop.Libraries.IpHlpApi)] internal static extern uint GetIfEntry2(ref MibIfRow2 pIfRow); [DllImport(Interop.Libraries.IpHlpApi)] internal static extern uint GetIpStatisticsEx(out MibIpStats statistics, AddressFamily family); [DllImport(Interop.Libraries.IpHlpApi)] internal static extern uint GetTcpStatisticsEx(out MibTcpStats statistics, AddressFamily family); [DllImport(Interop.Libraries.IpHlpApi)] internal static extern uint GetUdpStatisticsEx(out MibUdpStats statistics, AddressFamily family); [DllImport(Interop.Libraries.IpHlpApi)] internal static extern uint GetIcmpStatistics(out MibIcmpInfo statistics); [DllImport(Interop.Libraries.IpHlpApi)] internal static extern uint GetIcmpStatisticsEx(out MibIcmpInfoEx statistics, AddressFamily family); [DllImport(Interop.Libraries.IpHlpApi)] internal static extern uint GetTcpTable(SafeLocalAllocHandle pTcpTable, ref uint dwOutBufLen, bool order); [DllImport(Interop.Libraries.IpHlpApi)] internal static extern uint GetExtendedTcpTable(SafeLocalAllocHandle pTcpTable, ref uint dwOutBufLen, bool order, uint IPVersion, TcpTableClass tableClass, uint reserved); [DllImport(Interop.Libraries.IpHlpApi)] internal static extern uint GetUdpTable(SafeLocalAllocHandle pUdpTable, ref uint dwOutBufLen, bool order); [DllImport(Interop.Libraries.IpHlpApi)] internal static extern uint GetExtendedUdpTable(SafeLocalAllocHandle pUdpTable, ref uint dwOutBufLen, bool order, uint IPVersion, UdpTableClass tableClass, uint reserved); [DllImport(Interop.Libraries.IpHlpApi)] internal static extern uint GetPerAdapterInfo(uint IfIndex, SafeLocalAllocHandle pPerAdapterInfo, ref uint pOutBufLen); [DllImport(Interop.Libraries.IpHlpApi)] internal static extern void FreeMibTable(IntPtr handle); [DllImport(Interop.Libraries.IpHlpApi)] internal static extern uint CancelMibChangeNotify2(IntPtr notificationHandle); [DllImport(Interop.Libraries.IpHlpApi)] internal static extern uint NotifyStableUnicastIpAddressTable( [In] AddressFamily addressFamily, [Out] out SafeFreeMibTable table, [MarshalAs(UnmanagedType.FunctionPtr)][In] StableUnicastIpAddressTableDelegate callback, [In] IntPtr context, [Out] out SafeCancelMibChangeNotify notificationHandle); [DllImport(Interop.Libraries.IpHlpApi, ExactSpelling = true)] internal static extern uint GetNetworkParams(SafeLocalAllocHandle pFixedInfo, ref uint pOutBufLen); } }
using CilJs.Ast; using CilJs.JSAst; using CilJs.Loading; using CilJs.Loading.Model; using System; using System.Collections.Generic; using System.Linq; namespace CilJs.JsTranslation { /// <summary> /// Translates blocks (method bodies, try-catch-finally constructs) into JavaScript AST. /// </summary> class BlockTranslator : AbstractTranslator { private CilType type; private CilMethod method; private JSExpression this_; private CilAssembly assembly; public BlockTranslator(Context context, CilAssembly assembly, CilType type, CilMethod method, JSExpression this_, SourceMapBuilder sourceMapBuilder) : base(context, sourceMapBuilder) { this.type = type; this.assembly = assembly; this.method = method; this.this_ = this_; } public List<JSStatement> Translate(Block block) { return CreateJsBlock(null, block, 0).Build().ToList(); } private BlockBuilder CreateJsBlock(ProtectedRegion region, Block block, int depth, bool isSubBlock = false, bool isFinally = false) { var opTranslator = new OpTranslator(context, assembly, type, method, block, sourceMapBuilder); var hasFinally = region != null && region.FinallyBlock != null; var hasBranching = block.GetAllLabels().Any(l => l.Position != 0); var builder = new BlockBuilder( depth, GetStartPosition(block), GetEndPosition(block), hasFinally, hasBranching, isSubBlock, isFinally); foreach (var nodes in block.Ast.Zip(block.Ast.Skip(1).EndWith(null), (current, next) => new { current, next })) { var node = nodes.current; var peek = nodes.next; var subblock = node as Block; var protectedRegion = node as ProtectedRegion; var label = node as JumpLabel; var expr = node as OpExpression; if (label != null) { builder.InsertLabel(label); } else if (protectedRegion != null) { if (protectedRegion.CatchBlocks.Count == 0 && protectedRegion.FaultBlock == null && protectedRegion.FinallyBlock == null) { builder.InsertStatements(CreateJsBlock(protectedRegion, protectedRegion.TryBlock, depth + 1).Build()); } else { builder.InsertStatements(CreateJsTryBlock(protectedRegion, protectedRegion.TryBlock, depth + 1)); if (protectedRegion.CatchBlocks.Any() || protectedRegion.FaultBlock != null) builder.InsertStatements(CreateJsCatchBlock(protectedRegion, protectedRegion.CatchBlocks, protectedRegion.FaultBlock, depth + 1)); if (protectedRegion.FinallyBlock != null) builder.InsertStatements(CreateJsFinallyBlock(protectedRegion, protectedRegion.FinallyBlock, depth + 1)); builder.InsertStatements(new[] { new JSContinueExpression().ToStatement() }); } } else if (subblock != null) { // todo: check which labels can _actually_ be targets from outside loop foreach (var lbl in subblock.GetAllLabels()) builder.InsertLabel(lbl); builder.InsertStatements(CreateJsBlock(null, subblock, depth + 1, isSubBlock: true).Build()); if (!(peek is JumpLabel)) // trims a few unneeded checks, but is not necessary, remove if there is problem { var positions = subblock.GetAllLabels().Select(l => l.Position).ToArray(); var start = positions.Min(); var end = positions.Max(); // this is in case we jumped out of the loop rather than "fell" out.. // we need to yield to the while-switch to end up at the right position builder.InsertStatements( new[] { new JSIfStatement { Condition = JSFactory.Binary( JSFactory.Binary(JSFactory.Identifier("__pos__"), ">", JSFactory.HexLiteral(end)), "||", JSFactory.Binary(JSFactory.Identifier("__pos__"), "<", JSFactory.HexLiteral(start))), Statements = { new JSContinueExpression().ToStatement() } } }); } } else if (expr != null) { builder.InsertStatements(opTranslator.Process(expr)); } } return builder; } private int GetStartPosition(Block block) { foreach (var node in block.Ast) { var op = node as OpExpression; if (op != null) return op.PrefixTraversal().Min(o => o.Position); var b = node as ProtectedRegion; if (b != null) return GetStartPosition(b.TryBlock); } throw new NotSupportedException(); } private int GetEndPosition(Block block) { return block.Ast .Select( node => { var op = node as OpExpression; if (op != null) return op.PrefixTraversal().Max(o => o.Position); var b = node as ProtectedRegion; if (b != null) return GetEndPosition(b.TryBlock); return -1; }) .Max() ; throw new NotSupportedException(); } private IEnumerable<JSStatement> CreateJsTryBlock(ProtectedRegion region, TryBlock tryBlock, int depth) { yield return new JSTryBlock { Statements = CreateJsBlock(region, tryBlock, depth).Build().ToList() }; } private IEnumerable<JSStatement> CreateJsCatchBlock(ProtectedRegion region, IEnumerable<CatchBlock> catchBlocks, FaultBlock faultBlock, int p) { if (catchBlocks.Count() == 1 && catchBlocks.First().CatchType == null) { yield return new JSCatchBlock { Error = new JSIdentifier { Name = "_" } }; yield break; } var handledFlag = new JSIdentifier { Name = "__error_handled_" + p + "__" }; var statements = new List<JSStatement> { JSFactory.Statement( new JSVariableDelcaration { Name = handledFlag.Name, Value = new JSBoolLiteral { Value = false } }) }; var exceptionObject = new JSIdentifier { Name = "__error__" }; foreach (var catchBlock in catchBlocks) { var block = CreateJsBlock(region, catchBlock, p); int index; for (index = 0; index < block.Statements.Count; index++) { var es = block.Statements[index] as JSSwitchCase; if (es == null) break; } block.Statements.Insert(index, JSFactory .Assignment(handledFlag, new JSBoolLiteral { Value = true }) .ToStatement()); // assign the exception object to expressions reading from top of the stack // ok this is too delicate.. we happen to know it is the second expression.. var expression = catchBlock.Ast.Skip(1).FirstOrDefault() as OpExpression; if (expression != null) { var locations = expression .StackBefore .First() .Definitions .Cast<ExceptionNode>() .SelectMany(e => e.StoreLocations) ; foreach (var location in locations) { block.Statements.Insert(index, JSFactory.Assignment(location.Name, exceptionObject).ToStatement()); } } statements.Add(new JSIfStatement { Condition = new JSBinaryExpression { Left = new JSUnaryExpression { Operand = handledFlag, Operator = "!" }, Operator = "&&", Right = new JSBinaryExpression { Left = exceptionObject, Operator = "instanceof", Right = GetTypeIdentifier(catchBlock.CatchType, method.ReflectionMethod, type.ReflectionType, this_) } }, Statements = block.Build().ToList() }); } statements.Add(new JSIfStatement { Condition = new JSUnaryExpression { Operand = handledFlag, Operator = "!" }, Statements = { new JSThrowExpression { Expression = exceptionObject }.ToStatement() } }); if (faultBlock != null) { statements.AddRange(CreateJsFaultBlock(region, faultBlock, p)); } yield return new JSCatchBlock { Error = exceptionObject, Statements = statements }; } private IEnumerable<JSStatement> CreateJsFaultBlock(ProtectedRegion region, FaultBlock faultBlock, int p) { var block = CreateJsBlock(region, faultBlock, p); block.Statements.Add(JSFactory.Statement(new JSThrowExpression { Expression = new JSIdentifier { Name = "__error__" } })); yield return new JSIfStatement { Condition = new JSBinaryExpression { Left = new JSIdentifier { Name = "__error_handled_" + block.Depth + "__" }, Operator = "===", Right = new JSBoolLiteral { Value = false } }, Statements = block.Build().ToList() }; } private IEnumerable<JSStatement> CreateJsFinallyBlock(ProtectedRegion region, FinallyBlock finallyBlock, int p) { yield return new JSFinallyBlock { Statements = CreateJsBlock(region, finallyBlock, p, isFinally: true).Build().ToList() }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Contracts; namespace System.Globalization { public partial class CompareInfo { internal unsafe CompareInfo(CultureInfo culture) { this.m_name = culture.m_name; InitSort(culture); } private void InitSort(CultureInfo culture) { this.m_sortName = culture.SortName; const uint LCMAP_SORTHANDLE = 0x20000000; long handle; int ret = Interop.mincore.LCMapStringEx(m_sortName, LCMAP_SORTHANDLE, null, 0, (IntPtr)(&handle), IntPtr.Size, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); _sortHandle = ret > 0 ? (IntPtr)handle : IntPtr.Zero; } internal static int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { Contract.Assert(source != null); Contract.Assert(value != null); return Interop.mincore.FindStringOrdinal(FIND_FROMSTART, source, startIndex, count, value, value.Length, ignoreCase); } internal static int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { Contract.Assert(source != null); Contract.Assert(value != null); return Interop.mincore.FindStringOrdinal(FIND_FROMEND, source, startIndex - count + 1, count, value, value.Length, ignoreCase); } private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options) { Contract.Assert(source != null); Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); if (source.Length == 0) { return 0; } int tmpHash = 0; if (Interop.mincore.LCMapStringEx(m_sortName, LCMAP_HASH | (uint)GetNativeCompareFlags(options), source, source.Length, (IntPtr)(&tmpHash), sizeof(int), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero) == 0) { Environment.FailFast("LCMapStringEx failed!"); } return tmpHash; } private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2) { // Use the OS to compare and then convert the result to expected value by subtracting 2 return Interop.mincore.CompareStringOrdinal(string1, count1, string2, count2, true) - 2; } private int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options) { Contract.Assert(string1 != null); Contract.Assert(string2 != null); Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); int result = Interop.mincore.CompareStringEx(_sortHandle != IntPtr.Zero ? null : m_sortName, GetNativeCompareFlags(options), string1, offset1, length1, string2, offset2, length2, _sortHandle); if (result == 0) { Environment.FailFast("CompareStringEx failed"); } // Map CompareStringEx return value to -1, 0, 1. return result - 2; } private int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) { Contract.Assert(!string.IsNullOrEmpty(source)); Contract.Assert(target != null); Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); if (target.Length == 0) return startIndex; // keep Whidbey compatibility if ((options & CompareOptions.Ordinal) != 0) { return FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: false); } else { int retValue = Interop.mincore.FindNLSStringEx(_sortHandle != IntPtr.Zero ? null : m_sortName, FIND_FROMSTART | (uint)GetNativeCompareFlags(options), source, startIndex, count, target, 0, target.Length, _sortHandle); if (retValue >= 0) { return retValue + startIndex; } } return -1; } private int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) { Contract.Assert(!string.IsNullOrEmpty(source)); Contract.Assert(target != null); Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); if (target.Length == 0) return startIndex; // keep Whidbey compatibility if ((options & CompareOptions.Ordinal) != 0) { return FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: true); } else { int retValue = Interop.mincore.FindNLSStringEx(_sortHandle != IntPtr.Zero ? null : m_sortName, FIND_FROMEND | (uint)GetNativeCompareFlags(options), source, startIndex - count + 1, count, target, 0, target.Length, _sortHandle); if (retValue >= 0) { return retValue + startIndex - (count - 1); } } return -1; } private bool StartsWith(string source, string prefix, CompareOptions options) { Contract.Assert(!string.IsNullOrEmpty(source)); Contract.Assert(!string.IsNullOrEmpty(prefix)); Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return Interop.mincore.FindNLSStringEx(_sortHandle != IntPtr.Zero ? null : m_sortName, FIND_STARTSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length, prefix, 0, prefix.Length, _sortHandle) >= 0; } private bool EndsWith(string source, string suffix, CompareOptions options) { Contract.Assert(!string.IsNullOrEmpty(source)); Contract.Assert(!string.IsNullOrEmpty(suffix)); Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return Interop.mincore.FindNLSStringEx(_sortHandle != IntPtr.Zero ? null : m_sortName, FIND_ENDSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length, suffix, 0, suffix.Length, _sortHandle) >= 0; } // PAL ends here [NonSerialized] private readonly IntPtr _sortHandle; private const uint LCMAP_HASH = 0x00040000; private const int FIND_STARTSWITH = 0x00100000; private const int FIND_ENDSWITH = 0x00200000; private const int FIND_FROMSTART = 0x00400000; private const int FIND_FROMEND = 0x00800000; private static unsafe int FastIndexOfString(string source, string target, int startIndex, int sourceCount, int targetCount, bool findLastIndex) { int retValue = -1; int sourceStartIndex = findLastIndex ? startIndex - sourceCount + 1 : startIndex; #if !TEST_CODEGEN_OPTIMIZATION fixed (char* pSource = source, spTarget = target) { char* spSubSource = pSource + sourceStartIndex; #else String.StringPointer spSubSource = source.GetStringPointer(sourceStartIndex); String.StringPointer spTarget = target.GetStringPointer(); #endif if (findLastIndex) { int startPattern = (sourceCount - 1) - targetCount + 1; if (startPattern < 0) return -1; char patternChar0 = spTarget[0]; for (int ctrSrc = startPattern; ctrSrc >= 0; ctrSrc--) { if (spSubSource[ctrSrc] != patternChar0) continue; int ctrPat; for (ctrPat = 1; ctrPat < targetCount; ctrPat++) { if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat]) break; } if (ctrPat == targetCount) { retValue = ctrSrc; break; } } if (retValue >= 0) { retValue += startIndex - sourceCount + 1; } } else { int endPattern = (sourceCount - 1) - targetCount + 1; if (endPattern < 0) return -1; char patternChar0 = spTarget[0]; for (int ctrSrc = 0; ctrSrc <= endPattern; ctrSrc++) { if (spSubSource[ctrSrc] != patternChar0) continue; int ctrPat; for (ctrPat = 1; ctrPat < targetCount; ctrPat++) { if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat]) break; } if (ctrPat == targetCount) { retValue = ctrSrc; break; } } if (retValue >= 0) { retValue += startIndex; } } #if !TEST_CODEGEN_OPTIMIZATION } return retValue; #endif // TEST_CODEGEN_OPTIMIZATION } private const int COMPARE_OPTIONS_ORDINAL = 0x40000000; // Ordinal private const int NORM_IGNORECASE = 0x00000001; // Ignores case. (use LINGUISTIC_IGNORECASE instead) private const int NORM_IGNOREKANATYPE = 0x00010000; // Does not differentiate between Hiragana and Katakana characters. Corresponding Hiragana and Katakana will compare as equal. private const int NORM_IGNORENONSPACE = 0x00000002; // Ignores nonspacing. This flag also removes Japanese accent characters. (use LINGUISTIC_IGNOREDIACRITIC instead) private const int NORM_IGNORESYMBOLS = 0x00000004; // Ignores symbols. private const int NORM_IGNOREWIDTH = 0x00020000; // Does not differentiate between a single-byte character and the same character as a double-byte character. private const int NORM_LINGUISTIC_CASING = 0x08000000; // use linguistic rules for casing private const int SORT_STRINGSORT = 0x00001000; // Treats punctuation the same as symbols. private static int GetNativeCompareFlags(CompareOptions options) { // Use "linguistic casing" by default (load the culture's casing exception tables) int nativeCompareFlags = NORM_LINGUISTIC_CASING; if ((options & CompareOptions.IgnoreCase) != 0) { nativeCompareFlags |= NORM_IGNORECASE; } if ((options & CompareOptions.IgnoreKanaType) != 0) { nativeCompareFlags |= NORM_IGNOREKANATYPE; } if ((options & CompareOptions.IgnoreNonSpace) != 0) { nativeCompareFlags |= NORM_IGNORENONSPACE; } if ((options & CompareOptions.IgnoreSymbols) != 0) { nativeCompareFlags |= NORM_IGNORESYMBOLS; } if ((options & CompareOptions.IgnoreWidth) != 0) { nativeCompareFlags |= NORM_IGNOREWIDTH; } if ((options & CompareOptions.StringSort) != 0) { nativeCompareFlags |= SORT_STRINGSORT; } // Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; } Contract.Assert(((options & ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreWidth | CompareOptions.StringSort)) == 0) || (options == CompareOptions.Ordinal), "[CompareInfo.GetNativeCompareFlags]Expected all flags to be handled"); return nativeCompareFlags; } } }
/* * JSONParser.cs * * Copyright ?2007 Michael Schwarz (http://www.ajaxpro.info). * All Rights Reserved. * * 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. */ /* * MS 06-05-30 added \u0000 support for unicode characters * MS 06-07-09 changed "new ..." string to JavaScriptSource * * */ using System; using System.Reflection; using System.Data; using System.IO; using System.Collections; using System.Globalization; using System.Text; namespace AjaxPro { /// <summary> /// Represents a parser for JSON strings. /// </summary> public sealed class JSONParser { /// <summary> /// Initialize a new instance of JSONParser. /// </summary> internal JSONParser() { } #region Constant Variables public const char JSON_OBJECT_BEGIN = '{'; public const char JSON_OBJECT_END = '}'; public const char JSON_ARRAY_BEGIN = '['; public const char JSON_ARRAY_END = ']'; public const char JSON_PROPERTY_SEPARATOR = ':'; public const char JSON_STRING_SINGLE_QUOTE = '\''; public const char JSON_STRING_DOUBLE_QUOTE = '"'; public const char JSON_ITEMS_SEPARATOR = ','; public const char JSON_DECIMAL_SEPARATOR = '.'; public const char END_OF_STRING = '\0'; public const char NEW_LINE = '\n'; public const char RETURN = '\r'; #endregion #region Private Variables private int _idx = 0; private string _json = null; private char _ch = ' '; #endregion #region Read Methods /// <summary> /// Read on the JSON string until first non-whitespace character. /// </summary> internal void ReadWhiteSpaces() { while (_ch != END_OF_STRING && _ch <= ' ') ReadNext(); } /// <summary> /// Read the next character from the JSON string and store it in the private variable ch. /// </summary> /// <returns>Returns false if at end of JSON string.</returns> internal bool ReadNext() { if (_idx >= _json.Length) { _ch = END_OF_STRING; return false; } _ch = _json[_idx]; _idx++; return true; } internal bool CompareNext(string s) { if (_idx + s.Length > _json.Length) return false; if (_json.Substring(_idx, s.Length) == s) return true; return false; } /// <summary> /// Read the previous character from the JSON string and store it in the private variable ch. /// </summary> /// <returns> /// Returns false if at the beginning of the JSON string. /// </returns> internal bool ReadPrev() { if (_idx <= 0) return false; _idx--; _ch = _json[_idx]; return true; } #endregion #region Read JSON Methods /// <summary> /// Read a string object from the JSON string. /// </summary> /// <returns>Returns the string.</returns> internal JavaScriptString ReadString() { JavaScriptString s = new JavaScriptString(); if (_ch == JSON_STRING_DOUBLE_QUOTE) { while (ReadNext()) { if (_ch == JSON_STRING_DOUBLE_QUOTE) { ReadNext(); return s; } else if (_ch == '\\') { ReadNext(); switch (_ch) { case 'n': s += '\n'; break; case 'r': s += '\r'; break; case 'b': s += '\b'; break; case 'f': s += '\f'; break; case 't': s += '\t'; break; case '\\': s += '\\'; break; case 'u': string u = ""; for (int i = 0; i < 4; i++) { // TODO: add more checks if correct format \\u0000 ReadNext(); u += _ch; } s += (char)((ushort)int.Parse(u, NumberStyles.HexNumber, CultureInfo.InvariantCulture)); break; default: s += _ch; break; } } else { s += _ch; } } } else { throw new NotSupportedException("The string could not be read."); } return s; } /// <summary> /// Reads the java script source. /// </summary> /// <returns></returns> internal JavaScriptSource ReadJavaScriptSource() { JavaScriptSource s = new JavaScriptSource(); s.Append(ReadJavaScriptObject().ToString()); return s; } /// <summary> /// Reads the java script object. /// </summary> /// <returns></returns> internal JavaScriptString ReadJavaScriptObject() { JavaScriptString n = new JavaScriptString(); int b = 0; bool bf = false; while (_ch != END_OF_STRING) { if (_ch == '(') { b++; bf = true; } else if (_ch == ')') b--; if (bf) { } n += _ch; ReadNext(); if (bf && b == 0) break; } return n; } /// <summary> /// Read a number object from the JSON string. /// </summary> /// <returns>Returns the number.</returns> internal JavaScriptNumber ReadNumber() { JavaScriptNumber n = new JavaScriptNumber(); if (_ch == '-') // negative numbers { n += "-"; ReadNext(); } // Searching for all numbers until the first character that is not // a number. while (_ch >= '0' && _ch <= '9' && _ch != END_OF_STRING) // all numbers between 0..9 { n += _ch; ReadNext(); } // In JavaScript (JSON) the decimal separator is always a point. If we // have a decimal number we read all the numbers after the separator. if (_ch == '.') { n += '.'; ReadNext(); while (_ch >= '0' && _ch <= '9' && _ch != END_OF_STRING) { n += _ch; ReadNext(); } } if (_ch == 'e' || _ch == 'E') { n += 'e'; ReadNext(); if (_ch == '-' || _ch == '+') { n += _ch; ReadNext(); } while (_ch >= '0' && _ch <= '9' && _ch != END_OF_STRING) { n += _ch; ReadNext(); } } return n; } /// <summary> /// Read a word object from the JSON string. /// </summary> /// <returns>Returns the word.</returns> internal IJavaScriptObject ReadWord() { switch (_ch) { case 't': if (CompareNext("rue") == true) { ReadNext(); ReadNext(); ReadNext(); ReadNext(); return new JavaScriptBoolean(true); } break; case 'f': if (CompareNext("alse") == true) { ReadNext(); ReadNext(); ReadNext(); ReadNext(); ReadNext(); return new JavaScriptBoolean(false); } break; case 'n': if (CompareNext("ull") == true) { ReadNext(); ReadNext(); ReadNext(); ReadNext(); return null; } else if (CompareNext("ew ") == true) { return ReadJavaScriptSource(); } break; } throw new NotSupportedException("word " + _ch); } /// <summary> /// Read an array object from the JSON string. /// </summary> /// <returns>Returns an ArrayList with all objects.</returns> internal JavaScriptArray ReadArray() { JavaScriptArray a = new JavaScriptArray(); if (_ch == JSON_ARRAY_BEGIN) { ReadNext(); ReadWhiteSpaces(); if (_ch == JSON_ARRAY_END) { ReadNext(); return a; } while (_ch != END_OF_STRING) { a.Add(GetObject()); ReadWhiteSpaces(); if (_ch == JSON_ARRAY_END) { ReadNext(); return a; } else if (_ch != JSON_ITEMS_SEPARATOR) { break; } ReadNext(); ReadWhiteSpaces(); } } else { throw new NotSupportedException("Array could not be read."); } return a; } /// <summary> /// Reads the next object from the JSON string. /// </summary> /// <returns> /// Returns an Hashtable with all properties. /// </returns> internal JavaScriptObject ReadObject() { JavaScriptObject h = new JavaScriptObject(); string k; if (_ch == JSON_OBJECT_BEGIN) { ReadNext(); ReadWhiteSpaces(); if (_ch == JSON_OBJECT_END) { ReadNext(); return h; } while (_ch != END_OF_STRING) { k = ReadString(); ReadWhiteSpaces(); if (_ch != JSON_PROPERTY_SEPARATOR) { break; } ReadNext(); h.Add(k, GetObject()); ReadWhiteSpaces(); if (_ch == JSON_OBJECT_END) { ReadNext(); return h; } else if (_ch != JSON_ITEMS_SEPARATOR) { break; } ReadNext(); ReadWhiteSpaces(); } } throw new NotSupportedException("obj"); } #endregion #region JSON string and JSON object /// <summary> /// Returns a JSON object using Hashtable, ArrayList or string. /// </summary> /// <returns></returns> internal IJavaScriptObject GetObject() { if (_json == null) throw new Exception("Missing json string."); ReadWhiteSpaces(); switch (_ch) { case JSON_OBJECT_BEGIN: return ReadObject(); case JSON_ARRAY_BEGIN: return ReadArray(); case JSON_STRING_DOUBLE_QUOTE: return ReadString(); case '-': return ReadNumber(); default: return _ch >= '0' && _ch <= '9' ? ReadNumber() : ReadWord(); } } #endregion /// <summary> /// Reads the object that represents the JSON string. /// </summary> /// <param name="json">The json.</param> /// <returns>Returns an object.</returns> public IJavaScriptObject GetJSONObject(string json) { _json = json; _idx = 0; _ch = ' '; return GetObject(); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using System.Text; // This class is based on the assumption that positive x faces right, and positive y faces up. #region Controller Enums namespace Xbox { public enum Button : byte { A = 0, B, X, Y, Back, Start, LAnalogBtn, RAnalogBtn, LBumper, RBumper, NONE = Byte.MaxValue }; public enum Axis : byte { DPadX = 0, DPadY, LAnalogX, LAnalogY, RAnalogX, RAnalogY, TriggerR, TriggerL, NONE = Byte.MaxValue } } #endregion public class Xbox360GamepadState { #region Input class mappings public const string MAP_DPAD_X = "DPad_XAxis_1"; public const string MAP_DPAD_Y = "DPad_YAxis_1"; public const string MAP_LANALOG_X = "L_XAxis_1"; public const string MAP_LANALOG_Y = "L_YAxis_1"; public const string MAP_RANALOG_X = "R_XAxis_1"; public const string MAP_RANALOG_Y = "R_YAxis_1"; public const string MAP_TRIGGER_R = "TriggersR_1"; public const string MAP_TRIGGER_L = "TriggersL_1"; public const string MAP_A = "A_1"; public const string MAP_B = "B_1"; public const string MAP_X = "X_1"; public const string MAP_Y = "Y_1"; public const string MAP_BACK = "Back_1"; public const string MAP_START = "Start_1"; public const string MAP_LANALOG_BTN = "LS_1"; public const string MAP_RANALOG_BTN = "RS_1"; public const string MAP_LBUMPER = "LB_1"; public const string MAP_RBUMPER = "RB_1"; //public const string MAP_AXIS_1 = "Axis_1"; //public const string MAP_AXIS_2 = "Axis_2"; //public const string MAP_AXIS_3 = "Axis_3"; //public const string MAP_AXIS_4 = "Axis_4"; //public const string MAP_AXIS_5 = "Axis_5"; //public const string MAP_AXIS_6 = "Axis_6"; //public const string MAP_AXIS_7 = "Axis_7"; //public const string MAP_AXIS_8 = "Axis_8"; //public const string MAP_AXIS_9 = "Axis_9"; //public const string MAP_AXIS_10 = "Axis_10"; #endregion #region Control axis/button values public Dictionary<Xbox.Axis, float> Axes { get { return axes; } private set { axes = value; } } public Dictionary<Xbox.Button, bool> Buttons { get { return buttons; } private set { buttons = value; } } private Dictionary<Xbox.Axis, float> PrevAxes { get { return prevAxes; } set { prevAxes = value; } } private Dictionary<Xbox.Button, bool> PrevButtons { get { return prevButtons; } set { prevButtons = value; } } private Dictionary<Xbox.Axis, float> axes; private Dictionary<Xbox.Button, bool> buttons; private Dictionary<Xbox.Axis, float> prevAxes; private Dictionary<Xbox.Button, bool> prevButtons; #endregion #region Constructor public Xbox360GamepadState() { Axes = new Dictionary<Xbox.Axis, float> (); PrevAxes = new Dictionary<Xbox.Axis, float> (); Buttons = new Dictionary<Xbox.Button, bool> (); PrevButtons = new Dictionary<Xbox.Button, bool> (); Axes.Add( Xbox.Axis.DPadX, 0f ); PrevAxes.Add( Xbox.Axis.DPadX, 0f ); Axes.Add( Xbox.Axis.DPadY, 0f ); PrevAxes.Add( Xbox.Axis.DPadY, 0f ); Axes.Add( Xbox.Axis.LAnalogX, 0f ); PrevAxes.Add( Xbox.Axis.LAnalogX, 0f ); Axes.Add( Xbox.Axis.LAnalogY, 0f ); PrevAxes.Add( Xbox.Axis.LAnalogY, 0f ); Axes.Add( Xbox.Axis.RAnalogX, 0f ); PrevAxes.Add( Xbox.Axis.RAnalogX, 0f ); Axes.Add( Xbox.Axis.RAnalogY, 0f ); PrevAxes.Add( Xbox.Axis.RAnalogY, 0f ); Axes.Add( Xbox.Axis.TriggerL, 0f ); PrevAxes.Add( Xbox.Axis.TriggerL, 0f ); Axes.Add( Xbox.Axis.TriggerR, 0f ); PrevAxes.Add( Xbox.Axis.TriggerR, 0f ); Buttons.Add( Xbox.Button.A, false ); PrevButtons.Add( Xbox.Button.A, false ); Buttons.Add( Xbox.Button.B, false ); PrevButtons.Add( Xbox.Button.B, false ); Buttons.Add( Xbox.Button.Back, false ); PrevButtons.Add( Xbox.Button.Back, false ); Buttons.Add( Xbox.Button.LAnalogBtn, false ); PrevButtons.Add( Xbox.Button.LAnalogBtn, false ); Buttons.Add( Xbox.Button.LBumper, false ); PrevButtons.Add( Xbox.Button.LBumper, false ); Buttons.Add( Xbox.Button.RAnalogBtn, false ); PrevButtons.Add( Xbox.Button.RAnalogBtn, false ); Buttons.Add( Xbox.Button.RBumper, false ); PrevButtons.Add( Xbox.Button.RBumper, false ); Buttons.Add( Xbox.Button.Start, false ); PrevButtons.Add( Xbox.Button.Start, false ); Buttons.Add( Xbox.Button.X, false ); PrevButtons.Add( Xbox.Button.X, false ); Buttons.Add( Xbox.Button.Y, false ); PrevButtons.Add( Xbox.Button.Y, false ); } static Xbox360GamepadState() { Instance = null; } #endregion #region Get the current control state public void UpdateState() { foreach ( Xbox.Axis key in Axes.Keys ) { PrevAxes[ key ] = Axes[ key ]; } foreach ( Xbox.Button key in Buttons.Keys ) { PrevButtons[ key ] = Buttons[ key ]; } // Read in the control axes Axes[ Xbox.Axis.DPadX ] = Input.GetAxis( MAP_DPAD_X ); Axes[ Xbox.Axis.DPadY ] = Input.GetAxis( MAP_DPAD_Y ); Axes[ Xbox.Axis.LAnalogX ] = Input.GetAxis( MAP_LANALOG_X ); Axes[ Xbox.Axis.LAnalogY ] = Input.GetAxis( MAP_LANALOG_Y ); Axes[ Xbox.Axis.RAnalogX ] = Input.GetAxis( MAP_RANALOG_X ); Axes[ Xbox.Axis.RAnalogY ] = Input.GetAxis( MAP_RANALOG_Y ); Axes[ Xbox.Axis.TriggerL ] = Input.GetAxis( MAP_TRIGGER_L ); Axes[ Xbox.Axis.TriggerR ] = Input.GetAxis( MAP_TRIGGER_R ); // Read in each of the buttons Buttons[ Xbox.Button.A ] = Input.GetButton( MAP_A ); Buttons[ Xbox.Button.B ] = Input.GetButton( MAP_B ); Buttons[ Xbox.Button.X ] = Input.GetButton( MAP_X ); Buttons[ Xbox.Button.Y ] = Input.GetButton( MAP_Y ); Buttons[ Xbox.Button.Back ] = Input.GetButton( MAP_BACK ); Buttons[ Xbox.Button.Start ] = Input.GetButton( MAP_START ); Buttons[ Xbox.Button.LAnalogBtn ] = Input.GetButton( MAP_LANALOG_BTN ); Buttons[ Xbox.Button.RAnalogBtn ] = Input.GetButton( MAP_RANALOG_BTN ); Buttons[ Xbox.Button.LBumper ] = Input.GetButton( MAP_LBUMPER ); Buttons[ Xbox.Button.RBumper ] = Input.GetButton( MAP_RBUMPER ); } #endregion #region ButtonDown / ButtonUp public bool IsButtonDown( Xbox.Button b ) { if ( Buttons[ b ] == true && prevButtons[ b ] == false ) { return true; } return false; } public bool IsButtonUp( Xbox.Button b ) { if ( Buttons[ b ] == false && prevButtons[ b ] == true ) { return true; } return false; } #endregion #region Axis Threshold Functions /// <summary> Check if an axis is past a threshold and was not the check before. </summary> /// <remarks> James, 2014-05-02. </remarks> /// <param name="Axis"> The axis to check. </param> /// <param name="Threshold"> The threashold between 0 and 1. </param> /// <returns> /// true if the axis is past the threshold and previously was not, otherwise false. /// </returns> public bool AxisJustPastThreshold( Xbox.Axis Axis, float Threshold ) { float threshold = Mathf.Clamp( Threshold, -1f, 1f ); if ( threshold > 0 ) { if ( Axes[ Axis ] >= threshold && PrevAxes[ Axis ] < threshold ) return true; } else { if ( Axes[ Axis ] < threshold && PrevAxes[ Axis ] > threshold ) return true; } return false; } #endregion #region Singleton Stuff private static Xbox360GamepadState instance; public static Xbox360GamepadState Instance { get { if ( instance == null ) { instance = new Xbox360GamepadState(); } return instance; } private set { instance = value; } } #endregion public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendLine( "Xbox 360 Game pad State\n\n" ); sb.AppendLine( "Axes\n" ); foreach ( Xbox.Axis key in Axes.Keys ) { sb.AppendLine( key.ToString() + ": \t\t" + Axes[ key ].ToString() ); } sb.AppendLine( "" ); sb.AppendLine( "Buttons\n" ); foreach ( Xbox.Button key in Buttons.Keys ) { sb.AppendLine( key.ToString() + ": \t\t" + Buttons[ key ].ToString() ); } sb.AppendLine(""); return sb.ToString(); } }
// 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.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using System.Diagnostics; namespace System.IO { public partial class FileStream : Stream { private const FileShare DefaultShare = FileShare.Read; private const bool DefaultIsAsync = false; internal const int DefaultBufferSize = 4096; private byte[] _buffer; private int _bufferLength; private readonly SafeFileHandle _fileHandle; /// <summary>Whether the file is opened for reading, writing, or both.</summary> private readonly FileAccess _access; /// <summary>The path to the opened file.</summary> private readonly string _path; /// <summary>The next available byte to be read from the _buffer.</summary> private int _readPos; /// <summary>The number of valid bytes in _buffer.</summary> private int _readLength; /// <summary>The next location in which a write should occur to the buffer.</summary> private int _writePos; /// <summary> /// Whether asynchronous read/write/flush operations should be performed using async I/O. /// On Windows FileOptions.Asynchronous controls how the file handle is configured, /// and then as a result how operations are issued against that file handle. On Unix, /// there isn't any distinction around how file descriptors are created for async vs /// sync, but we still differentiate how the operations are issued in order to provide /// similar behavioral semantics and performance characteristics as on Windows. On /// Windows, if non-async, async read/write requests just delegate to the base stream, /// and no attempt is made to synchronize between sync and async operations on the stream; /// if async, then async read/write requests are implemented specially, and sync read/write /// requests are coordinated with async ones by implementing the sync ones over the async /// ones. On Unix, we do something similar. If non-async, async read/write requests just /// delegate to the base stream, and no attempt is made to synchronize. If async, we use /// a semaphore to coordinate both sync and async operations. /// </summary> private readonly bool _useAsyncIO; /// <summary> /// Currently cached position in the stream. This should always mirror the underlying file's actual position, /// and should only ever be out of sync if another stream with access to this same file manipulates it, at which /// point we attempt to error out. /// </summary> private long _filePosition; /// <summary>Whether the file stream's handle has been exposed.</summary> private bool _exposedHandle; public FileStream(SafeFileHandle handle, FileAccess access) : this(handle, access, DefaultBufferSize) { } public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) : this(handle, access, bufferSize, GetDefaultIsAsync(handle)) { } public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) { if (handle.IsInvalid) throw new ArgumentException(SR.Arg_InvalidHandle, nameof(handle)); if (access < FileAccess.Read || access > FileAccess.ReadWrite) throw new ArgumentOutOfRangeException(nameof(access), SR.ArgumentOutOfRange_Enum); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); if (handle.IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (handle.IsAsync.HasValue && isAsync != handle.IsAsync.Value) throw new ArgumentException(SR.Arg_HandleNotAsync, nameof(handle)); _access = access; _useAsyncIO = isAsync; _exposedHandle = true; _bufferLength = bufferSize; _fileHandle = handle; InitFromHandle(handle); } public FileStream(string path, FileMode mode) : this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), DefaultShare, DefaultBufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access) : this(path, mode, access, DefaultShare, DefaultBufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share) : this(path, mode, access, share, DefaultBufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) : this(path, mode, access, share, bufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) : this(path, mode, access, share, bufferSize, useAsync ? FileOptions.Asynchronous : FileOptions.None) { } internal FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, string msgPath, bool bFromProxy) : this(path, mode, access, share, bufferSize, options, msgPath, bFromProxy, useLongPath: false, checkHost: false) { } internal FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, string msgPath, bool bFromProxy, bool useLongPath, bool checkHost) : this(path, mode, access, share, bufferSize, options) { // msgPath is the path that is handed back to untrusted code, CoreCLR is always full trust // bFromProxy is also related to asserting rights for limited trust and also can be ignored // useLongPath was used to get around the legacy MaxPath check, this is no longer applicable as everything supports long paths // checkHost is also related to limited trust scenarios } public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { if (path == null) throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); // don't include inheritable in our bounds check for share FileShare tempshare = share & ~FileShare.Inheritable; string badArg = null; if (mode < FileMode.CreateNew || mode > FileMode.Append) badArg = nameof(mode); else if (access < FileAccess.Read || access > FileAccess.ReadWrite) badArg = nameof(access); else if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete)) badArg = nameof(share); if (badArg != null) throw new ArgumentOutOfRangeException(badArg, SR.ArgumentOutOfRange_Enum); // NOTE: any change to FileOptions enum needs to be matched here in the error validation if (options != FileOptions.None && (options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0) throw new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_Enum); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); // Write access validation if ((access & FileAccess.Write) == 0) { if (mode == FileMode.Truncate || mode == FileMode.CreateNew || mode == FileMode.Create || mode == FileMode.Append) { // No write access, mode and access disagree but flag access since mode comes first throw new ArgumentException(SR.Format(SR.Argument_InvalidFileModeAndAccessCombo, mode, access), nameof(access)); } } if ((access & FileAccess.Read) != 0 && mode == FileMode.Append) throw new ArgumentException(SR.Argument_InvalidAppendMode, nameof(access)); string fullPath = Path.GetFullPath(path); _path = fullPath; _access = access; _bufferLength = bufferSize; if ((options & FileOptions.Asynchronous) != 0) _useAsyncIO = true; _fileHandle = OpenHandle(mode, share, options); try { Init(mode, share); } catch { // If anything goes wrong while setting up the stream, make sure we deterministically dispose // of the opened handle. _fileHandle.Dispose(); _fileHandle = null; throw; } } private static bool GetDefaultIsAsync(SafeFileHandle handle) { // This will eventually get more complicated as we can actually check the underlying handle type on Windows return handle.IsAsync.HasValue ? handle.IsAsync.Value : false; } // InternalOpen, InternalCreate, and InternalAppend: // Factory methods for FileStream used by File, FileInfo, and ReadLinesIterator // Specifies default access and sharing options for FileStreams created by those classes internal static FileStream InternalOpen(string path, int bufferSize = DefaultBufferSize, bool useAsync = DefaultIsAsync) { return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, useAsync); } internal static FileStream InternalCreate(string path, int bufferSize = DefaultBufferSize, bool useAsync = DefaultIsAsync) { return new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, bufferSize, useAsync); } internal static FileStream InternalAppend(string path, int bufferSize = DefaultBufferSize, bool useAsync = DefaultIsAsync) { return new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read, bufferSize, useAsync); } [Obsolete("This property has been deprecated. Please use FileStream's SafeFileHandle property instead. http://go.microsoft.com/fwlink/?linkid=14202")] public virtual IntPtr Handle { get { return SafeFileHandle.DangerousGetHandle(); } } public virtual void Lock(long position, long length) { if (position < 0 || length < 0) { throw new ArgumentOutOfRangeException(position < 0 ? nameof(position) : nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } LockInternal(position, length); } public virtual void Unlock(long position, long length) { if (position < 0 || length < 0) { throw new ArgumentOutOfRangeException(position < 0 ? nameof(position) : nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } UnlockInternal(position, length); } public override Task FlushAsync(CancellationToken cancellationToken) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Flush() which a subclass might have overridden. To be safe // we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Flush) when we are not sure. if (GetType() != typeof(FileStream)) return base.FlushAsync(cancellationToken); return FlushAsyncInternal(cancellationToken); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Read() or ReadAsync() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Read/ReadAsync) when we are not sure. if (GetType() != typeof(FileStream)) return base.ReadAsync(buffer, offset, count, cancellationToken); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<int>(cancellationToken); if (IsClosed) throw Error.GetFileNotOpen(); return ReadAsyncInternal(buffer, offset, count, cancellationToken); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() or WriteAsync() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write/WriteAsync) when we are not sure. if (GetType() != typeof(FileStream)) return base.WriteAsync(buffer, offset, count, cancellationToken); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); if (IsClosed) throw Error.GetFileNotOpen(); return WriteAsyncInternal(buffer, offset, count, cancellationToken); } /// <summary> /// Clears buffers for this stream and causes any buffered data to be written to the file. /// </summary> public override void Flush() { // Make sure that we call through the public virtual API Flush(flushToDisk: false); } /// <summary> /// Clears buffers for this stream, and if <param name="flushToDisk"/> is true, /// causes any buffered data to be written to the file. /// </summary> public virtual void Flush(bool flushToDisk) { if (IsClosed) throw Error.GetFileNotOpen(); FlushInternalBuffer(); if (flushToDisk && CanWrite) { FlushOSBuffer(); } } /// <summary>Gets a value indicating whether the current stream supports reading.</summary> public override bool CanRead { get { return !_fileHandle.IsClosed && (_access & FileAccess.Read) != 0; } } /// <summary>Gets a value indicating whether the current stream supports writing.</summary> public override bool CanWrite { get { return !_fileHandle.IsClosed && (_access & FileAccess.Write) != 0; } } /// <summary>Validates arguments to Read and Write and throws resulting exceptions.</summary> /// <param name="array">The buffer to read from or write to.</param> /// <param name="offset">The zero-based offset into the array.</param> /// <param name="count">The maximum number of bytes to read or write.</param> private void ValidateReadWriteArgs(byte[] array, int offset, int count) { if (array == null) throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); } /// <summary>Sets the length of this stream to the given value.</summary> /// <param name="value">The new length of the stream.</param> public override void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanSeek) throw Error.GetSeekNotSupported(); if (!CanWrite) throw Error.GetWriteNotSupported(); SetLengthInternal(value); } public virtual SafeFileHandle SafeFileHandle { get { Flush(); _exposedHandle = true; return _fileHandle; } } /// <summary>Gets the path that was passed to the constructor.</summary> public virtual string Name { get { return _path ?? SR.IO_UnknownFileName; } } /// <summary>Gets a value indicating whether the stream was opened for I/O to be performed synchronously or asynchronously.</summary> public virtual bool IsAsync { get { return _useAsyncIO; } } /// <summary>Gets the length of the stream in bytes.</summary> public override long Length { get { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanSeek) throw Error.GetSeekNotSupported(); return GetLengthInternal(); } } /// <summary> /// Verify that the actual position of the OS's handle equals what we expect it to. /// This will fail if someone else moved the UnixFileStream's handle or if /// our position updating code is incorrect. /// </summary> private void VerifyOSHandlePosition() { bool verifyPosition = _exposedHandle; // in release, only verify if we've given out the handle such that someone else could be manipulating it #if DEBUG verifyPosition = true; // in debug, always make sure our position matches what the OS says it should be #endif if (verifyPosition && CanSeek) { long oldPos = _filePosition; // SeekCore will override the current _position, so save it now long curPos = SeekCore(0, SeekOrigin.Current); if (oldPos != curPos) { // For reads, this is non-fatal but we still could have returned corrupted // data in some cases, so discard the internal buffer. For writes, // this is a problem; discard the buffer and error out. _readPos = _readLength = 0; if (_writePos > 0) { _writePos = 0; throw new IOException(SR.IO_FileStreamHandlePosition); } } } } /// <summary>Verifies that state relating to the read/write buffer is consistent.</summary> [Conditional("DEBUG")] private void AssertBufferInvariants() { // Read buffer values must be in range: 0 <= _bufferReadPos <= _bufferReadLength <= _bufferLength Debug.Assert(0 <= _readPos && _readPos <= _readLength && _readLength <= _bufferLength); // Write buffer values must be in range: 0 <= _bufferWritePos <= _bufferLength Debug.Assert(0 <= _writePos && _writePos <= _bufferLength); // Read buffering and write buffering can't both be active Debug.Assert((_readPos == 0 && _readLength == 0) || _writePos == 0); } /// <summary>Validates that we're ready to read from the stream.</summary> private void PrepareForReading() { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (_readLength == 0 && !CanRead) throw Error.GetReadNotSupported(); AssertBufferInvariants(); } /// <summary>Gets or sets the position within the current stream</summary> public override long Position { get { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanSeek) throw Error.GetSeekNotSupported(); AssertBufferInvariants(); VerifyOSHandlePosition(); // We may have read data into our buffer from the handle, such that the handle position // is artificially further along than the consumer's view of the stream's position. // Thus, when reading, our position is really starting from the handle position negatively // offset by the number of bytes in the buffer and positively offset by the number of // bytes into that buffer we've read. When writing, both the read length and position // must be zero, and our position is just the handle position offset positive by how many // bytes we've written into the buffer. return (_filePosition - _readLength) + _readPos + _writePos; } set { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); Seek(value, SeekOrigin.Begin); } } internal virtual bool IsClosed => _fileHandle.IsClosed; /// <summary> /// Gets the array used for buffering reading and writing. /// If the array hasn't been allocated, this will lazily allocate it. /// </summary> /// <returns>The buffer.</returns> private byte[] GetBuffer() { Debug.Assert(_buffer == null || _buffer.Length == _bufferLength); if (_buffer == null) { _buffer = new byte[_bufferLength]; OnBufferAllocated(); } return _buffer; } partial void OnBufferAllocated(); /// <summary> /// Flushes the internal read/write buffer for this stream. If write data has been buffered, /// that data is written out to the underlying file. Or if data has been buffered for /// reading from the stream, the data is dumped and our position in the underlying file /// is rewound as necessary. This does not flush the OS buffer. /// </summary> private void FlushInternalBuffer() { AssertBufferInvariants(); if (_writePos > 0) { FlushWriteBuffer(); } else if (_readPos < _readLength && CanSeek) { FlushReadBuffer(); } } /// <summary>Dumps any read data in the buffer and rewinds our position in the stream, accordingly, as necessary.</summary> private void FlushReadBuffer() { // Reading is done by blocks from the file, but someone could read // 1 byte from the buffer then write. At that point, the OS's file // pointer is out of sync with the stream's position. All write // functions should call this function to preserve the position in the file. AssertBufferInvariants(); Debug.Assert(_writePos == 0, "FileStream: Write buffer must be empty in FlushReadBuffer!"); int rewind = _readPos - _readLength; if (rewind != 0) { Debug.Assert(CanSeek, "FileStream will lose buffered read data now."); SeekCore(rewind, SeekOrigin.Current); } _readPos = _readLength = 0; } private int ReadByteCore() { PrepareForReading(); byte[] buffer = GetBuffer(); if (_readPos == _readLength) { FlushWriteBuffer(); Debug.Assert(_bufferLength > 0, "_bufferSize > 0"); _readLength = ReadNative(buffer, 0, _bufferLength); _readPos = 0; if (_readLength == 0) { return -1; } } return buffer[_readPos++]; } private void WriteByteCore(byte value) { PrepareForWriting(); // Flush the write buffer if it's full if (_writePos == _bufferLength) FlushWriteBuffer(); // We now have space in the buffer. Store the byte. GetBuffer()[_writePos++] = value; } /// <summary> /// Validates that we're ready to write to the stream, /// including flushing a read buffer if necessary. /// </summary> private void PrepareForWriting() { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); // Make sure we're good to write. We only need to do this if there's nothing already // in our write buffer, since if there is something in the buffer, we've already done // this checking and flushing. if (_writePos == 0) { if (!CanWrite) throw Error.GetWriteNotSupported(); FlushReadBuffer(); Debug.Assert(_bufferLength > 0, "_bufferSize > 0"); } } ~FileStream() { // Preserved for compatibility since FileStream has defined a // finalizer in past releases and derived classes may depend // on Dispose(false) call. Dispose(false); } } }
// 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 GeneratedInterconnectAttachmentsClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<InterconnectAttachments.InterconnectAttachmentsClient> mockGrpcClient = new moq::Mock<InterconnectAttachments.InterconnectAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInterconnectAttachmentRequest request = new GetInterconnectAttachmentRequest { Region = "regionedb20d96", Project = "projectaa6ff846", InterconnectAttachment = "interconnect_attachmentc83a7a7c", }; InterconnectAttachment expectedResponse = new InterconnectAttachment { Id = 11672635353343658936UL, Mtu = 1280318054, Kind = "kindf7aa39d9", Name = "name1c9368b0", Type = InterconnectAttachment.Types.Type.PartnerProvider, CreationTimestamp = "creation_timestamp235e59a1", DataplaneVersion = -763719012, PartnerMetadata = new InterconnectAttachmentPartnerMetadata(), EdgeAvailabilityDomain = InterconnectAttachment.Types.EdgeAvailabilityDomain.AvailabilityDomain1, Encryption = InterconnectAttachment.Types.Encryption.None, State = InterconnectAttachment.Types.State.Unspecified, VlanTag8021Q = 1290733749, Region = "regionedb20d96", Router = "routerd55c39f3", Bandwidth = InterconnectAttachment.Types.Bandwidth.Bps500M, OperationalStatus = InterconnectAttachment.Types.OperationalStatus.UndefinedOperationalStatus, Interconnect = "interconnect253e8bf5", PrivateInterconnectInfo = new InterconnectAttachmentPrivateInfo(), CandidateSubnets = { "candidate_subnets3377adaa", }, CloudRouterIpAddress = "cloud_router_ip_address62b476a9", CustomerRouterIpAddress = "customer_router_ip_address819aa186", IpsecInternalAddresses = { "ipsec_internal_addresses8b47c5bb", }, Description = "description2cf9da67", PartnerAsn = 6862354938501622805L, PairingKey = "pairing_keyfe878c44", AdminEnabled = true, SelfLink = "self_link7e87f12d", SatisfiesPzs = false, GoogleReferenceId = "google_reference_id815b6ab4", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InterconnectAttachmentsClient client = new InterconnectAttachmentsClientImpl(mockGrpcClient.Object, null); InterconnectAttachment response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<InterconnectAttachments.InterconnectAttachmentsClient> mockGrpcClient = new moq::Mock<InterconnectAttachments.InterconnectAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInterconnectAttachmentRequest request = new GetInterconnectAttachmentRequest { Region = "regionedb20d96", Project = "projectaa6ff846", InterconnectAttachment = "interconnect_attachmentc83a7a7c", }; InterconnectAttachment expectedResponse = new InterconnectAttachment { Id = 11672635353343658936UL, Mtu = 1280318054, Kind = "kindf7aa39d9", Name = "name1c9368b0", Type = InterconnectAttachment.Types.Type.PartnerProvider, CreationTimestamp = "creation_timestamp235e59a1", DataplaneVersion = -763719012, PartnerMetadata = new InterconnectAttachmentPartnerMetadata(), EdgeAvailabilityDomain = InterconnectAttachment.Types.EdgeAvailabilityDomain.AvailabilityDomain1, Encryption = InterconnectAttachment.Types.Encryption.None, State = InterconnectAttachment.Types.State.Unspecified, VlanTag8021Q = 1290733749, Region = "regionedb20d96", Router = "routerd55c39f3", Bandwidth = InterconnectAttachment.Types.Bandwidth.Bps500M, OperationalStatus = InterconnectAttachment.Types.OperationalStatus.UndefinedOperationalStatus, Interconnect = "interconnect253e8bf5", PrivateInterconnectInfo = new InterconnectAttachmentPrivateInfo(), CandidateSubnets = { "candidate_subnets3377adaa", }, CloudRouterIpAddress = "cloud_router_ip_address62b476a9", CustomerRouterIpAddress = "customer_router_ip_address819aa186", IpsecInternalAddresses = { "ipsec_internal_addresses8b47c5bb", }, Description = "description2cf9da67", PartnerAsn = 6862354938501622805L, PairingKey = "pairing_keyfe878c44", AdminEnabled = true, SelfLink = "self_link7e87f12d", SatisfiesPzs = false, GoogleReferenceId = "google_reference_id815b6ab4", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InterconnectAttachment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InterconnectAttachmentsClient client = new InterconnectAttachmentsClientImpl(mockGrpcClient.Object, null); InterconnectAttachment responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); InterconnectAttachment responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<InterconnectAttachments.InterconnectAttachmentsClient> mockGrpcClient = new moq::Mock<InterconnectAttachments.InterconnectAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInterconnectAttachmentRequest request = new GetInterconnectAttachmentRequest { Region = "regionedb20d96", Project = "projectaa6ff846", InterconnectAttachment = "interconnect_attachmentc83a7a7c", }; InterconnectAttachment expectedResponse = new InterconnectAttachment { Id = 11672635353343658936UL, Mtu = 1280318054, Kind = "kindf7aa39d9", Name = "name1c9368b0", Type = InterconnectAttachment.Types.Type.PartnerProvider, CreationTimestamp = "creation_timestamp235e59a1", DataplaneVersion = -763719012, PartnerMetadata = new InterconnectAttachmentPartnerMetadata(), EdgeAvailabilityDomain = InterconnectAttachment.Types.EdgeAvailabilityDomain.AvailabilityDomain1, Encryption = InterconnectAttachment.Types.Encryption.None, State = InterconnectAttachment.Types.State.Unspecified, VlanTag8021Q = 1290733749, Region = "regionedb20d96", Router = "routerd55c39f3", Bandwidth = InterconnectAttachment.Types.Bandwidth.Bps500M, OperationalStatus = InterconnectAttachment.Types.OperationalStatus.UndefinedOperationalStatus, Interconnect = "interconnect253e8bf5", PrivateInterconnectInfo = new InterconnectAttachmentPrivateInfo(), CandidateSubnets = { "candidate_subnets3377adaa", }, CloudRouterIpAddress = "cloud_router_ip_address62b476a9", CustomerRouterIpAddress = "customer_router_ip_address819aa186", IpsecInternalAddresses = { "ipsec_internal_addresses8b47c5bb", }, Description = "description2cf9da67", PartnerAsn = 6862354938501622805L, PairingKey = "pairing_keyfe878c44", AdminEnabled = true, SelfLink = "self_link7e87f12d", SatisfiesPzs = false, GoogleReferenceId = "google_reference_id815b6ab4", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InterconnectAttachmentsClient client = new InterconnectAttachmentsClientImpl(mockGrpcClient.Object, null); InterconnectAttachment response = client.Get(request.Project, request.Region, request.InterconnectAttachment); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<InterconnectAttachments.InterconnectAttachmentsClient> mockGrpcClient = new moq::Mock<InterconnectAttachments.InterconnectAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInterconnectAttachmentRequest request = new GetInterconnectAttachmentRequest { Region = "regionedb20d96", Project = "projectaa6ff846", InterconnectAttachment = "interconnect_attachmentc83a7a7c", }; InterconnectAttachment expectedResponse = new InterconnectAttachment { Id = 11672635353343658936UL, Mtu = 1280318054, Kind = "kindf7aa39d9", Name = "name1c9368b0", Type = InterconnectAttachment.Types.Type.PartnerProvider, CreationTimestamp = "creation_timestamp235e59a1", DataplaneVersion = -763719012, PartnerMetadata = new InterconnectAttachmentPartnerMetadata(), EdgeAvailabilityDomain = InterconnectAttachment.Types.EdgeAvailabilityDomain.AvailabilityDomain1, Encryption = InterconnectAttachment.Types.Encryption.None, State = InterconnectAttachment.Types.State.Unspecified, VlanTag8021Q = 1290733749, Region = "regionedb20d96", Router = "routerd55c39f3", Bandwidth = InterconnectAttachment.Types.Bandwidth.Bps500M, OperationalStatus = InterconnectAttachment.Types.OperationalStatus.UndefinedOperationalStatus, Interconnect = "interconnect253e8bf5", PrivateInterconnectInfo = new InterconnectAttachmentPrivateInfo(), CandidateSubnets = { "candidate_subnets3377adaa", }, CloudRouterIpAddress = "cloud_router_ip_address62b476a9", CustomerRouterIpAddress = "customer_router_ip_address819aa186", IpsecInternalAddresses = { "ipsec_internal_addresses8b47c5bb", }, Description = "description2cf9da67", PartnerAsn = 6862354938501622805L, PairingKey = "pairing_keyfe878c44", AdminEnabled = true, SelfLink = "self_link7e87f12d", SatisfiesPzs = false, GoogleReferenceId = "google_reference_id815b6ab4", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InterconnectAttachment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InterconnectAttachmentsClient client = new InterconnectAttachmentsClientImpl(mockGrpcClient.Object, null); InterconnectAttachment responseCallSettings = await client.GetAsync(request.Project, request.Region, request.InterconnectAttachment, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); InterconnectAttachment responseCancellationToken = await client.GetAsync(request.Project, request.Region, request.InterconnectAttachment, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure.Core; using Azure.Core.Pipeline; using Azure.Communication.Pipeline; using Azure.Communication.Sms.Models; namespace Azure.Communication.Sms { /// <summary> /// The Azure Communication Services SMS client. /// </summary> public class SmsClient { private readonly ClientDiagnostics _clientDiagnostics; internal SmsRestClient RestClient { get; } #region public constructors - all arguments need null check /// <summary> Initializes a new instance of <see cref="SmsClient"/>.</summary> /// <param name="connectionString">Connection string acquired from the Azure Communication Services resource.</param> public SmsClient(string connectionString) : this( ConnectionString.Parse(AssertNotNullOrEmpty(connectionString, nameof(connectionString))), new SmsClientOptions()) { } /// <summary> Initializes a new instance of <see cref="SmsClient"/>.</summary> /// <param name="connectionString">Connection string acquired from the Azure Communication Services resource.</param> /// <param name="options">Client option exposing <see cref="ClientOptions.Diagnostics"/>, <see cref="ClientOptions.Retry"/>, <see cref="ClientOptions.Transport"/>, etc.</param> public SmsClient(string connectionString, SmsClientOptions options) : this( ConnectionString.Parse(AssertNotNullOrEmpty(connectionString, nameof(connectionString))), options ?? new SmsClientOptions()) { } /// <summary> Initializes a new instance of <see cref="SmsClient"/>.</summary> /// <param name="endpoint">The URI of the Azure Communication Services resource.</param> /// <param name="keyCredential">The <see cref="AzureKeyCredential"/> used to authenticate requests.</param> /// <param name="options">Client option exposing <see cref="ClientOptions.Diagnostics"/>, <see cref="ClientOptions.Retry"/>, <see cref="ClientOptions.Transport"/>, etc.</param> public SmsClient(Uri endpoint, AzureKeyCredential keyCredential, SmsClientOptions options = default) : this( AssertNotNull(endpoint, nameof(endpoint)).AbsoluteUri, AssertNotNull(keyCredential, nameof(keyCredential)), options ?? new SmsClientOptions()) { } /// <summary> Initializes a new instance of <see cref="SmsClient"/>.</summary> /// <param name="endpoint">The URI of the Azure Communication Services resource.</param> /// <param name="tokenCredential">The TokenCredential used to authenticate requests, such as DefaultAzureCredential.</param> /// <param name="options">Client option exposing <see cref="ClientOptions.Diagnostics"/>, <see cref="ClientOptions.Retry"/>, <see cref="ClientOptions.Transport"/>, etc.</param> public SmsClient(Uri endpoint, TokenCredential tokenCredential, SmsClientOptions options = default) : this( AssertNotNull(endpoint, nameof(endpoint)).AbsoluteUri, AssertNotNull(tokenCredential, nameof(tokenCredential)), options ?? new SmsClientOptions()) { } #endregion #region private constructors private SmsClient(ConnectionString connectionString, SmsClientOptions options) : this(connectionString.GetRequired("endpoint"), options.BuildHttpPipeline(connectionString), options) { } private SmsClient(string endpoint, TokenCredential tokenCredential, SmsClientOptions options) : this(endpoint, options.BuildHttpPipeline(tokenCredential), options) { } private SmsClient(string endpoint, AzureKeyCredential keyCredential, SmsClientOptions options) : this(endpoint, options.BuildHttpPipeline(keyCredential), options) { } private SmsClient(string endpoint, HttpPipeline httpPipeline, SmsClientOptions options) { _clientDiagnostics = new ClientDiagnostics(options); RestClient = new SmsRestClient(_clientDiagnostics, httpPipeline, endpoint, options.ApiVersion); } #endregion /// <summary>Initializes a new instance of <see cref="SmsClient"/> for mocking.</summary> protected SmsClient() { _clientDiagnostics = null; RestClient = null; } /// <summary> /// Sends a SMS <paramref name="from"/> a phone number that is acquired by the authenticated account, <paramref name="to"/> another phone number. /// </summary> /// <param name="from">The sender's phone number that is owned by the authenticated account.</param> /// <param name="to">The recipient's phone number.</param> /// <param name="message">The contents of the message that will be sent to the recipient. The allowable content is defined by RFC 5724. If the message has more than 160 characters, the server will split it into multiple SMSs automatically.</param> /// <param name="options">Optional configuration for sending SMS messages.</param> /// <param name="cancellationToken">The cancellation token for the task.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <exception cref="ArgumentNullException"><paramref name="from"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="to"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="message"/> is null.</exception> public virtual async Task<Response<SmsSendResult>> SendAsync(string from, string to, string message, SmsSendOptions options = default, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(from, nameof(from)); Argument.AssertNotNullOrEmpty(to, nameof(to)); Response<IReadOnlyList<SmsSendResult>> response = await SendAsync(from, new[] { to }, message, options, cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value[0], response.GetRawResponse()); } /// <summary> /// Sends a SMS <paramref name="from"/> a phone number that is acquired by the authenticated account, <paramref name="to"/> another phone number. /// </summary> /// <param name="from">The sender's phone number that is owned by the authenticated account.</param> /// <param name="to">The recipient's phone number.</param> /// <param name="message">The contents of the message that will be sent to the recipient. The allowable content is defined by RFC 5724. If the message has more than 160 characters, the server will split it into multiple SMSs automatically.</param> /// <param name="options">Optional configuration for sending SMS messages.</param> /// <param name="cancellationToken">The cancellation token for the underlying request.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <exception cref="ArgumentNullException"><paramref name="from"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="to"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="message"/> is null.</exception> public virtual Response<SmsSendResult> Send(string from, string to, string message, SmsSendOptions options = default, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(from, nameof(from)); Argument.AssertNotNullOrEmpty(to, nameof(to)); Response<IReadOnlyList<SmsSendResult>> response = Send(from, new[] { to }, message, options, cancellationToken); return Response.FromValue(response.Value[0], response.GetRawResponse()); } /// <summary> Sends an SMS message from a phone number that belongs to the authenticated account. </summary> /// <param name="from"> The sender&apos;s phone number in E.164 format that is owned by the authenticated account. </param> /// <param name="to"> The recipient&apos;s phone number in E.164 format. In this version, up to 100 recipients in the list is supported. </param> /// <param name="message"> The contents of the message that will be sent to the recipient. The allowable content is defined by RFC 5724. </param> /// <param name="options"> Optional configuration for sending SMS messages. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <exception cref="ArgumentNullException"><paramref name="from"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="to"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="message"/> is null.</exception> public virtual async Task<Response<IReadOnlyList<SmsSendResult>>> SendAsync(string from, IEnumerable<string> to, string message, SmsSendOptions options = default, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(SmsClient)}.{nameof(Send)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(from, nameof(from)); Argument.AssertNotNullOrEmpty(to, nameof(to)); IEnumerable<SmsRecipient> recipients = to.Select(x => new SmsRecipient(AssertNotNullOrEmpty(x, nameof(to))) { RepeatabilityRequestId = Guid.NewGuid().ToString(), RepeatabilityFirstSent = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture), }); Response<SmsSendResponse> response = await RestClient.SendAsync(from, recipients, message, options, cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value.Value, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> Sends an SMS message from a phone number that belongs to the authenticated account. </summary> /// <param name="from"> The sender&apos;s phone number in E.164 format that is owned by the authenticated account. </param> /// <param name="to"> The recipient&apos;s phone number in E.164 format. In this version, up to 100 recipients in the list is supported. </param> /// <param name="message"> The contents of the message that will be sent to the recipient. The allowable content is defined by RFC 5724. </param> /// <param name="options"> Optional configuration for sending SMS messages. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <exception cref="ArgumentNullException"><paramref name="from"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="to"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="message"/> is null.</exception> public virtual Response<IReadOnlyList<SmsSendResult>> Send(string from, IEnumerable<string> to, string message, SmsSendOptions options = default, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(SmsClient)}.{nameof(Send)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(from, nameof(from)); Argument.AssertNotNullOrEmpty(to, nameof(to)); IEnumerable<SmsRecipient> recipients = to.Select(x => new SmsRecipient(AssertNotNullOrEmpty(x, nameof(to))) { RepeatabilityRequestId = Guid.NewGuid().ToString(), RepeatabilityFirstSent = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture), }); Response<SmsSendResponse> response = RestClient.Send(from, recipients, message, options, cancellationToken); return Response.FromValue(response.Value.Value, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } private static T AssertNotNull<T>(T argument, string argumentName) where T : class { Argument.AssertNotNull(argument, argumentName); return argument; } private static string AssertNotNullOrEmpty(string argument, string argumentName) { Argument.AssertNotNullOrEmpty(argument, argumentName); return argument; } } }
// 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.Configuration; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.CompilerServices; using System.Xml; using System.Xml.Serialization.Configuration; using System.Security; using System.Text.RegularExpressions; using System.Xml.Extensions; namespace System.Xml.Serialization { internal class CodeGenerator { internal static BindingFlags InstancePublicBindingFlags = BindingFlags.Instance | BindingFlags.Public; internal static BindingFlags InstanceBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; internal static BindingFlags StaticBindingFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; internal static MethodAttributes PublicMethodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig; internal static MethodAttributes PublicOverrideMethodAttributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig; internal static MethodAttributes ProtectedOverrideMethodAttributes = MethodAttributes.Family | MethodAttributes.Virtual | MethodAttributes.HideBySig; internal static MethodAttributes PrivateMethodAttributes = MethodAttributes.Private | MethodAttributes.HideBySig; private readonly TypeBuilder _typeBuilder; private MethodBuilder _methodBuilder; private ILGenerator _ilGen; private Dictionary<string, ArgBuilder> _argList; private LocalScope _currentScope; // Stores a queue of free locals available in the context of the method, keyed by // type and name of the local private Dictionary<Tuple<Type, string>, Queue<LocalBuilder>> _freeLocals; private Stack<object> _blockStack; private Label _methodEndLabel; internal CodeGenerator(TypeBuilder typeBuilder) { System.Diagnostics.Debug.Assert(typeBuilder != null); _typeBuilder = typeBuilder; } internal static bool IsNullableGenericType(Type type) { return type.Name == "Nullable`1"; } internal static void AssertHasInterface(Type type, Type iType) { #if DEBUG Debug.Assert(iType.IsInterface); foreach (Type iFace in type.GetInterfaces()) { if (iFace == iType) return; } Debug.Fail("Interface not found"); #endif } internal void BeginMethod(Type returnType, string methodName, Type[] argTypes, string[] argNames, MethodAttributes methodAttributes) { _methodBuilder = _typeBuilder.DefineMethod(methodName, methodAttributes, returnType, argTypes); _ilGen = _methodBuilder.GetILGenerator(); InitILGeneration(argTypes, argNames, (_methodBuilder.Attributes & MethodAttributes.Static) == MethodAttributes.Static); } internal void BeginMethod(Type returnType, MethodBuilderInfo methodBuilderInfo, Type[] argTypes, string[] argNames, MethodAttributes methodAttributes) { #if DEBUG methodBuilderInfo.Validate(returnType, argTypes, methodAttributes); #endif _methodBuilder = methodBuilderInfo.MethodBuilder; _ilGen = _methodBuilder.GetILGenerator(); InitILGeneration(argTypes, argNames, (_methodBuilder.Attributes & MethodAttributes.Static) == MethodAttributes.Static); } private void InitILGeneration(Type[] argTypes, string[] argNames, bool isStatic) { _methodEndLabel = _ilGen.DefineLabel(); this.retLabel = _ilGen.DefineLabel(); _blockStack = new Stack<object>(); _whileStack = new Stack<WhileState>(); _currentScope = new LocalScope(); _freeLocals = new Dictionary<Tuple<Type, string>, Queue<LocalBuilder>>(); _argList = new Dictionary<string, ArgBuilder>(); // this ptr is arg 0 for non static, assuming ref type (not value type) if (!isStatic) _argList.Add("this", new ArgBuilder("this", 0, _typeBuilder.BaseType)); for (int i = 0; i < argTypes.Length; i++) { ArgBuilder arg = new ArgBuilder(argNames[i], _argList.Count, argTypes[i]); _argList.Add(arg.Name, arg); _methodBuilder.DefineParameter(arg.Index, ParameterAttributes.None, arg.Name); } } internal MethodBuilder EndMethod() { MarkLabel(_methodEndLabel); Ret(); MethodBuilder retVal = null; retVal = _methodBuilder; _methodBuilder = null; _ilGen = null; _freeLocals = null; _blockStack = null; _whileStack = null; _argList = null; _currentScope = null; retLocal = null; return retVal; } internal MethodBuilder MethodBuilder { get { return _methodBuilder; } } internal ArgBuilder GetArg(string name) { System.Diagnostics.Debug.Assert(_argList != null && _argList.ContainsKey(name)); return (ArgBuilder)_argList[name]; } internal LocalBuilder GetLocal(string name) { System.Diagnostics.Debug.Assert(_currentScope != null && _currentScope.ContainsKey(name)); return _currentScope[name]; } internal LocalBuilder retLocal; internal Label retLabel; internal LocalBuilder ReturnLocal { get { if (retLocal == null) retLocal = DeclareLocal(_methodBuilder.ReturnType, "_ret"); return retLocal; } } internal Label ReturnLabel { get { return retLabel; } } private readonly Dictionary<Type, LocalBuilder> _tmpLocals = new Dictionary<Type, LocalBuilder>(); internal LocalBuilder GetTempLocal(Type type) { LocalBuilder localTmp; if (!_tmpLocals.TryGetValue(type, out localTmp)) { localTmp = DeclareLocal(type, "_tmp" + _tmpLocals.Count); _tmpLocals.Add(type, localTmp); } return localTmp; } internal Type GetVariableType(object var) { if (var is ArgBuilder) return ((ArgBuilder)var).ArgType; else if (var is LocalBuilder) return ((LocalBuilder)var).LocalType; else return var.GetType(); } internal object GetVariable(string name) { object var; if (TryGetVariable(name, out var)) return var; System.Diagnostics.Debug.Fail("Variable not found"); return null; } internal bool TryGetVariable(string name, out object variable) { LocalBuilder loc; if (_currentScope != null && _currentScope.TryGetValue(name, out loc)) { variable = loc; return true; } ArgBuilder arg; if (_argList != null && _argList.TryGetValue(name, out arg)) { variable = arg; return true; } int val; if (int.TryParse(name, out val)) { variable = val; return true; } variable = null; return false; } internal void EnterScope() { LocalScope newScope = new LocalScope(_currentScope); _currentScope = newScope; } internal void ExitScope() { Debug.Assert(_currentScope.parent != null); _currentScope.AddToFreeLocals(_freeLocals); _currentScope = _currentScope.parent; } private bool TryDequeueLocal(Type type, string name, out LocalBuilder local) { // This method can only be called between BeginMethod and EndMethod (i.e. // while we are emitting code for a method Debug.Assert(_freeLocals != null); Queue<LocalBuilder> freeLocalQueue; Tuple<Type, string> key = new Tuple<Type, string>(type, name); if (_freeLocals.TryGetValue(key, out freeLocalQueue)) { local = freeLocalQueue.Dequeue(); // If the queue is empty, remove this key from the dictionary // of free locals if (freeLocalQueue.Count == 0) { _freeLocals.Remove(key); } return true; } local = null; return false; } internal LocalBuilder DeclareLocal(Type type, string name) { Debug.Assert(!_currentScope.ContainsKey(name)); LocalBuilder local; if (!TryDequeueLocal(type, name, out local)) { local = _ilGen.DeclareLocal(type, false); } _currentScope[name] = local; return local; } internal LocalBuilder DeclareOrGetLocal(Type type, string name) { LocalBuilder local; if (!_currentScope.TryGetValue(name, out local)) local = DeclareLocal(type, name); else Debug.Assert(local.LocalType == type); return local; } internal object For(LocalBuilder local, object start, object end) { ForState forState = new ForState(local, DefineLabel(), DefineLabel(), end); if (forState.Index != null) { Load(start); Stloc(forState.Index); Br(forState.TestLabel); } MarkLabel(forState.BeginLabel); _blockStack.Push(forState); return forState; } internal void EndFor() { object stackTop = _blockStack.Pop(); ForState forState = stackTop as ForState; Debug.Assert(forState != null); if (forState.Index != null) { Ldloc(forState.Index); Ldc(1); Add(); Stloc(forState.Index); MarkLabel(forState.TestLabel); Ldloc(forState.Index); Load(forState.End); Type varType = GetVariableType(forState.End); if (varType.IsArray) { Ldlen(); } else { #if DEBUG CodeGenerator.AssertHasInterface(varType, typeof(ICollection)); #endif MethodInfo ICollection_get_Count = typeof(ICollection).GetMethod( "get_Count", CodeGenerator.InstanceBindingFlags, Array.Empty<Type>() ); Call(ICollection_get_Count); } Blt(forState.BeginLabel); } else Br(forState.BeginLabel); } internal void If() { InternalIf(false); } internal void IfNot() { InternalIf(true); } private static readonly OpCode[] s_branchCodes = new OpCode[] { OpCodes.Bge, OpCodes.Bne_Un, OpCodes.Bgt, OpCodes.Ble, OpCodes.Beq, OpCodes.Blt, }; private OpCode GetBranchCode(Cmp cmp) { return s_branchCodes[(int)cmp]; } internal void If(Cmp cmpOp) { IfState ifState = new IfState(); ifState.EndIf = DefineLabel(); ifState.ElseBegin = DefineLabel(); _ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin); _blockStack.Push(ifState); } internal void If(object value1, Cmp cmpOp, object value2) { Load(value1); Load(value2); If(cmpOp); } internal void Else() { IfState ifState = PopIfState(); Br(ifState.EndIf); MarkLabel(ifState.ElseBegin); ifState.ElseBegin = ifState.EndIf; _blockStack.Push(ifState); } internal void EndIf() { IfState ifState = PopIfState(); if (!ifState.ElseBegin.Equals(ifState.EndIf)) MarkLabel(ifState.ElseBegin); MarkLabel(ifState.EndIf); } private readonly Stack<Label> _leaveLabels = new Stack<Label>(); internal void BeginExceptionBlock() { _leaveLabels.Push(DefineLabel()); _ilGen.BeginExceptionBlock(); } internal void BeginCatchBlock(Type exception) { _ilGen.BeginCatchBlock(exception); } internal void EndExceptionBlock() { _ilGen.EndExceptionBlock(); _ilGen.MarkLabel(_leaveLabels.Pop()); } internal void Leave() { _ilGen.Emit(OpCodes.Leave, _leaveLabels.Peek()); } internal void Call(MethodInfo methodInfo) { Debug.Assert(methodInfo != null); if (methodInfo.IsVirtual && !methodInfo.DeclaringType.IsValueType) _ilGen.Emit(OpCodes.Callvirt, methodInfo); else _ilGen.Emit(OpCodes.Call, methodInfo); } internal void Call(ConstructorInfo ctor) { Debug.Assert(ctor != null); _ilGen.Emit(OpCodes.Call, ctor); } internal void New(ConstructorInfo constructorInfo) { Debug.Assert(constructorInfo != null); _ilGen.Emit(OpCodes.Newobj, constructorInfo); } internal void InitObj(Type valueType) { _ilGen.Emit(OpCodes.Initobj, valueType); } internal void NewArray(Type elementType, object len) { Load(len); _ilGen.Emit(OpCodes.Newarr, elementType); } internal void LoadArrayElement(object obj, object arrayIndex) { Type objType = GetVariableType(obj).GetElementType(); Load(obj); Load(arrayIndex); if (IsStruct(objType)) { Ldelema(objType); Ldobj(objType); } else Ldelem(objType); } internal void StoreArrayElement(object obj, object arrayIndex, object value) { Type arrayType = GetVariableType(obj); if (arrayType == typeof(Array)) { Load(obj); Call(typeof(Array).GetMethod("SetValue", new Type[] { typeof(object), typeof(int) })); } else { Type objType = arrayType.GetElementType(); Load(obj); Load(arrayIndex); if (IsStruct(objType)) Ldelema(objType); Load(value); ConvertValue(GetVariableType(value), objType); if (IsStruct(objType)) Stobj(objType); else Stelem(objType); } } private static bool IsStruct(Type objType) { return objType.IsValueType && !objType.IsPrimitive; } internal Type LoadMember(object obj, MemberInfo memberInfo) { if (GetVariableType(obj).IsValueType) LoadAddress(obj); else Load(obj); return LoadMember(memberInfo); } private static MethodInfo GetPropertyMethodFromBaseType(PropertyInfo propertyInfo, bool isGetter) { // we only invoke this when the propertyInfo does not have a GET or SET method on it Type currentType = propertyInfo.DeclaringType.BaseType; PropertyInfo currentProperty; string propertyName = propertyInfo.Name; MethodInfo result = null; while (currentType != null) { currentProperty = currentType.GetProperty(propertyName); if (currentProperty != null) { if (isGetter) { result = currentProperty.GetMethod; } else { result = currentProperty.SetMethod; } if (result != null) { // we found the GetMethod/SetMethod on the type closest to the current declaring type break; } } // keep looking at the base type like compiler does currentType = currentType.BaseType; } return result; } internal Type LoadMember(MemberInfo memberInfo) { Type memberType = null; if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; memberType = fieldInfo.FieldType; if (fieldInfo.IsStatic) { _ilGen.Emit(OpCodes.Ldsfld, fieldInfo); } else { _ilGen.Emit(OpCodes.Ldfld, fieldInfo); } } else { System.Diagnostics.Debug.Assert(memberInfo is PropertyInfo); PropertyInfo property = (PropertyInfo)memberInfo; memberType = property.PropertyType; if (property != null) { MethodInfo getMethod = property.GetMethod; if (getMethod == null) { getMethod = GetPropertyMethodFromBaseType(property, true); } System.Diagnostics.Debug.Assert(getMethod != null); Call(getMethod); } } return memberType; } internal Type LoadMemberAddress(MemberInfo memberInfo) { Type memberType = null; if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; memberType = fieldInfo.FieldType; if (fieldInfo.IsStatic) { _ilGen.Emit(OpCodes.Ldsflda, fieldInfo); } else { _ilGen.Emit(OpCodes.Ldflda, fieldInfo); } } else { System.Diagnostics.Debug.Assert(memberInfo is PropertyInfo); PropertyInfo property = (PropertyInfo)memberInfo; memberType = property.PropertyType; if (property != null) { MethodInfo getMethod = property.GetMethod; if (getMethod == null) { getMethod = GetPropertyMethodFromBaseType(property, true); } System.Diagnostics.Debug.Assert(getMethod != null); Call(getMethod); LocalBuilder tmpLoc = GetTempLocal(memberType); Stloc(tmpLoc); Ldloca(tmpLoc); } } return memberType; } internal void StoreMember(MemberInfo memberInfo) { if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; if (fieldInfo.IsStatic) { _ilGen.Emit(OpCodes.Stsfld, fieldInfo); } else { _ilGen.Emit(OpCodes.Stfld, fieldInfo); } } else { System.Diagnostics.Debug.Assert(memberInfo is PropertyInfo); PropertyInfo property = (PropertyInfo)memberInfo; if (property != null) { MethodInfo setMethod = property.SetMethod; if (setMethod == null) { setMethod = GetPropertyMethodFromBaseType(property, false); } System.Diagnostics.Debug.Assert(setMethod != null); Call(setMethod); } } } internal void Load(object obj) { if (obj == null) _ilGen.Emit(OpCodes.Ldnull); else if (obj is ArgBuilder) Ldarg((ArgBuilder)obj); else if (obj is LocalBuilder) Ldloc((LocalBuilder)obj); else Ldc(obj); } internal void LoadAddress(object obj) { if (obj is ArgBuilder) LdargAddress((ArgBuilder)obj); else if (obj is LocalBuilder) LdlocAddress((LocalBuilder)obj); else Load(obj); } internal void ConvertAddress(Type source, Type target) { InternalConvert(source, target, true); } internal void ConvertValue(Type source, Type target) { InternalConvert(source, target, false); } internal void Castclass(Type target) { _ilGen.Emit(OpCodes.Castclass, target); } internal void Box(Type type) { _ilGen.Emit(OpCodes.Box, type); } internal void Unbox(Type type) { _ilGen.Emit(OpCodes.Unbox, type); } private static readonly OpCode[] s_ldindOpCodes = new OpCode[] { OpCodes.Nop, //Empty = 0, OpCodes.Nop, //Object = 1, OpCodes.Nop, //DBNull = 2, OpCodes.Ldind_I1, //Boolean = 3, OpCodes.Ldind_I2, //Char = 4, OpCodes.Ldind_I1, //SByte = 5, OpCodes.Ldind_U1, //Byte = 6, OpCodes.Ldind_I2, //Int16 = 7, OpCodes.Ldind_U2, //UInt16 = 8, OpCodes.Ldind_I4, //Int32 = 9, OpCodes.Ldind_U4, //UInt32 = 10, OpCodes.Ldind_I8, //Int64 = 11, OpCodes.Ldind_I8, //UInt64 = 12, OpCodes.Ldind_R4, //Single = 13, OpCodes.Ldind_R8, //Double = 14, OpCodes.Nop, //Decimal = 15, OpCodes.Nop, //DateTime = 16, OpCodes.Nop, //17 OpCodes.Ldind_Ref, //String = 18, }; private OpCode GetLdindOpCode(TypeCode typeCode) { return s_ldindOpCodes[(int)typeCode]; } internal void Ldobj(Type type) { OpCode opCode = GetLdindOpCode(type.GetTypeCode()); if (!opCode.Equals(OpCodes.Nop)) { _ilGen.Emit(opCode); } else { _ilGen.Emit(OpCodes.Ldobj, type); } } internal void Stobj(Type type) { _ilGen.Emit(OpCodes.Stobj, type); } internal void Ceq() { _ilGen.Emit(OpCodes.Ceq); } internal void Clt() { _ilGen.Emit(OpCodes.Clt); } internal void Cne() { Ceq(); Ldc(0); Ceq(); } internal void Ble(Label label) { _ilGen.Emit(OpCodes.Ble, label); } internal void Throw() { _ilGen.Emit(OpCodes.Throw); } internal void Ldtoken(Type t) { _ilGen.Emit(OpCodes.Ldtoken, t); } internal void Ldc(object o) { Type valueType = o.GetType(); if (o is Type) { Ldtoken((Type)o); Call(typeof(Type).GetMethod("GetTypeFromHandle", BindingFlags.Static | BindingFlags.Public, new Type[] { typeof(RuntimeTypeHandle) })); } else if (valueType.IsEnum) { Ldc(Convert.ChangeType(o, Enum.GetUnderlyingType(valueType), null)); } else { switch (valueType.GetTypeCode()) { case TypeCode.Boolean: Ldc((bool)o); break; case TypeCode.Char: Debug.Fail("Char is not a valid schema primitive and should be treated as int in DataContract"); throw new NotSupportedException(SR.XmlInvalidCharSchemaPrimitive); case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: Ldc(Convert.ToInt32(o, CultureInfo.InvariantCulture)); break; case TypeCode.Int32: Ldc((int)o); break; case TypeCode.UInt32: Ldc((int)(uint)o); break; case TypeCode.UInt64: Ldc((long)(ulong)o); break; case TypeCode.Int64: Ldc((long)o); break; case TypeCode.Single: Ldc((float)o); break; case TypeCode.Double: Ldc((double)o); break; case TypeCode.String: Ldstr((string)o); break; case TypeCode.Decimal: ConstructorInfo Decimal_ctor = typeof(decimal).GetConstructor( CodeGenerator.InstanceBindingFlags, new Type[] { typeof(int), typeof(int), typeof(int), typeof(bool), typeof(byte) } ); int[] bits = decimal.GetBits((decimal)o); Ldc(bits[0]); // digit Ldc(bits[1]); // digit Ldc(bits[2]); // digit Ldc((bits[3] & 0x80000000) == 0x80000000); // sign Ldc((byte)((bits[3] >> 16) & 0xFF)); // decimal location New(Decimal_ctor); break; case TypeCode.DateTime: ConstructorInfo DateTime_ctor = typeof(DateTime).GetConstructor( CodeGenerator.InstanceBindingFlags, new Type[] { typeof(long) } ); Ldc(((DateTime)o).Ticks); // ticks New(DateTime_ctor); break; case TypeCode.Object: case TypeCode.Empty: case TypeCode.DBNull: default: if (valueType == typeof(TimeSpan)) { ConstructorInfo TimeSpan_ctor = typeof(TimeSpan).GetConstructor( CodeGenerator.InstanceBindingFlags, null, new Type[] { typeof(long) }, null ); Ldc(((TimeSpan)o).Ticks); // ticks New(TimeSpan_ctor); break; } else { throw new NotSupportedException(SR.Format(SR.UnknownConstantType, valueType.AssemblyQualifiedName)); } } } } internal void Ldc(bool boolVar) { if (boolVar) { _ilGen.Emit(OpCodes.Ldc_I4_1); } else { _ilGen.Emit(OpCodes.Ldc_I4_0); } } internal void Ldc(int intVar) { switch (intVar) { case -1: _ilGen.Emit(OpCodes.Ldc_I4_M1); break; case 0: _ilGen.Emit(OpCodes.Ldc_I4_0); break; case 1: _ilGen.Emit(OpCodes.Ldc_I4_1); break; case 2: _ilGen.Emit(OpCodes.Ldc_I4_2); break; case 3: _ilGen.Emit(OpCodes.Ldc_I4_3); break; case 4: _ilGen.Emit(OpCodes.Ldc_I4_4); break; case 5: _ilGen.Emit(OpCodes.Ldc_I4_5); break; case 6: _ilGen.Emit(OpCodes.Ldc_I4_6); break; case 7: _ilGen.Emit(OpCodes.Ldc_I4_7); break; case 8: _ilGen.Emit(OpCodes.Ldc_I4_8); break; default: _ilGen.Emit(OpCodes.Ldc_I4, intVar); break; } } internal void Ldc(long l) { _ilGen.Emit(OpCodes.Ldc_I8, l); } internal void Ldc(float f) { _ilGen.Emit(OpCodes.Ldc_R4, f); } internal void Ldc(double d) { _ilGen.Emit(OpCodes.Ldc_R8, d); } internal void Ldstr(string strVar) { if (strVar == null) _ilGen.Emit(OpCodes.Ldnull); else _ilGen.Emit(OpCodes.Ldstr, strVar); } internal void LdlocAddress(LocalBuilder localBuilder) { if (localBuilder.LocalType.IsValueType) Ldloca(localBuilder); else Ldloc(localBuilder); } internal void Ldloc(LocalBuilder localBuilder) { _ilGen.Emit(OpCodes.Ldloc, localBuilder); } internal void Ldloc(string name) { Debug.Assert(_currentScope.ContainsKey(name)); LocalBuilder local = _currentScope[name]; Ldloc(local); } internal void Stloc(Type type, string name) { LocalBuilder local = null; if (!_currentScope.TryGetValue(name, out local)) { local = DeclareLocal(type, name); } Debug.Assert(local.LocalType == type); Stloc(local); } internal void Stloc(LocalBuilder local) { _ilGen.Emit(OpCodes.Stloc, local); } internal void Ldloc(Type type, string name) { Debug.Assert(_currentScope.ContainsKey(name)); LocalBuilder local = _currentScope[name]; Debug.Assert(local.LocalType == type); Ldloc(local); } internal void Ldloca(LocalBuilder localBuilder) { _ilGen.Emit(OpCodes.Ldloca, localBuilder); } internal void LdargAddress(ArgBuilder argBuilder) { if (argBuilder.ArgType.IsValueType) Ldarga(argBuilder); else Ldarg(argBuilder); } internal void Ldarg(string arg) { Ldarg(GetArg(arg)); } internal void Ldarg(ArgBuilder arg) { Ldarg(arg.Index); } internal void Ldarg(int slot) { switch (slot) { case 0: _ilGen.Emit(OpCodes.Ldarg_0); break; case 1: _ilGen.Emit(OpCodes.Ldarg_1); break; case 2: _ilGen.Emit(OpCodes.Ldarg_2); break; case 3: _ilGen.Emit(OpCodes.Ldarg_3); break; default: if (slot <= 255) _ilGen.Emit(OpCodes.Ldarg_S, slot); else _ilGen.Emit(OpCodes.Ldarg, slot); break; } } internal void Ldarga(ArgBuilder argBuilder) { Ldarga(argBuilder.Index); } internal void Ldarga(int slot) { if (slot <= 255) _ilGen.Emit(OpCodes.Ldarga_S, slot); else _ilGen.Emit(OpCodes.Ldarga, slot); } internal void Ldlen() { _ilGen.Emit(OpCodes.Ldlen); _ilGen.Emit(OpCodes.Conv_I4); } private static readonly OpCode[] s_ldelemOpCodes = new OpCode[] { OpCodes.Nop, //Empty = 0, OpCodes.Ldelem_Ref, //Object = 1, OpCodes.Ldelem_Ref, //DBNull = 2, OpCodes.Ldelem_I1, //Boolean = 3, OpCodes.Ldelem_I2, //Char = 4, OpCodes.Ldelem_I1, //SByte = 5, OpCodes.Ldelem_U1, //Byte = 6, OpCodes.Ldelem_I2, //Int16 = 7, OpCodes.Ldelem_U2, //UInt16 = 8, OpCodes.Ldelem_I4, //Int32 = 9, OpCodes.Ldelem_U4, //UInt32 = 10, OpCodes.Ldelem_I8, //Int64 = 11, OpCodes.Ldelem_I8, //UInt64 = 12, OpCodes.Ldelem_R4, //Single = 13, OpCodes.Ldelem_R8, //Double = 14, OpCodes.Nop, //Decimal = 15, OpCodes.Nop, //DateTime = 16, OpCodes.Nop, //17 OpCodes.Ldelem_Ref, //String = 18, }; private OpCode GetLdelemOpCode(TypeCode typeCode) { return s_ldelemOpCodes[(int)typeCode]; } internal void Ldelem(Type arrayElementType) { if (arrayElementType.IsEnum) { Ldelem(Enum.GetUnderlyingType(arrayElementType)); } else { OpCode opCode = GetLdelemOpCode(arrayElementType.GetTypeCode()); Debug.Assert(!opCode.Equals(OpCodes.Nop)); if (opCode.Equals(OpCodes.Nop)) throw new InvalidOperationException(SR.Format(SR.ArrayTypeIsNotSupported, arrayElementType.AssemblyQualifiedName)); _ilGen.Emit(opCode); } } internal void Ldelema(Type arrayElementType) { OpCode opCode = OpCodes.Ldelema; _ilGen.Emit(opCode, arrayElementType); } private static readonly OpCode[] s_stelemOpCodes = new OpCode[] { OpCodes.Nop, //Empty = 0, OpCodes.Stelem_Ref, //Object = 1, OpCodes.Stelem_Ref, //DBNull = 2, OpCodes.Stelem_I1, //Boolean = 3, OpCodes.Stelem_I2, //Char = 4, OpCodes.Stelem_I1, //SByte = 5, OpCodes.Stelem_I1, //Byte = 6, OpCodes.Stelem_I2, //Int16 = 7, OpCodes.Stelem_I2, //UInt16 = 8, OpCodes.Stelem_I4, //Int32 = 9, OpCodes.Stelem_I4, //UInt32 = 10, OpCodes.Stelem_I8, //Int64 = 11, OpCodes.Stelem_I8, //UInt64 = 12, OpCodes.Stelem_R4, //Single = 13, OpCodes.Stelem_R8, //Double = 14, OpCodes.Nop, //Decimal = 15, OpCodes.Nop, //DateTime = 16, OpCodes.Nop, //17 OpCodes.Stelem_Ref, //String = 18, }; private OpCode GetStelemOpCode(TypeCode typeCode) { return s_stelemOpCodes[(int)typeCode]; } internal void Stelem(Type arrayElementType) { if (arrayElementType.IsEnum) Stelem(Enum.GetUnderlyingType(arrayElementType)); else { OpCode opCode = GetStelemOpCode(arrayElementType.GetTypeCode()); if (opCode.Equals(OpCodes.Nop)) throw new InvalidOperationException(SR.Format(SR.ArrayTypeIsNotSupported, arrayElementType.AssemblyQualifiedName)); _ilGen.Emit(opCode); } } internal Label DefineLabel() { return _ilGen.DefineLabel(); } internal void MarkLabel(Label label) { _ilGen.MarkLabel(label); } internal void Nop() { _ilGen.Emit(OpCodes.Nop); } internal void Add() { _ilGen.Emit(OpCodes.Add); } internal void Ret() { _ilGen.Emit(OpCodes.Ret); } internal void Br(Label label) { _ilGen.Emit(OpCodes.Br, label); } internal void Br_S(Label label) { _ilGen.Emit(OpCodes.Br_S, label); } internal void Blt(Label label) { _ilGen.Emit(OpCodes.Blt, label); } internal void Brfalse(Label label) { _ilGen.Emit(OpCodes.Brfalse, label); } internal void Brtrue(Label label) { _ilGen.Emit(OpCodes.Brtrue, label); } internal void Pop() { _ilGen.Emit(OpCodes.Pop); } internal void Dup() { _ilGen.Emit(OpCodes.Dup); } private void InternalIf(bool negate) { IfState ifState = new IfState(); ifState.EndIf = DefineLabel(); ifState.ElseBegin = DefineLabel(); if (negate) Brtrue(ifState.ElseBegin); else Brfalse(ifState.ElseBegin); _blockStack.Push(ifState); } private static readonly OpCode[] s_convOpCodes = new OpCode[] { OpCodes.Nop, //Empty = 0, OpCodes.Nop, //Object = 1, OpCodes.Nop, //DBNull = 2, OpCodes.Conv_I1, //Boolean = 3, OpCodes.Conv_I2, //Char = 4, OpCodes.Conv_I1, //SByte = 5, OpCodes.Conv_U1, //Byte = 6, OpCodes.Conv_I2, //Int16 = 7, OpCodes.Conv_U2, //UInt16 = 8, OpCodes.Conv_I4, //Int32 = 9, OpCodes.Conv_U4, //UInt32 = 10, OpCodes.Conv_I8, //Int64 = 11, OpCodes.Conv_U8, //UInt64 = 12, OpCodes.Conv_R4, //Single = 13, OpCodes.Conv_R8, //Double = 14, OpCodes.Nop, //Decimal = 15, OpCodes.Nop, //DateTime = 16, OpCodes.Nop, //17 OpCodes.Nop, //String = 18, }; private OpCode GetConvOpCode(TypeCode typeCode) { return s_convOpCodes[(int)typeCode]; } private void InternalConvert(Type source, Type target, bool isAddress) { if (target == source) return; if (target.IsValueType) { if (source.IsValueType) { OpCode opCode = GetConvOpCode(target.GetTypeCode()); if (opCode.Equals(OpCodes.Nop)) { throw new CodeGeneratorConversionException(source, target, isAddress, "NoConversionPossibleTo"); } else { _ilGen.Emit(opCode); } } else if (source.IsAssignableFrom(target)) { Unbox(target); if (!isAddress) Ldobj(target); } else { throw new CodeGeneratorConversionException(source, target, isAddress, "IsNotAssignableFrom"); } } else if (target.IsAssignableFrom(source)) { if (source.IsValueType) { if (isAddress) Ldobj(source); Box(source); } } else if (source.IsAssignableFrom(target)) { Castclass(target); } else if (target.IsInterface || source.IsInterface) { Castclass(target); } else { throw new CodeGeneratorConversionException(source, target, isAddress, "IsNotAssignableFrom"); } } private IfState PopIfState() { object stackTop = _blockStack.Pop(); IfState ifState = stackTop as IfState; Debug.Assert(ifState != null); return ifState; } internal static AssemblyBuilder CreateAssemblyBuilder(string name) { AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = name; assemblyName.Version = new Version(1, 0, 0, 0); return AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); } internal static ModuleBuilder CreateModuleBuilder(AssemblyBuilder assemblyBuilder, string name) { return assemblyBuilder.DefineDynamicModule(name); } internal static TypeBuilder CreateTypeBuilder(ModuleBuilder moduleBuilder, string name, TypeAttributes attributes, Type parent, Type[] interfaces) { // parent is nullable if no base class return moduleBuilder.DefineType(TempAssembly.GeneratedAssemblyNamespace + "." + name, attributes, parent, interfaces); } private int _initElseIfStack = -1; private IfState _elseIfState; internal void InitElseIf() { Debug.Assert(_initElseIfStack == -1); _elseIfState = (IfState)_blockStack.Pop(); _initElseIfStack = _blockStack.Count; Br(_elseIfState.EndIf); MarkLabel(_elseIfState.ElseBegin); } private int _initIfStack = -1; internal void InitIf() { Debug.Assert(_initIfStack == -1); _initIfStack = _blockStack.Count; } internal void AndIf(Cmp cmpOp) { if (_initIfStack == _blockStack.Count) { _initIfStack = -1; If(cmpOp); return; } if (_initElseIfStack == _blockStack.Count) { _initElseIfStack = -1; _elseIfState.ElseBegin = DefineLabel(); _ilGen.Emit(GetBranchCode(cmpOp), _elseIfState.ElseBegin); _blockStack.Push(_elseIfState); return; } Debug.Assert(_initIfStack == -1 && _initElseIfStack == -1); IfState ifState = (IfState)_blockStack.Peek(); _ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin); } internal void AndIf() { if (_initIfStack == _blockStack.Count) { _initIfStack = -1; If(); return; } if (_initElseIfStack == _blockStack.Count) { _initElseIfStack = -1; _elseIfState.ElseBegin = DefineLabel(); Brfalse(_elseIfState.ElseBegin); _blockStack.Push(_elseIfState); return; } Debug.Assert(_initIfStack == -1 && _initElseIfStack == -1); IfState ifState = (IfState)_blockStack.Peek(); Brfalse(ifState.ElseBegin); } internal void IsInst(Type type) { _ilGen.Emit(OpCodes.Isinst, type); } internal void Beq(Label label) { _ilGen.Emit(OpCodes.Beq, label); } internal void Bne(Label label) { _ilGen.Emit(OpCodes.Bne_Un, label); } internal void GotoMethodEnd() { //limit to only short forward (127 CIL instruction) //Br_S(this.methodEndLabel); Br(_methodEndLabel); } internal class WhileState { public Label StartLabel; public Label CondLabel; public Label EndLabel; public WhileState(CodeGenerator ilg) { StartLabel = ilg.DefineLabel(); CondLabel = ilg.DefineLabel(); EndLabel = ilg.DefineLabel(); } } // Usage: // WhileBegin() // WhileBreak() // WhileContinue() // WhileBeginCondition() // (bool on stack) // WhileEndCondition() // WhileEnd() private Stack<WhileState> _whileStack; internal void WhileBegin() { WhileState whileState = new WhileState(this); // ECMA-335 III.1.7.5 states that code blocks after unconditional // branch which could only be reached by backward branch are assumed // to have empty stack on the entrance. // // Since we don't have control over the current stack contents here // we have to generate conditional branch here instead of // Br(whileState.CondLabel) to make the IL verifiable. Ldc(true); Brtrue(whileState.CondLabel); MarkLabel(whileState.StartLabel); _whileStack.Push(whileState); } internal void WhileEnd() { WhileState whileState = _whileStack.Pop(); MarkLabel(whileState.EndLabel); } internal void WhileContinue() { WhileState whileState = _whileStack.Peek(); Br(whileState.CondLabel); } internal void WhileBeginCondition() { WhileState whileState = _whileStack.Peek(); // If there are two MarkLabel ILs consecutively, Labels will converge to one label. // This could cause the code to look different. We insert Nop here specifically // that the While label stands out. Nop(); MarkLabel(whileState.CondLabel); } internal void WhileEndCondition() { WhileState whileState = _whileStack.Peek(); Brtrue(whileState.StartLabel); } } internal class ArgBuilder { internal string Name; internal int Index; internal Type ArgType; internal ArgBuilder(string name, int index, Type argType) { this.Name = name; this.Index = index; this.ArgType = argType; } } internal class ForState { private readonly LocalBuilder _indexVar; private readonly Label _beginLabel; private readonly Label _testLabel; private readonly object _end; internal ForState(LocalBuilder indexVar, Label beginLabel, Label testLabel, object end) { _indexVar = indexVar; _beginLabel = beginLabel; _testLabel = testLabel; _end = end; } internal LocalBuilder Index { get { return _indexVar; } } internal Label BeginLabel { get { return _beginLabel; } } internal Label TestLabel { get { return _testLabel; } } internal object End { get { return _end; } } } internal enum Cmp : int { LessThan = 0, EqualTo, LessThanOrEqualTo, GreaterThan, NotEqualTo, GreaterThanOrEqualTo } internal class IfState { private Label _elseBegin; private Label _endIf; internal Label EndIf { get { return _endIf; } set { _endIf = value; } } internal Label ElseBegin { get { return _elseBegin; } set { _elseBegin = value; } } } internal class LocalScope { public readonly LocalScope parent; private readonly Dictionary<string, LocalBuilder> _locals; // Root scope public LocalScope() { _locals = new Dictionary<string, LocalBuilder>(); } public LocalScope(LocalScope parent) : this() { this.parent = parent; } public bool ContainsKey(string key) { return _locals.ContainsKey(key) || (parent != null && parent.ContainsKey(key)); } public bool TryGetValue(string key, out LocalBuilder value) { if (_locals.TryGetValue(key, out value)) { return true; } else if (parent != null) { return parent.TryGetValue(key, out value); } else { value = null; return false; } } public LocalBuilder this[string key] { get { LocalBuilder value; TryGetValue(key, out value); return value; } set { _locals[key] = value; } } public void AddToFreeLocals(Dictionary<Tuple<Type, string>, Queue<LocalBuilder>> freeLocals) { foreach (var item in _locals) { Tuple<Type, string> key = new Tuple<Type, string>(item.Value.LocalType, item.Key); Queue<LocalBuilder> freeLocalQueue; if (freeLocals.TryGetValue(key, out freeLocalQueue)) { // Add to end of the queue so that it will be re-used in // FIFO manner freeLocalQueue.Enqueue(item.Value); } else { freeLocalQueue = new Queue<LocalBuilder>(); freeLocalQueue.Enqueue(item.Value); freeLocals.Add(key, freeLocalQueue); } } } } internal class MethodBuilderInfo { public readonly MethodBuilder MethodBuilder; public readonly Type[] ParameterTypes; public MethodBuilderInfo(MethodBuilder methodBuilder, Type[] parameterTypes) { this.MethodBuilder = methodBuilder; this.ParameterTypes = parameterTypes; } public void Validate(Type returnType, Type[] parameterTypes, MethodAttributes attributes) { #if DEBUG Debug.Assert(this.MethodBuilder.ReturnType == returnType); Debug.Assert(this.MethodBuilder.Attributes == attributes); Debug.Assert(this.ParameterTypes.Length == parameterTypes.Length); for (int i = 0; i < parameterTypes.Length; ++i) { Debug.Assert(this.ParameterTypes[i] == parameterTypes[i]); } #endif } } internal class CodeGeneratorConversionException : Exception { private readonly Type _sourceType; private readonly Type _targetType; private readonly bool _isAddress; private readonly string _reason; public CodeGeneratorConversionException(Type sourceType, Type targetType, bool isAddress, string reason) : base() { _sourceType = sourceType; _targetType = targetType; _isAddress = isAddress; _reason = reason; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Analyzer.Utilities; using System.Linq; using System.Collections.Concurrent; using System.Collections.Generic; namespace Microsoft.ApiDesignGuidelines.Analyzers { /// <summary> /// CA1707: Identifiers should not contain underscores /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class IdentifiersShouldNotContainUnderscoresAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA1707"; private const string Uri = "https://msdn.microsoft.com/en-us/library/ms182245.aspx"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresTitle), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageAssembly = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageAssembly), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageNamespace = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageNamespace), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageType = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageType), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageMember = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMember), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageTypeTypeParameter = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageTypeTypeParameter), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageMethodTypeParameter = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMethodTypeParameter), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageMemberParameter = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMemberParameter), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageDelegateParameter = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageDelegateParameter), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresDescription), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); internal static DiagnosticDescriptor AssemblyRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageAssembly, DiagnosticCategory.Naming, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: s_localizableDescription, helpLinkUri: Uri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor NamespaceRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageNamespace, DiagnosticCategory.Naming, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: s_localizableDescription, helpLinkUri: Uri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor TypeRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageType, DiagnosticCategory.Naming, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: s_localizableDescription, helpLinkUri: Uri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor MemberRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageMember, DiagnosticCategory.Naming, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: s_localizableDescription, helpLinkUri: Uri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor TypeTypeParameterRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageTypeTypeParameter, DiagnosticCategory.Naming, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: s_localizableDescription, helpLinkUri: Uri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor MethodTypeParameterRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageMethodTypeParameter, DiagnosticCategory.Naming, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: s_localizableDescription, helpLinkUri: Uri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor MemberParameterRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageMemberParameter, DiagnosticCategory.Naming, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: s_localizableDescription, helpLinkUri: Uri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor DelegateParameterRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageDelegateParameter, DiagnosticCategory.Naming, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: s_localizableDescription, helpLinkUri: Uri, customTags: WellKnownDiagnosticTags.Telemetry); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(AssemblyRule, NamespaceRule, TypeRule, MemberRule, TypeTypeParameterRule, MethodTypeParameterRule, MemberParameterRule, DelegateParameterRule); public override void Initialize(AnalysisContext analysisContext) { analysisContext.RegisterSymbolAction(symbolAnalysisContext => { var symbol = symbolAnalysisContext.Symbol; switch (symbol.Kind) { case SymbolKind.Namespace: { if (ContainsUnderScore(symbol.Name)) { symbolAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(NamespaceRule, symbol.ToDisplayString())); } return; } case SymbolKind.NamedType: { var namedType = symbol as INamedTypeSymbol; AnalyzeTypeParameters(symbolAnalysisContext, namedType.TypeParameters); if (namedType.TypeKind == TypeKind.Delegate && namedType.DelegateInvokeMethod != null) { AnalyzeParameters(symbolAnalysisContext, namedType.DelegateInvokeMethod.Parameters); } if (!ContainsUnderScore(symbol.Name) || !symbol.IsPublic()) { return; } symbolAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(TypeRule, symbol.ToDisplayString())); return; } case SymbolKind.Field: { var fieldSymbol = symbol as IFieldSymbol; if (ContainsUnderScore(symbol.Name) && symbol.IsPublic() && (fieldSymbol.IsConst || (fieldSymbol.IsStatic && fieldSymbol.IsReadOnly))) { symbolAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(MemberRule, symbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat))); return; } return; } default: { var methodSymbol = symbol as IMethodSymbol; if (methodSymbol != null) { AnalyzeParameters(symbolAnalysisContext, methodSymbol.Parameters); AnalyzeTypeParameters(symbolAnalysisContext, methodSymbol.TypeParameters); } var propertySymbol = symbol as IPropertySymbol; if (propertySymbol != null) { AnalyzeParameters(symbolAnalysisContext, propertySymbol.Parameters); } if (!ContainsUnderScore(symbol.Name) || IsInvalidSymbol(symbol)) { return; } symbolAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(MemberRule, symbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat))); return; } } }, SymbolKind.Namespace, // Namespace SymbolKind.NamedType, //Type SymbolKind.Method, SymbolKind.Property, SymbolKind.Field, SymbolKind.Event // Members ); analysisContext.RegisterCompilationAction(compilationAnalysisContext => { var compilation = compilationAnalysisContext.Compilation; if (ContainsUnderScore(compilation.AssemblyName)) { compilationAnalysisContext.ReportDiagnostic(compilation.Assembly.CreateDiagnostic(AssemblyRule, compilation.AssemblyName)); } }); } private bool IsInvalidSymbol(ISymbol symbol) { return (!(symbol.GetResultantVisibility() == SymbolVisibility.Public && !symbol.IsOverride)) || symbol.IsAccessorMethod() || symbol.IsImplementationOfAnyInterfaceMember(); } private void AnalyzeParameters(SymbolAnalysisContext symbolAnalysisContext, IEnumerable<IParameterSymbol> parameters) { foreach (var parameter in parameters) { if (ContainsUnderScore(parameter.Name)) { var containingType = parameter.ContainingType; // Parameter in Delegate if (containingType.TypeKind == TypeKind.Delegate) { if (containingType.IsPublic()) { symbolAnalysisContext.ReportDiagnostic(parameter.CreateDiagnostic(DelegateParameterRule, containingType.ToDisplayString(), parameter.Name)); } } else if (!IsInvalidSymbol(parameter.ContainingSymbol)) { symbolAnalysisContext.ReportDiagnostic(parameter.CreateDiagnostic(MemberParameterRule, parameter.ContainingSymbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat), parameter.Name)); } } } } private void AnalyzeTypeParameters(SymbolAnalysisContext symbolAnalysisContext, IEnumerable<ITypeParameterSymbol> typeParameters) { foreach (var typeParameter in typeParameters) { if (ContainsUnderScore(typeParameter.Name)) { var containingSymbol = typeParameter.ContainingSymbol; if (containingSymbol.Kind == SymbolKind.NamedType) { if (containingSymbol.IsPublic()) { symbolAnalysisContext.ReportDiagnostic(typeParameter.CreateDiagnostic(TypeTypeParameterRule, containingSymbol.ToDisplayString(), typeParameter.Name)); } } else if (containingSymbol.Kind == SymbolKind.Method && !IsInvalidSymbol(containingSymbol)) { symbolAnalysisContext.ReportDiagnostic(typeParameter.CreateDiagnostic(MethodTypeParameterRule, containingSymbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat), typeParameter.Name)); } } } } private static bool ContainsUnderScore(string identifier) { return identifier.IndexOf('_') != -1; } } }
// *********************************************************************** // Copyright (c) 2008 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.TestData.TestCaseAttributeFixture; using NUnit.TestUtilities; namespace NUnit.Framework.Attributes { [TestFixture] public class TestCaseAttributeTests { [TestCase(12, 3, 4)] [TestCase(12, 2, 6)] [TestCase(12, 4, 3)] public void IntegerDivisionWithResultPassedToTest(int n, int d, int q) { Assert.AreEqual(q, n / d); } [TestCase(12, 3, ExpectedResult = 4)] [TestCase(12, 2, ExpectedResult = 6)] [TestCase(12, 4, ExpectedResult = 3)] public int IntegerDivisionWithResultCheckedByNUnit(int n, int d) { return n / d; } [TestCase(2, 2, ExpectedResult=4)] public double CanConvertIntToDouble(double x, double y) { return x + y; } [TestCase("2.2", "3.3", ExpectedResult = 5.5)] public decimal CanConvertStringToDecimal(decimal x, decimal y) { return x + y; } [TestCase(2.2, 3.3, ExpectedResult = 5.5)] public decimal CanConvertDoubleToDecimal(decimal x, decimal y) { return x + y; } [TestCase(5, 2, ExpectedResult = 7)] public decimal CanConvertIntToDecimal(decimal x, decimal y) { return x + y; } [TestCase(5, 2, ExpectedResult = 7)] public short CanConvertSmallIntsToShort(short x, short y) { return (short)(x + y); } [TestCase(5, 2, ExpectedResult = 7)] public byte CanConvertSmallIntsToByte(byte x, byte y) { return (byte)(x + y); } [TestCase(5, 2, ExpectedResult = 7)] public sbyte CanConvertSmallIntsToSByte(sbyte x, sbyte y) { return (sbyte)(x + y); } [TestCase("MethodCausesConversionOverflow", RunState.NotRunnable)] [TestCase("VoidTestCaseWithExpectedResult", RunState.NotRunnable)] [TestCase("TestCaseWithNullableReturnValueAndNullExpectedResult", RunState.Runnable)] public void TestCaseRunnableState(string methodName, RunState expectedState) { var test = (Test)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), methodName).Tests[0]; Assert.AreEqual(expectedState, test.RunState); } [TestCase("12-October-1942")] public void CanConvertStringToDateTime(DateTime dt) { Assert.AreEqual(1942, dt.Year); } [TestCase(null)] public void CanPassNullAsFirstArgument(object a) { Assert.IsNull(a); } [TestCase(new object[] { 1, "two", 3.0 })] [TestCase(new object[] { "zip" })] public void CanPassObjectArrayAsFirstArgument(object[] a) { } [TestCase(new object[] { "a", "b" })] public void CanPassArrayAsArgument(object[] array) { Assert.AreEqual("a", array[0]); Assert.AreEqual("b", array[1]); } [TestCase("a", "b")] public void ArgumentsAreCoalescedInObjectArray(object[] array) { Assert.AreEqual("a", array[0]); Assert.AreEqual("b", array[1]); } [TestCase(1, "b")] public void ArgumentsOfDifferentTypeAreCoalescedInObjectArray(object[] array) { Assert.AreEqual(1, array[0]); Assert.AreEqual("b", array[1]); } [TestCase(ExpectedResult = null)] public object ResultCanBeNull() { return null; } [TestCase("a", "b")] public void HandlesParamsArrayAsSoleArgument(params string[] array) { Assert.AreEqual("a", array[0]); Assert.AreEqual("b", array[1]); } [TestCase("a")] public void HandlesParamsArrayWithOneItemAsSoleArgument(params string[] array) { Assert.AreEqual("a", array[0]); } [TestCase("a", "b", "c", "d")] public void HandlesParamsArrayAsLastArgument(string s1, string s2, params object[] array) { Assert.AreEqual("a", s1); Assert.AreEqual("b", s2); Assert.AreEqual("c", array[0]); Assert.AreEqual("d", array[1]); } [TestCase("a", "b")] public void HandlesParamsArrayWithNoItemsAsLastArgument(string s1, string s2, params object[] array) { Assert.AreEqual("a", s1); Assert.AreEqual("b", s2); Assert.AreEqual(0, array.Length); } [TestCase("a", "b", "c")] public void HandlesParamsArrayWithOneItemAsLastArgument(string s1, string s2, params object[] array) { Assert.AreEqual("a", s1); Assert.AreEqual("b", s2); Assert.AreEqual("c", array[0]); } [TestCase(1)] public void NullableSimpleFormalParametersWithArgument(int? a) { Assert.AreEqual(1, a); } [TestCase(null)] public void NullableSimpleFormalParametersWithNullArgument(int? a) { Assert.IsNull(a); } [TestCase(null, ExpectedResult = null)] [TestCase(1, ExpectedResult = 1)] public int? TestCaseWithNullableReturnValue(int? a) { return a; } [Test] public void CanSpecifyDescription() { Test test = (Test)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodHasDescriptionSpecified").Tests[0]; Assert.AreEqual("My Description", test.Properties.Get(PropertyNames.Description)); } [Test] public void CanSpecifyTestName() { Test test = (Test)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodHasTestNameSpecified").Tests[0]; Assert.AreEqual("XYZ", test.Name); Assert.AreEqual("NUnit.TestData.TestCaseAttributeFixture.TestCaseAttributeFixture.XYZ", test.FullName); } [Test] public void CanSpecifyCategory() { Test test = (Test)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodHasSingleCategory").Tests[0]; IList categories = test.Properties["Category"]; Assert.AreEqual(new string[] { "XYZ" }, categories); } [Test] public void CanSpecifyMultipleCategories() { Test test = (Test)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodHasMultipleCategories").Tests[0]; IList categories = test.Properties["Category"]; Assert.AreEqual(new string[] { "X", "Y", "Z" }, categories); } [Test] public void CanIgnoreIndividualTestCases() { TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodWithIgnoredTestCases"); Test testCase = TestFinder.Find("MethodWithIgnoredTestCases(1)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable)); testCase = TestFinder.Find("MethodWithIgnoredTestCases(2)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored)); testCase = TestFinder.Find("MethodWithIgnoredTestCases(3)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored)); Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Don't Run Me!")); } [Test] public void CanMarkIndividualTestCasesExplicit() { TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodWithExplicitTestCases"); Test testCase = TestFinder.Find("MethodWithExplicitTestCases(1)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable)); testCase = TestFinder.Find("MethodWithExplicitTestCases(2)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit)); testCase = TestFinder.Find("MethodWithExplicitTestCases(3)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit)); Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Connection failing")); } #if !PORTABLE [Test] public void CanIncludePlatform() { bool isLinux = System.IO.Path.DirectorySeparatorChar == '/'; TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodWithIncludePlatform"); Test testCase1 = TestFinder.Find("MethodWithIncludePlatform(1)", suite, false); Test testCase2 = TestFinder.Find("MethodWithIncludePlatform(2)", suite, false); if (isLinux) { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable)); } else { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Skipped)); } } [Test] public void CanExcludePlatform() { bool isLinux = System.IO.Path.DirectorySeparatorChar == '/'; TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseAttributeFixture), "MethodWitExcludePlatform"); Test testCase1 = TestFinder.Find("MethodWitExcludePlatform(1)", suite, false); Test testCase2 = TestFinder.Find("MethodWitExcludePlatform(2)", suite, false); if (isLinux) { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Skipped)); } else { Assert.That(testCase1.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable)); } } #endif } }
//----------------------------------------------------------------------- // Copyright (c) Microsoft Open Technologies, Inc. // All Rights Reserved // Apache License 2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //----------------------------------------------------------------------- using Microsoft.IdentityModel.Protocols; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections; using System.Collections.Generic; using System.IdentityModel.Test; namespace Microsoft.IdentityModel.Test { /// <summary> /// /// </summary> [TestClass] public class JsonWebKeyTests { public TestContext TestContext { get; set; } [ClassInitialize] public static void ClassSetup(TestContext testContext) { } [ClassCleanup] public static void ClassCleanup() { } [TestInitialize] public void Initialize() { } [TestMethod] [TestProperty("TestCaseID", "5c9f0af7-b2cf-4baa-a73a-986574714a64")] [Description("Tests: Constructors")] public void JsonWebKey_Constructors() { JsonWebKey jsonWebKey = new JsonWebKey(); Assert.IsTrue(IsDefaultJsonWebKey(jsonWebKey)); string str = "hello"; str = null; // null string, nothing to add RunJsonWebKeyTest(str, new JsonWebKey(), ExpectedException.NoExceptionExpected); // null dictionary, nothing to add RunJsonWebKeyTest(null, new JsonWebKey(), ExpectedException.NoExceptionExpected, false); // valid json, JsonWebKey1 RunJsonWebKeyTest(OpenIdConfigData.JsonWebKeyFromPing, OpenIdConfigData.JsonWebKeyFromPingExpected1, ExpectedException.NoExceptionExpected); // valid json, JsonWebKey1 RunJsonWebKeyTest(OpenIdConfigData.JsonWebKeyString1, OpenIdConfigData.JsonWebKeyExpected1, ExpectedException.NoExceptionExpected); // valid dictionary, JsonWebKey1 RunJsonWebKeyTest(OpenIdConfigData.JsonWebKeyDictionary1, OpenIdConfigData.JsonWebKeyExpected1, ExpectedException.NoExceptionExpected); // valid json, JsonWebKey2 jsonWebKey = RunJsonWebKeyTest(OpenIdConfigData.JsonWebKeyString2, OpenIdConfigData.JsonWebKeyExpected2, ExpectedException.NoExceptionExpected); Assert.IsTrue(!IdentityComparer.AreEqual(jsonWebKey, OpenIdConfigData.JsonWebKeyExpected1)); // invalid json, JsonWebKeyBadFormatString1 RunJsonWebKeyTest(OpenIdConfigData.JsonWebKeyBadFormatString1, null, ExpectedException.ArgumentException()); // invalid json, JsonWebKeyBadFormatString2 RunJsonWebKeyTest(OpenIdConfigData.JsonWebKeyBadFormatString2, null, ExpectedException.ArgumentException()); // invalid json, JsonWebKeyBadx509String1 RunJsonWebKeyTest(OpenIdConfigData.JsonWebKeyBadX509String, OpenIdConfigData.JsonWebKeyExpectedBadX509Data, ExpectedException.NoExceptionExpected); } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <param name="compareTo"></param> /// <param name="expectedException"></param> /// <param name="asString"> this is useful when passing null for parameter 'is' and 'as' don't contain type info.</param> /// <returns></returns> private JsonWebKey RunJsonWebKeyTest(object obj, JsonWebKey compareTo, ExpectedException expectedException, bool asString = true) { JsonWebKey jsonWebKey = null; try { if (obj is string) { jsonWebKey = new JsonWebKey(obj as string); } else if (obj is IDictionary<string, object>) { jsonWebKey = new JsonWebKey(obj as IDictionary<string, object>); } else { if (asString) { jsonWebKey = new JsonWebKey(obj as string); } else { jsonWebKey = new JsonWebKey(obj as IDictionary<string, object>); } } expectedException.ProcessNoException(); } catch (Exception ex) { expectedException.ProcessException(ex); } if (compareTo != null) { Assert.IsTrue(IdentityComparer.AreEqual(jsonWebKey, compareTo), "jsonWebKey created from: " + ( obj == null ? "NULL" : obj.ToString() + " did not match expected.")); } return jsonWebKey; } [TestMethod] [TestProperty("TestCaseID", "54fa205b-5a50-4d29-9ff0-9c38c397106a")] [Description("Tests: Defaults")] public void JsonWebKey_Defaults() { } [TestMethod] [TestProperty("TestCaseID", "4642e46f-72cd-4ffe-80ea-1006036986a1")] [Description("Tests: GetSets")] public void JsonWebKey_GetSets() { JsonWebKey jsonWebKey = new JsonWebKey(); TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(jsonWebKey, "JsonWebKey_GetSets"); List<string> methods = new List<string>{"Alg", "KeyOps", "Kid", "Kty", "X5t", "X5u", "Use"}; foreach(string method in methods) { TestUtilities.GetSet(jsonWebKey, method, null, new object[] { Guid.NewGuid().ToString(), null, Guid.NewGuid().ToString() }); jsonWebKey.X5c.Add(method); } Assert.IsTrue(IdentityComparer.AreEqual<IEnumerable<string>>(jsonWebKey.X5c, methods, CompareContext.Default)); } [TestMethod] [TestProperty("TestCaseID", "ee45364b-0792-4fea-8485-e36fc6381319")] [Description("Tests: Publics")] public void JsonWebKey_Publics() { } private bool IsDefaultJsonWebKey(JsonWebKey jsonWebKey) { if (jsonWebKey.Alg != null) return false; if (jsonWebKey.KeyOps != null) return false; if (jsonWebKey.Kid != null) return false; if (jsonWebKey.Kty != null) return false; if (jsonWebKey.X5c == null) return false; if (jsonWebKey.X5c.Count != 0) return false; if (jsonWebKey.X5t != null) return false; if (jsonWebKey.X5u != null) return false; if (jsonWebKey.Use != null) return false; return true; } } }
// Copyright (c) Russlan Akiev. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace IdentityBase.Actions.Register { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IdentityBase.Configuration; using IdentityBase.Extensions; using IdentityBase.Models; using IdentityBase.Services; using IdentityServer4.Models; using IdentityServer4.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using ServiceBase.Notification.Email; public class RegisterController : WebController { private readonly ApplicationOptions _applicationOptions; private readonly ILogger<RegisterController> _logger; private readonly IIdentityServerInteractionService _interaction; private readonly UserAccountService _userAccountService; private readonly ClientService _clientService; private readonly NotificationService _notificationService; private readonly AuthenticationService _authenticationService; private readonly IStringLocalizer _localizer; public RegisterController( ApplicationOptions applicationOptions, ILogger<RegisterController> logger, IIdentityServerInteractionService interaction, IEmailService emailService, UserAccountService userAccountService, ClientService clientService, NotificationService notificationService, AuthenticationService authenticationService, IStringLocalizer localizer) { this._applicationOptions = applicationOptions; this._logger = logger; this._interaction = interaction; this._userAccountService = userAccountService; this._clientService = clientService; this._notificationService = notificationService; this._authenticationService = authenticationService; this._localizer = localizer; } [HttpGet("register", Name = "Register")] public async Task<IActionResult> Index(string returnUrl) { RegisterViewModel vm = await this.CreateViewModelAsync(returnUrl); if (vm == null) { this._logger.LogError( "Register attempt with missing returnUrl parameter"); return this.RedirectToAction("Index", "Error"); } return this.View(vm); } [HttpPost("register", Name = "Register")] [ValidateAntiForgeryToken] public async Task<IActionResult> Index(RegisterInputModel model) { if (!this.ModelState.IsValid) { return this.View(await this.CreateViewModelAsync(model)); } string email = model.Email.ToLower(); // Check if user with same email exists UserAccount userAccount = await this._userAccountService .LoadByEmailWithExternalAsync(email); // If user dont exists create a new one if (userAccount == null) { return await this.TryCreateNewUserAccount(model); } // User is just disabled by whatever reason else if (!userAccount.IsLoginAllowed) { this.ModelState.AddModelError( this._localizer[ErrorMessages.AccountIsDesabled]); } // If user has a password then its a local account else if (userAccount.HasPassword()) { // User has to follow a link in confirmation mail if (this._applicationOptions.RequireLocalAccountVerification && !userAccount.IsEmailVerified) { this.ModelState.AddModelError( this._localizer[ErrorMessages.ConfirmAccount]); // TODO: show link for resent confirmation link } // If user has a password then its a local account this.ModelState.AddModelError( this._localizer[ErrorMessages.AccountAlreadyExists]); } else { // External account with same email return await this.TryMergeWithExistingUserAccount( userAccount, model ); } return this.View( await this.CreateViewModelAsync(model, userAccount) ); } // [HttpGet("register/complete")] // public async Task<IActionResult> Complete(string returnUrl) // { // var userAccount = await GetUserAccountFromCoockyValue(); // if (userAccount == null) // { // ModelState.AddModelError(IdentityBaseConstants.ErrorMessages.TokenIsInvalid); // return View("InvalidToken"); // } // // var vm = new RegisterCompleteViewModel // { // ReturnUrl = returnUrl, // UserAccountId = userAccount.Id, // Email = userAccount.Email // }; // // return View(vm); // } // [HttpPost("register/complete")] // [ValidateAntiForgeryToken] // public async Task<IActionResult> Complete(RegisterCompleteInputModel model) // { // // update user // // authenticate user // // redirect to return url // // var userAccount = await GetUserAccountFromCoockyValue(); // httpContextAccessor.HttpContext.Response.Cookies.Delete("ConfirmUserAccountId"); // // throw new NotImplementedException(); // // /* // // TODO: cleanup // userAccount.ClearVerification(); // var now = DateTime.UtcNow; // userAccount.IsLoginAllowed = true; // userAccount.IsEmailVerified = true; // userAccount.EmailVerifiedAt = now; // userAccount.UpdatedAt = now; // // await Task.WhenAll( // userAccountService.AddLocalCredentialsAsync(userAccount, model.Password), // httpContextAccessor.HttpContext.Authentication.SignInAsync(userAccount, null) // ); */ // // // && interaction.IsValidReturnUrl(returnUrl) // // if (model.ReturnUrl != null) // { // return Redirect(model.ReturnUrl); // } // // return Redirect("/"); // } // [NonAction] // internal async Task<UserAccount> GetUserAccountFromCoockyValue() // { // if (httpContextAccessor.HttpContext.Request.Cookies // .TryGetValue("ConfirmUserAccountId", out string userIdStr)) // { // if (Guid.TryParse(userIdStr, out Guid userId)) // { // return await userAccountService.LoadByIdAsync(userId); // } // } // // return null; // } [NonAction] internal async Task<RegisterViewModel> CreateViewModelAsync( string returnUrl) { return await this.CreateViewModelAsync( new RegisterViewModel { ReturnUrl = returnUrl } ); } [NonAction] internal async Task<RegisterViewModel> CreateViewModelAsync( RegisterInputModel inputModel, UserAccount userAccount = null) { AuthorizationRequest context = await this._interaction .GetAuthorizationContextAsync(inputModel.ReturnUrl); if (context == null) { return null; } Client client = await this._clientService .FindEnabledClientByIdAsync(context.ClientId); IEnumerable<ExternalProvider> providers = await this._clientService .GetEnabledProvidersAsync(client); RegisterViewModel vm = new RegisterViewModel(inputModel) { EnableAccountRecover = this._applicationOptions.EnableAccountRecovery, EnableLocalLogin = client != null ? client.EnableLocalLogin : false && this._applicationOptions.EnableAccountLogin, ExternalProviders = providers.ToArray(), ExternalProviderHints = userAccount?.Accounts? .Select(c => c.Provider) }; return vm; } [NonAction] internal SuccessViewModel CreateSuccessViewModel( UserAccount userAccount, string returnUrl) { return new SuccessViewModel() { ReturnUrl = returnUrl, Provider = userAccount.Email.Split('@').LastOrDefault() }; } [NonAction] internal async Task<IActionResult> TryMergeWithExistingUserAccount( UserAccount userAccount, RegisterInputModel model) { // Merge accounts without user consent if (this._applicationOptions.AutomaticAccountMerge) { await this._userAccountService .AddLocalCredentialsAsync(userAccount, model.Password); if (this._applicationOptions.LoginAfterAccountCreation) { await this._authenticationService .SignInAsync(userAccount, model.ReturnUrl); } else { return this.View("Success", this.CreateSuccessViewModel( userAccount, model.ReturnUrl) ); } } // Ask user if he wants to merge accounts else { throw new NotImplementedException(); } // Return list of external account providers as hint RegisterViewModel vm = new RegisterViewModel(model) { ExternalProviderHints = userAccount.Accounts .Select(s => s.Provider).ToArray() }; return View(vm); } [NonAction] internal async Task<IActionResult> TryCreateNewUserAccount( RegisterInputModel model) { UserAccount userAccount = await this._userAccountService .CreateNewLocalUserAccountAsync( model.Email, model.Password, model.ReturnUrl ); // Send confirmation mail if (this._applicationOptions.RequireLocalAccountVerification) { await this._notificationService .SendUserAccountCreatedEmailAsync(userAccount); } if (this._applicationOptions.LoginAfterAccountCreation) { await this._authenticationService .SignInAsync(userAccount, model.ReturnUrl); return this.RedirectToReturnUrl( model.ReturnUrl, this._interaction); } return this.View("Success", this.CreateSuccessViewModel(userAccount, model.ReturnUrl) ); } [HttpGet("register/confirm", Name = "RegisterConfirm")] public async Task<IActionResult> Confirm([FromQuery]string key) { TokenVerificationResult result = await this._userAccountService .HandleVerificationKeyAsync( key, VerificationKeyPurpose.ConfirmAccount ); if (result.UserAccount == null || !result.PurposeValid || result.TokenExpired) { if (result.UserAccount != null) { await this._userAccountService .ClearVerificationAsync(result.UserAccount); } this.ModelState.AddModelError( this._localizer[ErrorMessages.TokenIsInvalid]); return this.View("InvalidToken"); } // User account requires completion. if (this._applicationOptions.EnableAccountInvitation && result.UserAccount.CreationKind == CreationKind.Invitation) { // TODO: move invitation confirmation to own contoller // listening on /invitation/confirm ConfirmViewModel vm = new ConfirmViewModel { RequiresPassword = !result.UserAccount.HasPassword(), Email = result.UserAccount.Email }; return this.View("Confirm", vm); } // User account already fine and can be authenticated. else { // TODO: Refactor so the db will hit only once in case // LoginAfterAccountConfirmation is true string returnUrl = result.UserAccount.VerificationStorage; await this._userAccountService .SetEmailVerifiedAsync(result.UserAccount); if (this._applicationOptions.LoginAfterAccountConfirmation) { await this._authenticationService .SignInAsync(result.UserAccount, returnUrl); return this.RedirectToReturnUrl( returnUrl, this._interaction); } else if (this._applicationOptions.CancelAfterAccountConfirmation) { return this.RedirectToAction( "complete", new { ReturnUrl = returnUrl } ); } return this.RedirectToLogin(returnUrl); } } [HttpGet("register/complete", Name = "RegisterComplete")] public async Task<IActionResult> Complete() { return this.View("Complete"); } // Currently is only used for invitations [HttpPost("register/confirm", Name = "RegisterConfirm")] [ValidateAntiForgeryToken] public async Task<IActionResult> Confirm( [FromQuery]string key, ConfirmInputModel model) { if (!this._applicationOptions.EnableAccountInvitation) { return this.NotFound(); } TokenVerificationResult result = await this._userAccountService .HandleVerificationKeyAsync( key, VerificationKeyPurpose.ConfirmAccount ); if (result.UserAccount == null || result.TokenExpired || !result.PurposeValid) { if (result.UserAccount != null) { await this._userAccountService .ClearVerificationAsync(result.UserAccount); } this.ModelState.AddModelError( this._localizer[ErrorMessages.TokenIsInvalid]); return this.View("InvalidToken"); } if (!this.ModelState.IsValid) { return this.View("Confirm", new ConfirmViewModel { Email = result.UserAccount.Email }); } string returnUrl = result.UserAccount.VerificationStorage; this._userAccountService.SetEmailVerified(result.UserAccount); this._userAccountService .AddLocalCredentials(result.UserAccount, model.Password); await this._userAccountService .UpdateUserAccountAsync(result.UserAccount); if (this._applicationOptions.CancelAfterAccountConfirmation) { // return this.View("Complete"); return this.RedirectToAction( "complete", new { ReturnUrl = returnUrl } ); } else if (result.UserAccount.CreationKind == CreationKind.Invitation) { return this.RedirectToReturnUrl( returnUrl, this._interaction); } else { if (this._applicationOptions.LoginAfterAccountRecovery) { await this._authenticationService .SignInAsync(result.UserAccount, returnUrl); return this.RedirectToReturnUrl( returnUrl, this._interaction); } return this.RedirectToLogin(returnUrl); } } [HttpGet("register/cancel", Name = "RegisterCancel")] public async Task<IActionResult> Cancel([FromQuery]string key) { TokenVerificationResult result = await this._userAccountService .HandleVerificationKeyAsync( key, VerificationKeyPurpose.ConfirmAccount ); if (result.UserAccount == null || !result.PurposeValid || result.TokenExpired) { if (result.UserAccount != null) { await this._userAccountService .ClearVerificationAsync(result.UserAccount); } this.ModelState.AddModelError( this._localizer[ErrorMessages.TokenIsInvalid]); return this.View("InvalidToken"); } string returnUrl = result.UserAccount.VerificationStorage; await this._userAccountService .ClearVerificationAsync(result.UserAccount); if (this._interaction.IsValidReturnUrl(returnUrl)) { return this.Redirect(returnUrl); } else { return this.RedirectToLogin(returnUrl); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using KitchenPC.Data; using KitchenPC.Data.DTO; using log4net; using NHibernate; using NHibernate.Persister.Entity; namespace KitchenPC.DB.Provisioning { public class DatabaseExporter : IDisposable, IProvisioner { readonly IStatelessSession session; public static ILog Log = LogManager.GetLogger(typeof (DatabaseExporter)); public DatabaseExporter(IStatelessSession session) { this.session = session; } IEnumerable<D> ImportTableData<T, D>(Func<IDataReader, D> action) where T : new() { using (var cmd = session.Connection.CreateCommand()) { var persister = session.GetSessionImplementation().GetEntityPersister(null, new T()) as ILockable; if (persister == null) throw new NullReferenceException(); cmd.CommandType = CommandType.TableDirect; cmd.CommandText = persister.RootTableName; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { yield return action(reader); } } } } public IngredientForms[] IngredientForms() { var list = ImportTableData<Models.IngredientForms, IngredientForms>(r => new IngredientForms { IngredientFormId = (Guid) r["IngredientFormId"], IngredientId = (Guid) r["IngredientId"], ConvMultiplier = (short) r["ConvMultiplier"], FormAmount = (float) r["FormAmount"], UnitType = Unit.Parse<Units>(r["UnitType"]), UnitName = r["UnitName"] as String, FormUnit = Unit.Parse<Units>(r["FormUnit"]), FormDisplayName = r["FormDisplayName"] as String }).ToArray(); Log.DebugFormat("Read {0} row(s) from IngredientForms.", list.Count()); return list; } public IngredientMetadata[] IngredientMetadata() { var list = ImportTableData<Models.IngredientMetadata, IngredientMetadata>(r => new IngredientMetadata { IngredientMetadataId = (Guid) r["IngredientMetadataId"], IngredientId = (Guid) r["IngredientId"], HasMeat = r["HasMeat"] as Boolean?, CarbsPerUnit = r["CarbsPerUnit"] as Single?, HasRedMeat = r["HasRedMeat"] as Boolean?, SugarPerUnit = r["SugarPerUnit"] as Single?, HasPork = r["HasPork"] as Boolean?, FatPerUnit = r["FatPerUnit"] as Single?, SodiumPerUnit = r["SodiumPerUnit"] as Single?, CaloriesPerUnit = r["CaloriesPerUnit"] as Single?, Spicy = (Int16) r["Spicy"], Sweet = (Int16) r["Sweet"], HasGluten = r["HasGluten"] as Boolean?, HasAnimal = r["HasAnimal"] as Boolean?, }).ToArray(); Log.DebugFormat("Read {0} row(s) from IngredientMetadata.", list.Count()); return list; } public Data.DTO.Ingredients[] Ingredients() { var list = ImportTableData<Models.Ingredients, Data.DTO.Ingredients>(r => new Data.DTO.Ingredients { IngredientId = (Guid) r["IngredientId"], UsdaId = r["UsdaId"] as String, FoodGroup = r["FoodGroup"] as String, DisplayName = r["DisplayName"] as String, ManufacturerName = r["ManufacturerName"] as String, ConversionType = Unit.Parse<UnitType>(r["ConversionType"]), UnitName = r["UnitName"] as String, UsdaDesc = r["UsdaDesc"] as String, UnitWeight = (Int32) r["UnitWeight"] }).ToArray(); Log.DebugFormat("Read {0} row(s) from Ingredients.", list.Count()); return list; } public NlpAnomalousIngredients[] NlpAnomalousIngredients() { var list = ImportTableData<Models.NlpAnomalousIngredients, NlpAnomalousIngredients>(r => new NlpAnomalousIngredients { AnomalousIngredientId = (Guid) r["AnomalousIngredientId"], Name = r["Name"] as String, IngredientId = (Guid) r["IngredientId"], WeightFormId = r["WeightFormId"] as Guid?, VolumeFormId = r["VolumeFormId"] as Guid?, UnitFormId = r["UnitFormId"] as Guid? }).ToArray(); Log.DebugFormat("Read {0} row(s) from NlpAnomalousIngredients.", list.Count()); return list; } public NlpDefaultPairings[] NlpDefaultPairings() { var list = ImportTableData<Models.NlpDefaultPairings, NlpDefaultPairings>(r => new NlpDefaultPairings { DefaultPairingId = (Guid) r["DefaultPairingId"], IngredientId = (Guid) r["IngredientId"], WeightFormId = r["WeightFormId"] as Guid?, VolumeFormId = r["VolumeFormId"] as Guid?, UnitFormId = r["UnitFormId"] as Guid? }).ToArray(); Log.DebugFormat("Read {0} row(s) from NlpDefaultPairings.", list.Count()); return list; } public NlpFormSynonyms[] NlpFormSynonyms() { var list = ImportTableData<Models.NlpFormSynonyms, NlpFormSynonyms>(r => new NlpFormSynonyms { FormSynonymId = (Guid) r["FormSynonymId"], IngredientId = (Guid) r["IngredientId"], FormId = (Guid) r["FormId"], Name = r["Name"] as String }).ToArray(); Log.DebugFormat("Read {0} row(s) from NlpFormSynonyms.", list.Count()); return list; } public NlpIngredientSynonyms[] NlpIngredientSynonyms() { var list = ImportTableData<Models.NlpIngredientSynonyms, NlpIngredientSynonyms>(r => new NlpIngredientSynonyms { IngredientSynonymId = (Guid) r["IngredientSynonymId"], IngredientId = (Guid) r["IngredientId"], Alias = r["Alias"] as String, Prepnote = r["Prepnote"] as String }).ToArray(); Log.DebugFormat("Read {0} row(s) from NlpIngredientSynonyms.", list.Count()); return list; } public NlpPrepNotes[] NlpPrepNotes() { var list = ImportTableData<Models.NlpPrepNotes, NlpPrepNotes>(r => new NlpPrepNotes { Name = r["Name"] as String }).ToArray(); Log.DebugFormat("Read {0} row(s) from NlpPrepNotes.", list.Count()); return list; } public NlpUnitSynonyms[] NlpUnitSynonyms() { var list = ImportTableData<Models.NlpUnitSynonyms, NlpUnitSynonyms>(r => new NlpUnitSynonyms { UnitSynonymId = (Guid) r["UnitSynonymId"], IngredientId = (Guid) r["IngredientId"], FormId = (Guid) r["FormId"], Name = r["Name"] as String }).ToArray(); Log.DebugFormat("Read {0} row(s) from NlpUnitSynonyms.", list.Count()); return list; } public List<Data.DTO.Recipes> Recipes() { var list = ImportTableData<Models.Recipes, Data.DTO.Recipes>(r => new Data.DTO.Recipes { RecipeId = (Guid) r["RecipeId"], CookTime = r["CookTime"] as Int16?, Steps = r["Steps"] as String, PrepTime = r["PrepTime"] as Int16?, Rating = (Int16) r["Rating"], Description = r["Description"] as String, Title = r["Title"] as String, Hidden = (bool) r["Hidden"], Credit = r["Credit"] as String, CreditUrl = r["CreditUrl"] as String, DateEntered = (DateTime) r["DateEntered"], ServingSize = (Int16) r["ServingSize"], ImageUrl = r["ImageUrl"] as String }).ToList(); Log.DebugFormat("Read {0} row(s) from Recipes.", list.Count()); return list; } public List<RecipeMetadata> RecipeMetadata() { var list = ImportTableData<Models.RecipeMetadata, RecipeMetadata>(r => new RecipeMetadata { RecipeMetadataId = (Guid) r["RecipeMetadataId"], RecipeId = (Guid) r["RecipeId"], PhotoRes = (Int32) r["PhotoRes"], Commonality = (Single) r["Commonality"], UsdaMatch = (bool) r["UsdaMatch"], MealBreakfast = (bool) r["MealBreakfast"], MealLunch = (bool) r["MealLunch"], MealDinner = (bool) r["MealDinner"], MealDessert = (bool) r["MealDessert"], DietNomeat = (bool) r["DietNomeat"], DietGlutenFree = (bool) r["DietGlutenFree"], DietNoRedMeat = (bool) r["DietNoRedMeat"], DietNoAnimals = (bool) r["DietNoAnimals"], DietNoPork = (bool) r["DietNoPork"], NutritionTotalfat = (Int16) r["NutritionTotalfat"], NutritionTotalSodium = (Int16) r["NutritionTotalSodium"], NutritionLowSodium = (bool) r["NutritionLowSodium"], NutritionLowSugar = (bool) r["NutritionLowSugar"], NutritionLowCalorie = (bool) r["NutritionLowCalorie"], NutritionTotalSugar = (Int16) r["NutritionTotalSugar"], NutritionTotalCalories = (Int16) r["NutritionTotalCalories"], NutritionLowFat = (bool) r["NutritionLowFat"], NutritionLowCarb = (bool) r["NutritionLowCarb"], NutritionTotalCarbs = (Int16) r["NutritionTotalCarbs"], SkillQuick = (bool) r["SkillQuick"], SkillEasy = (bool) r["SkillEasy"], SkillCommon = (bool) r["SkillCommon"], TasteMildToSpicy = (Int16) r["TasteMildToSpicy"], TasteSavoryToSweet = (Int16) r["TasteSavoryToSweet"] }).ToList(); Log.DebugFormat("Read {0} row(s) from RecipeMetadata.", list.Count()); return list; } public List<RecipeIngredients> RecipeIngredients() { var list = ImportTableData<Models.RecipeIngredients, RecipeIngredients>(r => new RecipeIngredients { RecipeIngredientId = (Guid) r["RecipeIngredientId"], RecipeId = (Guid) r["RecipeId"], IngredientId = (Guid) r["IngredientId"], IngredientFormId = r["IngredientFormId"] as Guid?, Unit = Unit.Parse<Units>(r["Unit"]), QtyLow = r["QtyLow"] as Single?, DisplayOrder = (Int16) r["DisplayOrder"], PrepNote = r["PrepNote"] as String, Qty = r["Qty"] as Single?, Section = r["Section"] as String }).ToList(); Log.DebugFormat("Read {0} row(s) from RecipeIngredients.", list.Count()); return list; } public List<Favorites> Favorites() { var list = ImportTableData<Models.Favorites, Favorites>(r => new Favorites { FavoriteId = (Guid) r["FavoriteId"], UserId = (Guid) r["UserId"], RecipeId = (Guid) r["RecipeId"], MenuId = r["MenuId"] as Guid? }).ToList(); Log.DebugFormat("Read {0} row(s) from Favorites.", list.Count()); return list; } public List<Data.DTO.Menus> Menus() { var list = ImportTableData<Models.Menus, Data.DTO.Menus>(r => new Data.DTO.Menus { MenuId = (Guid) r["MenuId"], UserId = (Guid) r["UserId"], Title = r["Title"] as String, CreatedDate = (DateTime) r["CreatedDate"] }).ToList(); Log.DebugFormat("Read {0} row(s) from Menus.", list.Count()); return list; } public List<QueuedRecipes> QueuedRecipes() { var list = ImportTableData<Models.QueuedRecipes, QueuedRecipes>(r => new QueuedRecipes { QueueId = (Guid) r["QueueId"], UserId = (Guid) r["UserId"], RecipeId = (Guid) r["RecipeId"], QueuedDate = (DateTime) r["QueuedDate"] }).ToList(); Log.DebugFormat("Read {0} row(s) from QueuedRecipes.", list.Count()); return list; } public List<RecipeRatings> RecipeRatings() { var list = ImportTableData<Models.RecipeRatings, RecipeRatings>(r => new RecipeRatings { RatingId = (Guid) r["RatingId"], UserId = (Guid) r["UserId"], RecipeId = (Guid) r["RecipeId"], Rating = (Int16) r["Rating"] }).ToList(); Log.DebugFormat("Read {0} row(s) from RecipeRatings.", list.Count()); return list; } public List<Data.DTO.ShoppingLists> ShoppingLists() { var list = ImportTableData<Models.ShoppingLists, Data.DTO.ShoppingLists>(r => new Data.DTO.ShoppingLists { ShoppingListId = (Guid) r["ShoppingListId"], UserId = (Guid) r["UserId"], Title = r["Title"] as String }).ToList(); Log.DebugFormat("Read {0} row(s) from ShoppingLists.", list.Count()); return list; } public List<ShoppingListItems> ShoppingListItems() { var list = ImportTableData<Models.ShoppingListItems, ShoppingListItems>(r => new ShoppingListItems { ItemId = (Guid) r["ItemId"], Raw = r["Raw"] as String, Qty = r["Qty"] as Single?, Unit = Unit.ParseNullable<Units>(r["Unit"]), UserId = (Guid) r["UserId"], IngredientId = r["IngredientId"] as Guid?, RecipeId = r["RecipeId"] as Guid?, ShoppingListId = r["ShoppingListId"] as Guid?, CrossedOut = (bool) r["CrossedOut"] }).ToList(); Log.DebugFormat("Read {0} row(s) from ShoppingListItems.", list.Count()); return list; } public void Dispose() { session.Dispose(); } } }
// ------------------------------------------------------------------------------ // Copyright (c) 2014 Microsoft Corporation // // 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. // ------------------------------------------------------------------------------ namespace Microsoft.Live { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Microsoft.Live.Serialization; /// <summary> /// A utility class handles operations required to connect to auth server. /// </summary> internal static class LiveAuthRequestUtility { private const string TokenRequestContentType = "application/x-www-form-urlencoded;charset=UTF-8"; /// <summary> /// An async method to exhange authorization code for auth tokens with the auth server. /// </summary> public static Task<LiveLoginResult> ExchangeCodeForTokenAsync(string clientId, string clientSecret, string redirectUrl, string authorizationCode) { Debug.Assert(!string.IsNullOrEmpty(clientId)); Debug.Assert(!string.IsNullOrEmpty(redirectUrl)); Debug.Assert(!string.IsNullOrEmpty(authorizationCode)); string postContent = LiveAuthUtility.BuildCodeTokenExchangePostContent(clientId, clientSecret, redirectUrl, authorizationCode); return RequestAccessTokenAsync(postContent); } /// <summary> /// An async method to get auth tokens using refresh token. /// </summary> public static Task<LiveLoginResult> RefreshTokenAsync( string clientId, string clientSecret, string redirectUrl, string refreshToken, IEnumerable<string> scopes) { Debug.Assert(!string.IsNullOrEmpty(clientId)); Debug.Assert(!string.IsNullOrEmpty(redirectUrl)); Debug.Assert(!string.IsNullOrEmpty(refreshToken)); string postContent = LiveAuthUtility.BuildRefreshTokenPostContent(clientId, clientSecret, redirectUrl, refreshToken, scopes); return RequestAccessTokenAsync(postContent); } private static Task<LiveLoginResult> RequestAccessTokenAsync(string postContent) { Task<LiveLoginResult> task = Task.Factory.StartNew(() => { return RequestAccessToken(postContent); }); return task; } private static LiveLoginResult RequestAccessToken(string postContent) { string url = LiveAuthUtility.BuildTokenUrl(); HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; HttpWebResponse response = null; LiveLoginResult loginResult = null; request.Method = ApiMethod.Post.ToString().ToUpperInvariant(); request.ContentType = TokenRequestContentType; try { using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) { writer.Write(postContent); } response = request.GetResponse() as HttpWebResponse; loginResult = ReadResponse(response); } catch (WebException e) { response = e.Response as HttpWebResponse; loginResult = ReadResponse(response); } catch (IOException ioe) { loginResult = new LiveLoginResult(new LiveAuthException(AuthErrorCodes.ClientError, ioe.Message)); } finally { if (response != null) { response.Close(); } } if (loginResult == null) { loginResult = new LiveLoginResult(new LiveAuthException(AuthErrorCodes.ClientError, ErrorText.RetrieveTokenError)); } return loginResult; } private static LiveLoginResult ReadResponse(HttpWebResponse response) { LiveConnectSession newSession = null; LiveConnectSessionStatus status = LiveConnectSessionStatus.Unknown; IDictionary<string, object> jsonObj = null; try { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { JsonReader jsReader = new JsonReader(reader.ReadToEnd()); jsonObj = jsReader.ReadValue() as IDictionary<string, object>; } } catch (FormatException fe) { return new LiveLoginResult( new LiveAuthException(AuthErrorCodes.ServerError, fe.Message)); } if (jsonObj != null) { if (jsonObj.ContainsKey(AuthConstants.Error)) { string errorCode = jsonObj[AuthConstants.Error] as string; string errorDescription = string.Empty; if (jsonObj.ContainsKey(AuthConstants.ErrorDescription)) { errorDescription = jsonObj[AuthConstants.ErrorDescription] as string; } return new LiveLoginResult(new LiveAuthException(errorCode, errorDescription)); } else { status = LiveConnectSessionStatus.Connected; newSession = CreateSession(jsonObj); return new LiveLoginResult(status, newSession); } } return new LiveLoginResult( new LiveAuthException(AuthErrorCodes.ServerError, ErrorText.ServerError)); } /// <summary> /// Creates a LiveConnectSession object based on the parsed response. /// </summary> private static LiveConnectSession CreateSession(IDictionary<string, object> result) { var session = new LiveConnectSession(); Debug.Assert(result.ContainsKey(AuthConstants.AccessToken)); if (result.ContainsKey(AuthConstants.AccessToken)) { session.AccessToken = result[AuthConstants.AccessToken] as string; if (result.ContainsKey(AuthConstants.AuthenticationToken)) { session.AuthenticationToken = result[AuthConstants.AuthenticationToken] as string; } if (result.ContainsKey(AuthConstants.ExpiresIn)) { if (result[AuthConstants.ExpiresIn] is string) { session.Expires = CalculateExpiration(result[AuthConstants.ExpiresIn] as string); } else { session.Expires = DateTimeOffset.UtcNow.AddSeconds((int)result[AuthConstants.ExpiresIn]); } } if (result.ContainsKey(AuthConstants.Scope)) { session.Scopes = LiveAuthUtility.ParseScopeString(result[AuthConstants.Scope] as string); } if (result.ContainsKey(AuthConstants.RefreshToken)) { session.RefreshToken = result[AuthConstants.RefreshToken] as string; } } return session; } /// <summary> /// Calculates when the access token will be expired. /// </summary> private static DateTimeOffset CalculateExpiration(string expiresIn) { DateTimeOffset expires = DateTimeOffset.UtcNow; long seconds; if (long.TryParse(expiresIn, out seconds)) { expires = expires.AddSeconds(seconds); } return expires; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans; using Orleans.Runtime; using Orleans.Streams; using Orleans.TestingHost.Utils; using UnitTests.GrainInterfaces; using Xunit; namespace UnitTests.StreamingTests { public class SubscriptionMultiplicityTestRunner { private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); private readonly string streamProviderName; private readonly Logger logger; public SubscriptionMultiplicityTestRunner(string streamProviderName, Logger logger) { if (string.IsNullOrWhiteSpace(streamProviderName)) { throw new ArgumentNullException("streamProviderName"); } this.streamProviderName = streamProviderName; this.logger = logger; } public async Task MultipleParallelSubscriptionTest(Guid streamGuid, string streamNamespace) { // get producer and consumer var producer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid()); var consumer = GrainClient.GrainFactory.GetGrain<IMultipleSubscriptionConsumerGrain>(Guid.NewGuid()); // setup two subscriptions StreamSubscriptionHandle<int> firstSubscriptionHandle = await consumer.BecomeConsumer(streamGuid, streamNamespace, streamProviderName); StreamSubscriptionHandle<int> secondSubscriptionHandle = await consumer.BecomeConsumer(streamGuid, streamNamespace, streamProviderName); // produce some messages await producer.BecomeProducer(streamGuid, streamNamespace, streamProviderName); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); // check await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 2, lastTry), Timeout); // unsubscribe await consumer.StopConsuming(firstSubscriptionHandle); await consumer.StopConsuming(secondSubscriptionHandle); } public async Task MultipleLinearSubscriptionTest(Guid streamGuid, string streamNamespace) { // get producer and consumer var producer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid()); var consumer = GrainClient.GrainFactory.GetGrain<IMultipleSubscriptionConsumerGrain>(Guid.NewGuid()); await producer.BecomeProducer(streamGuid, streamNamespace, streamProviderName); // setup one subscription and send messsages StreamSubscriptionHandle<int> firstSubscriptionHandle = await consumer.BecomeConsumer(streamGuid, streamNamespace, streamProviderName); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); // clear counts await consumer.ClearNumberConsumed(); await producer.ClearNumberProduced(); // remove first subscription and send messages await consumer.StopConsuming(firstSubscriptionHandle); // setup second subscription and send messages StreamSubscriptionHandle<int> secondSubscriptionHandle = await consumer.BecomeConsumer(streamGuid, streamNamespace, streamProviderName); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); // remove second subscription await consumer.StopConsuming(secondSubscriptionHandle); } public async Task MultipleSubscriptionTest_AddRemove(Guid streamGuid, string streamNamespace) { // get producer and consumer var producer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid()); var consumer = GrainClient.GrainFactory.GetGrain<IMultipleSubscriptionConsumerGrain>(Guid.NewGuid()); await producer.BecomeProducer(streamGuid, streamNamespace, streamProviderName); // setup one subscription and send messsages StreamSubscriptionHandle<int> firstSubscriptionHandle = await consumer.BecomeConsumer(streamGuid, streamNamespace, streamProviderName); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); // clear counts await consumer.ClearNumberConsumed(); await producer.ClearNumberProduced(); // setup second subscription and send messages StreamSubscriptionHandle<int> secondSubscriptionHandle = await consumer.BecomeConsumer(streamGuid, streamNamespace, streamProviderName); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 2, lastTry), Timeout); // clear counts await consumer.ClearNumberConsumed(); await producer.ClearNumberProduced(); // remove first subscription and send messages await consumer.StopConsuming(firstSubscriptionHandle); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); // remove second subscription await consumer.StopConsuming(secondSubscriptionHandle); } public async Task ResubscriptionTest(Guid streamGuid, string streamNamespace) { // get producer and consumer var producer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid()); var consumer = GrainClient.GrainFactory.GetGrain<IMultipleSubscriptionConsumerGrain>(Guid.NewGuid()); await producer.BecomeProducer(streamGuid, streamNamespace, streamProviderName); // setup one subscription and send messsages StreamSubscriptionHandle<int> firstSubscriptionHandle = await consumer.BecomeConsumer(streamGuid, streamNamespace, streamProviderName); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); // Resume StreamSubscriptionHandle<int> resumeHandle = await consumer.Resume(firstSubscriptionHandle); Assert.Equal(firstSubscriptionHandle, resumeHandle); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); // remove subscription await consumer.StopConsuming(resumeHandle); } public async Task ResubscriptionAfterDeactivationTest(Guid streamGuid, string streamNamespace) { // get producer and consumer var producer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid()); var consumer = GrainClient.GrainFactory.GetGrain<IMultipleSubscriptionConsumerGrain>(Guid.NewGuid()); await producer.BecomeProducer(streamGuid, streamNamespace, streamProviderName); // setup one subscription and send messsages StreamSubscriptionHandle<int> firstSubscriptionHandle = await consumer.BecomeConsumer(streamGuid, streamNamespace, streamProviderName); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); // Deactivate grain await consumer.Deactivate(); // make sure grain has time to deactivate. await Task.Delay(TimeSpan.FromMilliseconds(100)); // clear producer counts await producer.ClearNumberProduced(); // Resume StreamSubscriptionHandle<int> resumeHandle = await consumer.Resume(firstSubscriptionHandle); Assert.Equal(firstSubscriptionHandle, resumeHandle); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); // remove subscription await consumer.StopConsuming(resumeHandle); } public async Task ActiveSubscriptionTest(Guid streamGuid, string streamNamespace) { const int subscriptionCount = 10; // get producer and consumer var consumer = GrainClient.GrainFactory.GetGrain<IMultipleSubscriptionConsumerGrain>(Guid.NewGuid()); // create expected subscriptions IEnumerable<Task<StreamSubscriptionHandle<int>>> subscriptionTasks = Enumerable.Range(0, subscriptionCount) .Select(async i => await consumer.BecomeConsumer(streamGuid, streamNamespace, streamProviderName)); List<StreamSubscriptionHandle<int>> expectedSubscriptions = (await Task.WhenAll(subscriptionTasks)).ToList(); // query actuall subscriptions IList<StreamSubscriptionHandle<int>> actualSubscriptions = await consumer.GetAllSubscriptions(streamGuid, streamNamespace, streamProviderName); // validate Assert.Equal(subscriptionCount, actualSubscriptions.Count); Assert.Equal(subscriptionCount, expectedSubscriptions.Count); foreach (StreamSubscriptionHandle<int> subscription in actualSubscriptions) { Assert.True(expectedSubscriptions.Contains(subscription), "Subscription Match"); } // unsubscribe from one of the subscriptions StreamSubscriptionHandle<int> firstHandle = expectedSubscriptions.First(); await consumer.StopConsuming(firstHandle); expectedSubscriptions.Remove(firstHandle); // query actuall subscriptions again actualSubscriptions = await consumer.GetAllSubscriptions(streamGuid, streamNamespace, streamProviderName); // validate Assert.Equal(subscriptionCount-1, actualSubscriptions.Count); Assert.Equal(subscriptionCount-1, expectedSubscriptions.Count); foreach (StreamSubscriptionHandle<int> subscription in actualSubscriptions) { Assert.True(expectedSubscriptions.Contains(subscription), "Subscription Match"); } // unsubscribe from the rest of the subscriptions expectedSubscriptions.ForEach( async h => await consumer.StopConsuming(h)); // query actuall subscriptions again actualSubscriptions = await consumer.GetAllSubscriptions(streamGuid, streamNamespace, streamProviderName); // validate Assert.Equal(0, actualSubscriptions.Count); } public async Task TwoIntermitentStreamTest(Guid streamGuid) { const string streamNamespace1 = "streamNamespace1"; const string streamNamespace2 = "streamNamespace2"; // send events on first stream ///////////////////////////// var producer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid()); var consumer = GrainClient.GrainFactory.GetGrain<IMultipleSubscriptionConsumerGrain>(Guid.NewGuid()); await producer.BecomeProducer(streamGuid, streamNamespace1, streamProviderName); StreamSubscriptionHandle<int> handle = await consumer.BecomeConsumer(streamGuid, streamNamespace1, streamProviderName); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); // send some events on second stream ///////////////////////////// var producer2 = GrainClient.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid()); var consumer2 = GrainClient.GrainFactory.GetGrain<IMultipleSubscriptionConsumerGrain>(Guid.NewGuid()); await producer2.BecomeProducer(streamGuid, streamNamespace2, streamProviderName); StreamSubscriptionHandle<int> handle2 = await consumer2.BecomeConsumer(streamGuid, streamNamespace2, streamProviderName); await producer2.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer2.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer2, consumer2, 1, lastTry), Timeout); // send some events on first stream again ///////////////////////////// await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, 1, lastTry), Timeout); await consumer.StopConsuming(handle); await consumer2.StopConsuming(handle2); } public async Task SubscribeFromClientTest(Guid streamGuid, string streamNamespace) { // get producer and consumer var producer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid()); int eventCount = 0; var provider = GrainClient.GetStreamProvider(streamProviderName); var stream = provider.GetStream<int>(streamGuid, streamNamespace); var handle = await stream.SubscribeAsync((e,t) => { eventCount++; return TaskDone.Done; }); // produce some messages await producer.BecomeProducer(streamGuid, streamNamespace, streamProviderName); await producer.StartPeriodicProducing(); await Task.Delay(TimeSpan.FromMilliseconds(1000)); await producer.StopPeriodicProducing(); // check await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, () => eventCount, lastTry), Timeout); // unsubscribe await handle.UnsubscribeAsync(); } private async Task<bool> CheckCounters(ISampleStreaming_ProducerGrain producer, IMultipleSubscriptionConsumerGrain consumer, int consumerCount, bool assertIsTrue) { var numProduced = await producer.GetNumberProduced(); var numConsumed = await consumer.GetNumberConsumed(); if (assertIsTrue) { Assert.True(numConsumed.Values.All(v => v.Item2 == 0), "Errors"); Assert.True(numProduced > 0, "Events were not produced"); Assert.Equal(consumerCount, numConsumed.Count); foreach (int consumed in numConsumed.Values.Select(v => v.Item1)) { Assert.Equal(numProduced, consumed); } } else if (numProduced <= 0 || // no events produced? consumerCount != numConsumed.Count || // subscription counts are wrong? numConsumed.Values.Any(consumedCount => consumedCount.Item1 != numProduced) ||// consumed events don't match produced events for any subscription? numConsumed.Values.Any(v => v.Item2 != 0)) // stream errors { if (numProduced <= 0) { logger.Info("numProduced <= 0: Events were not produced"); } if (consumerCount != numConsumed.Count) { logger.Info("consumerCount != numConsumed.Count: Incorrect number of consumers. consumerCount = {0}, numConsumed.Count = {1}", consumerCount, numConsumed.Count); } foreach (var consumed in numConsumed) { if (numProduced != consumed.Value.Item1) { logger.Info("numProduced != consumed: Produced and consumed counts do not match. numProduced = {0}, consumed = {1}", numProduced, consumed.Key.HandleId + " -> " + consumed.Value); //numProduced, Utils.DictionaryToString(numConsumed)); } } return false; } logger.Info("All counts are equal. numProduced = {0}, numConsumed = {1}", numProduced, Utils.EnumerableToString(numConsumed, kvp => kvp.Key.HandleId.ToString() + "->" + kvp.Value.ToString())); return true; } private async Task<bool> CheckCounters(ISampleStreaming_ProducerGrain producer, Func<int> eventCount, bool assertIsTrue) { var numProduced = await producer.GetNumberProduced(); var numConsumed = eventCount(); if (assertIsTrue) { Assert.True(numProduced > 0, "Events were not produced"); Assert.Equal(numProduced, numConsumed); } else if (numProduced <= 0 || // no events produced? numProduced != numConsumed) { if (numProduced <= 0) { logger.Info("numProduced <= 0: Events were not produced"); } if (numProduced != numConsumed) { logger.Info("numProduced != numConsumed: Produced and consumed counts do not match. numProduced = {0}, consumed = {1}", numProduced, numConsumed); } return false; } logger.Info("All counts are equal. numProduced = {0}, numConsumed = {1}", numProduced, numConsumed); return true; } } }
using System; using System.Globalization; using System.Reactive.Linq; using System.Reactive.Subjects; using Avalonia.Data.Converters; using Avalonia.Logging; using Avalonia.Reactive; using Avalonia.Utilities; namespace Avalonia.Data.Core { /// <summary> /// Binds to an expression on an object using a type value converter to convert the values /// that are sent and received. /// </summary> public class BindingExpression : LightweightObservableBase<object>, ISubject<object>, IDescription { private readonly ExpressionObserver _inner; private readonly Type _targetType; private readonly object _fallbackValue; private readonly object _targetNullValue; private readonly BindingPriority _priority; InnerListener _innerListener; WeakReference<object> _value; /// <summary> /// Initializes a new instance of the <see cref="ExpressionObserver"/> class. /// </summary> /// <param name="inner">The <see cref="ExpressionObserver"/>.</param> /// <param name="targetType">The type to convert the value to.</param> public BindingExpression(ExpressionObserver inner, Type targetType) : this(inner, targetType, DefaultValueConverter.Instance) { } /// <summary> /// Initializes a new instance of the <see cref="ExpressionObserver"/> class. /// </summary> /// <param name="inner">The <see cref="ExpressionObserver"/>.</param> /// <param name="targetType">The type to convert the value to.</param> /// <param name="converter">The value converter to use.</param> /// <param name="converterParameter"> /// A parameter to pass to <paramref name="converter"/>. /// </param> /// <param name="priority">The binding priority.</param> public BindingExpression( ExpressionObserver inner, Type targetType, IValueConverter converter, object converterParameter = null, BindingPriority priority = BindingPriority.LocalValue) : this(inner, targetType, AvaloniaProperty.UnsetValue, AvaloniaProperty.UnsetValue, converter, converterParameter, priority) { } /// <summary> /// Initializes a new instance of the <see cref="ExpressionObserver"/> class. /// </summary> /// <param name="inner">The <see cref="ExpressionObserver"/>.</param> /// <param name="targetType">The type to convert the value to.</param> /// <param name="fallbackValue"> /// The value to use when the binding is unable to produce a value. /// </param> /// <param name="targetNullValue"> /// The value to use when the binding result is null. /// </param> /// <param name="converter">The value converter to use.</param> /// <param name="converterParameter"> /// A parameter to pass to <paramref name="converter"/>. /// </param> /// <param name="priority">The binding priority.</param> public BindingExpression( ExpressionObserver inner, Type targetType, object fallbackValue, object targetNullValue, IValueConverter converter, object converterParameter = null, BindingPriority priority = BindingPriority.LocalValue) { Contract.Requires<ArgumentNullException>(inner != null); Contract.Requires<ArgumentNullException>(targetType != null); Contract.Requires<ArgumentNullException>(converter != null); _inner = inner; _targetType = targetType; Converter = converter; ConverterParameter = converterParameter; _fallbackValue = fallbackValue; _targetNullValue = targetNullValue; _priority = priority; } /// <summary> /// Gets the converter to use on the expression. /// </summary> public IValueConverter Converter { get; } /// <summary> /// Gets a parameter to pass to <see cref="Converter"/>. /// </summary> public object ConverterParameter { get; } /// <inheritdoc/> string IDescription.Description => _inner.Expression; /// <inheritdoc/> public void OnCompleted() { } /// <inheritdoc/> public void OnError(Exception error) { } /// <inheritdoc/> public void OnNext(object value) { if (value == BindingOperations.DoNothing) { return; } using (_inner.Subscribe(_ => { })) { var type = _inner.ResultType; if (type != null) { var converted = Converter.ConvertBack( value, type, ConverterParameter, CultureInfo.CurrentCulture); if (converted == BindingOperations.DoNothing) { return; } if (converted == AvaloniaProperty.UnsetValue) { converted = TypeUtilities.Default(type); _inner.SetValue(converted, _priority); } else if (converted is BindingNotification) { var notification = converted as BindingNotification; if (notification.ErrorType == BindingErrorType.None) { throw new AvaloniaInternalException( "IValueConverter should not return non-errored BindingNotification."); } PublishNext(notification); if (_fallbackValue != AvaloniaProperty.UnsetValue) { if (TypeUtilities.TryConvert( type, _fallbackValue, CultureInfo.InvariantCulture, out converted)) { _inner.SetValue(converted, _priority); } else { Logger.TryGet(LogEventLevel.Error, LogArea.Binding)?.Log( this, "Could not convert FallbackValue {FallbackValue} to {Type}", _fallbackValue, type); } } } else { _inner.SetValue(converted, _priority); } } } } protected override void Initialize() => _innerListener = new InnerListener(this); protected override void Deinitialize() => _innerListener.Dispose(); protected override void Subscribed(IObserver<object> observer, bool first) { if (!first && _value != null && _value.TryGetTarget(out var val)) { observer.OnNext(val); } } /// <inheritdoc/> private object ConvertValue(object value) { if (value == null && _targetNullValue != AvaloniaProperty.UnsetValue) { return _targetNullValue; } if (value == BindingOperations.DoNothing) { return value; } var notification = value as BindingNotification; if (notification == null) { var converted = Converter.Convert( value, _targetType, ConverterParameter, CultureInfo.CurrentCulture); if (converted == BindingOperations.DoNothing) { return converted; } notification = converted as BindingNotification; if (notification?.ErrorType == BindingErrorType.None) { converted = notification.Value; } if (_fallbackValue != AvaloniaProperty.UnsetValue && (converted == AvaloniaProperty.UnsetValue || converted is BindingNotification)) { var fallback = ConvertFallback(); converted = Merge(converted, fallback); } return converted; } else { return ConvertValue(notification); } } private BindingNotification ConvertValue(BindingNotification notification) { if (notification.HasValue) { var converted = ConvertValue(notification.Value); notification = Merge(notification, converted); } else if (_fallbackValue != AvaloniaProperty.UnsetValue) { var fallback = ConvertFallback(); notification = Merge(notification, fallback); } return notification; } private BindingNotification ConvertFallback() { object converted; if (_fallbackValue == AvaloniaProperty.UnsetValue) { throw new AvaloniaInternalException("Cannot call ConvertFallback with no fallback value"); } if (TypeUtilities.TryConvert( _targetType, _fallbackValue, CultureInfo.InvariantCulture, out converted)) { return new BindingNotification(converted); } else { return new BindingNotification( new InvalidCastException( $"Could not convert FallbackValue '{_fallbackValue}' to '{_targetType}'"), BindingErrorType.Error); } } private static BindingNotification Merge(object a, BindingNotification b) { var an = a as BindingNotification; if (an != null) { Merge(an, b); return an; } else { return b; } } private static BindingNotification Merge(BindingNotification a, object b) { var bn = b as BindingNotification; if (bn != null) { Merge(a, bn); } else { a.SetValue(b); } return a; } private static BindingNotification Merge(BindingNotification a, BindingNotification b) { if (b.HasValue) { a.SetValue(b.Value); } else { a.ClearValue(); } if (b.Error != null) { a.AddError(b.Error, b.ErrorType); } return a; } public class InnerListener : IObserver<object>, IDisposable { private readonly BindingExpression _owner; private readonly IDisposable _dispose; public InnerListener(BindingExpression owner) { _owner = owner; _dispose = owner._inner.Subscribe(this); } public void Dispose() => _dispose.Dispose(); public void OnCompleted() => _owner.PublishCompleted(); public void OnError(Exception error) => _owner.PublishError(error); public void OnNext(object value) { if (value == BindingOperations.DoNothing) { return; } var converted = _owner.ConvertValue(value); if (converted == BindingOperations.DoNothing) { return; } _owner._value = new WeakReference<object>(converted); _owner.PublishNext(converted); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using Lucene.Net.Documents; using FieldInvertState = Lucene.Net.Index.FieldInvertState; using Term = Lucene.Net.Index.Term; using SmallFloat = Lucene.Net.Util.SmallFloat; using IDFExplanation = Lucene.Net.Search.Explanation.IDFExplanation; namespace Lucene.Net.Search { /// <summary>Expert: Scoring API. /// <p/>Subclasses implement search scoring. /// /// <p/>The score of query <c>q</c> for document <c>d</c> correlates to the /// cosine-distance or dot-product between document and query vectors in a /// <a href="http://en.wikipedia.org/wiki/Vector_Space_Model"> /// Vector Space Model (VSM) of Information Retrieval</a>. /// A document whose vector is closer to the query vector in that model is scored higher. /// /// The score is computed as follows: /// /// <p/> /// <table cellpadding="1" cellspacing="0" border="1" align="center"> /// <tr><td> /// <table cellpadding="1" cellspacing="0" border="0" align="center"> /// <tr> /// <td valign="middle" align="right" rowspan="1"> /// score(q,d) &#160; = &#160; /// <A HREF="#formula_coord">coord(q,d)</A> &#160;&#183;&#160; /// <A HREF="#formula_queryNorm">queryNorm(q)</A> &#160;&#183;&#160; /// </td> /// <td valign="bottom" align="center" rowspan="1"> /// <big><big><big>&#8721;</big></big></big> /// </td> /// <td valign="middle" align="right" rowspan="1"> /// <big><big>(</big></big> /// <A HREF="#formula_tf">tf(t in d)</A> &#160;&#183;&#160; /// <A HREF="#formula_idf">idf(t)</A><sup>2</sup> &#160;&#183;&#160; /// <A HREF="#formula_termBoost">t.Boost</A>&#160;&#183;&#160; /// <A HREF="#formula_norm">norm(t,d)</A> /// <big><big>)</big></big> /// </td> /// </tr> /// <tr valigh="top"> /// <td></td> /// <td align="center"><small>t in q</small></td> /// <td></td> /// </tr> /// </table> /// </td></tr> /// </table> /// /// <p/> where /// <list type="bullet"> /// <item> /// <A NAME="formula_tf"></A> /// <b>tf(t in d)</b> /// correlates to the term's <i>frequency</i>, /// defined as the number of times term <i>t</i> appears in the currently scored document <i>d</i>. /// Documents that have more occurrences of a given term receive a higher score. /// The default computation for <i>tf(t in d)</i> in /// <see cref="Lucene.Net.Search.DefaultSimilarity.Tf(float)">DefaultSimilarity</see> is: /// /// <br/>&#160;<br/> /// <table cellpadding="2" cellspacing="2" border="0" align="center"> /// <tr> /// <td valign="middle" align="right" rowspan="1"> /// <see cref="Lucene.Net.Search.DefaultSimilarity.Tf(float)">tf(t in d)</see> &#160; = &#160; /// </td> /// <td valign="top" align="center" rowspan="1"> /// frequency<sup><big>&#189;</big></sup> /// </td> /// </tr> /// </table> /// <br/>&#160;<br/> /// </item> /// /// <item> /// <A NAME="formula_idf"></A> /// <b>idf(t)</b> stands for Inverse Document Frequency. This value /// correlates to the inverse of <i>docFreq</i> /// (the number of documents in which the term <i>t</i> appears). /// This means rarer terms give higher contribution to the total score. /// The default computation for <i>idf(t)</i> in /// <see cref="Lucene.Net.Search.DefaultSimilarity.Idf(int, int)">DefaultSimilarity</see> is: /// /// <br/>&#160;<br/> /// <table cellpadding="2" cellspacing="2" border="0" align="center"> /// <tr> /// <td valign="middle" align="right"> /// <see cref="Lucene.Net.Search.DefaultSimilarity.Idf(int, int)">idf(t)</see>&#160; = &#160; /// </td> /// <td valign="middle" align="center"> /// 1 + log <big>(</big> /// </td> /// <td valign="middle" align="center"> /// <table> /// <tr><td align="center"><small>numDocs</small></td></tr> /// <tr><td align="center">&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;</td></tr> /// <tr><td align="center"><small>docFreq+1</small></td></tr> /// </table> /// </td> /// <td valign="middle" align="center"> /// <big>)</big> /// </td> /// </tr> /// </table> /// <br/>&#160;<br/> /// </item> /// /// <item> /// <A NAME="formula_coord"></A> /// <b>coord(q,d)</b> /// is a score factor based on how many of the query terms are found in the specified document. /// Typically, a document that contains more of the query's terms will receive a higher score /// than another document with fewer query terms. /// This is a search time factor computed in /// <see cref="Coord(int, int)">coord(q,d)</see> /// by the Similarity in effect at search time. /// <br/>&#160;<br/> /// </item> /// /// <item><b> /// <A NAME="formula_queryNorm"></A> /// queryNorm(q) /// </b> /// is a normalizing factor used to make scores between queries comparable. /// This factor does not affect document ranking (since all ranked documents are multiplied by the same factor), /// but rather just attempts to make scores from different queries (or even different indexes) comparable. /// This is a search time factor computed by the Similarity in effect at search time. /// /// The default computation in /// <see cref="Lucene.Net.Search.DefaultSimilarity.QueryNorm(float)">DefaultSimilarity</see> /// is: /// <br/>&#160;<br/> /// <table cellpadding="1" cellspacing="0" border="0" align="center"> /// <tr> /// <td valign="middle" align="right" rowspan="1"> /// queryNorm(q) &#160; = &#160; /// <see cref="Lucene.Net.Search.DefaultSimilarity.QueryNorm(float)">queryNorm(sumOfSquaredWeights)</see> /// &#160; = &#160; /// </td> /// <td valign="middle" align="center" rowspan="1"> /// <table> /// <tr><td align="center"><big>1</big></td></tr> /// <tr><td align="center"><big> /// &#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211;&#8211; /// </big></td></tr> /// <tr><td align="center">sumOfSquaredWeights<sup><big>&#189;</big></sup></td></tr> /// </table> /// </td> /// </tr> /// </table> /// <br/>&#160;<br/> /// /// The sum of squared weights (of the query terms) is /// computed by the query <see cref="Lucene.Net.Search.Weight" /> object. /// For example, a <see cref="Lucene.Net.Search.BooleanQuery">boolean query</see> /// computes this value as: /// /// <br/>&#160;<br/> /// <table cellpadding="1" cellspacing="0" border="0" align="center"> /// <tr> /// <td valign="middle" align="right" rowspan="1"> /// <see cref="Lucene.Net.Search.Weight.GetSumOfSquaredWeights">GetSumOfSquaredWeights</see> &#160; = &#160; /// <see cref="Lucene.Net.Search.Query.Boost">q.Boost</see> <sup><big>2</big></sup> /// &#160;&#183;&#160; /// </td> /// <td valign="bottom" align="center" rowspan="1"> /// <big><big><big>&#8721;</big></big></big> /// </td> /// <td valign="middle" align="right" rowspan="1"> /// <big><big>(</big></big> /// <A HREF="#formula_idf">idf(t)</A> &#160;&#183;&#160; /// <A HREF="#formula_termBoost">t.Boost</A> /// <big><big>) <sup>2</sup> </big></big> /// </td> /// </tr> /// <tr valigh="top"> /// <td></td> /// <td align="center"><small>t in q</small></td> /// <td></td> /// </tr> /// </table> /// <br/>&#160;<br/> /// /// </item> /// /// <item> /// <A NAME="formula_termBoost"></A> /// <b>t.Boost</b> /// is a search time boost of term <i>t</i> in the query <i>q</i> as /// specified in the query text /// (see <A HREF="../../../../../../queryparsersyntax.html#Boosting a Term">query syntax</A>), /// or as set by application calls to /// <see cref="Lucene.Net.Search.Query.Boost" />. /// Notice that there is really no direct API for accessing a boost of one term in a multi term query, /// but rather multi terms are represented in a query as multi /// <see cref="Lucene.Net.Search.TermQuery">TermQuery</see> objects, /// and so the boost of a term in the query is accessible by calling the sub-query /// <see cref="Lucene.Net.Search.Query.Boost" />. /// <br/>&#160;<br/> /// </item> /// /// <item> /// <A NAME="formula_norm"></A> /// <b>norm(t,d)</b> encapsulates a few (indexing time) boost and length factors: /// /// <list type="bullet"> /// <item><b>Document boost</b> - set by calling /// <see cref="Lucene.Net.Documents.Document.Boost">doc.Boost</see> /// before adding the document to the index. /// </item> /// <item><b>Field boost</b> - set by calling /// <see cref="IFieldable.Boost">field.Boost</see> /// before adding the field to a document. /// </item> /// <item><see cref="LengthNorm(String, int)">LengthNorm(field)</see> - computed /// when the document is added to the index in accordance with the number of tokens /// of this field in the document, so that shorter fields contribute more to the score. /// LengthNorm is computed by the Similarity class in effect at indexing. /// </item> /// </list> /// /// <p/> /// When a document is added to the index, all the above factors are multiplied. /// If the document has multiple fields with the same name, all their boosts are multiplied together: /// /// <br/>&#160;<br/> /// <table cellpadding="1" cellspacing="0" border="0" align="center"> /// <tr> /// <td valign="middle" align="right" rowspan="1"> /// norm(t,d) &#160; = &#160; /// <see cref="Lucene.Net.Documents.Document.Boost">doc.Boost</see> /// &#160;&#183;&#160; /// <see cref="LengthNorm(String, int)">LengthNorm(field)</see> /// &#160;&#183;&#160; /// </td> /// <td valign="bottom" align="center" rowspan="1"> /// <big><big><big>&#8719;</big></big></big> /// </td> /// <td valign="middle" align="right" rowspan="1"> /// <see cref="IFieldable.Boost">field.Boost</see> /// </td> /// </tr> /// <tr valigh="top"> /// <td></td> /// <td align="center"><small>field <i><b>f</b></i> in <i>d</i> named as <i><b>t</b></i></small></td> /// <td></td> /// </tr> /// </table> /// <br/>&#160;<br/> /// However the resulted <i>norm</i> value is <see cref="EncodeNorm(float)">encoded</see> as a single byte /// before being stored. /// At search time, the norm byte value is read from the index /// <see cref="Lucene.Net.Store.Directory">directory</see> and /// <see cref="DecodeNorm(byte)">decoded</see> back to a float <i>norm</i> value. /// This encoding/decoding, while reducing index size, comes with the price of /// precision loss - it is not guaranteed that decode(encode(x)) = x. /// For instance, decode(encode(0.89)) = 0.75. /// Also notice that search time is too late to modify this <i>norm</i> part of scoring, e.g. by /// using a different <see cref="Similarity" /> for search. /// <br/>&#160;<br/> /// </item> /// </list> /// /// </summary> /// <seealso cref="Default"> /// </seealso> /// <seealso cref="Lucene.Net.Index.IndexWriter.Similarity"> /// </seealso> /// <seealso cref="Searcher.Similarity"> /// </seealso> [Serializable] public abstract class Similarity { protected Similarity() { InitBlock(); } [Serializable] private class AnonymousClassIDFExplanation1:IDFExplanation { public AnonymousClassIDFExplanation1(int df, int max, float idf, Similarity enclosingInstance) { InitBlock(df, max, idf, enclosingInstance); } private void InitBlock(int df, int max, float idf, Similarity enclosingInstance) { this.df = df; this.max = max; this.idf = idf; this.enclosingInstance = enclosingInstance; } private int df; private int max; private float idf; private Similarity enclosingInstance; public Similarity Enclosing_Instance { get { return enclosingInstance; } } //@Override public override System.String Explain() { return "idf(docFreq=" + df + ", maxDocs=" + max + ")"; } //@Override public override float Idf { get { return idf; } } } [Serializable] private class AnonymousClassIDFExplanation3:IDFExplanation { public AnonymousClassIDFExplanation3(float fIdf, System.Text.StringBuilder exp, Similarity enclosingInstance) { InitBlock(fIdf, exp, enclosingInstance); } private void InitBlock(float fIdf, System.Text.StringBuilder exp, Similarity enclosingInstance) { this.fIdf = fIdf; this.exp = exp; this.enclosingInstance = enclosingInstance; } private float fIdf; private System.Text.StringBuilder exp; private Similarity enclosingInstance; public Similarity Enclosing_Instance { get { return enclosingInstance; } } //@Override public override float Idf { get { return fIdf; } } //@Override public override System.String Explain() { return exp.ToString(); } } private void InitBlock() { } /// <summary>The Similarity implementation used by default.</summary> private static Similarity defaultImpl = new DefaultSimilarity(); public const int NO_DOC_ID_PROVIDED = - 1; /// <summary>Gets or sets the default Similarity implementation /// used by indexing and search code. /// <p/>This is initially an instance of <see cref="DefaultSimilarity" />. /// </summary> /// <seealso cref="Searcher.Similarity"> /// </seealso> /// <seealso cref="Lucene.Net.Index.IndexWriter.SetSimilarity(Similarity)"> /// </seealso> public static Similarity Default { get { return defaultImpl; } set { defaultImpl = value; } } /// <summary>Cache of decoded bytes. </summary> private static readonly float[] NORM_TABLE = new float[256]; /// <summary>Decodes a normalization factor stored in an index.</summary> /// <seealso cref="EncodeNorm(float)"> /// </seealso> public static float DecodeNorm(byte b) { return NORM_TABLE[b & 0xFF]; // & 0xFF maps negative bytes to positive above 127 } /// <summary>Returns a table for decoding normalization bytes.</summary> /// <seealso cref="EncodeNorm(float)"> /// </seealso> public static float[] GetNormDecoder() { return NORM_TABLE; } /// <summary> Compute the normalization value for a field, given the accumulated /// state of term processing for this field (see <see cref="FieldInvertState" />). /// /// <p/>Implementations should calculate a float value based on the field /// state and then return that value. /// /// <p/>For backward compatibility this method by default calls /// <see cref="LengthNorm(String, int)" /> passing /// <see cref="FieldInvertState.Length" /> as the second argument, and /// then multiplies this value by <see cref="FieldInvertState.Boost" />.<p/> /// /// <p/><b>WARNING</b>: This API is new and experimental and may /// suddenly change.<p/> /// /// </summary> /// <param name="field">field name /// </param> /// <param name="state">current processing state for this field /// </param> /// <returns> the calculated float norm /// </returns> public virtual float ComputeNorm(System.String field, FieldInvertState state) { return (float) (state.Boost * LengthNorm(field, state.Length)); } /// <summary>Computes the normalization value for a field given the total number of /// terms contained in a field. These values, together with field boosts, are /// stored in an index and multipled into scores for hits on each field by the /// search code. /// /// <p/>Matches in longer fields are less precise, so implementations of this /// method usually return smaller values when <c>numTokens</c> is large, /// and larger values when <c>numTokens</c> is small. /// /// <p/>Note that the return values are computed under /// <see cref="Lucene.Net.Index.IndexWriter.AddDocument(Lucene.Net.Documents.Document)" /> /// and then stored using /// <see cref="EncodeNorm(float)" />. /// Thus they have limited precision, and documents /// must be re-indexed if this method is altered. /// /// </summary> /// <param name="fieldName">the name of the field /// </param> /// <param name="numTokens">the total number of tokens contained in fields named /// <i>fieldName</i> of <i>doc</i>. /// </param> /// <returns> a normalization factor for hits on this field of this document /// /// </returns> /// <seealso cref="Lucene.Net.Documents.AbstractField.Boost" /> public abstract float LengthNorm(System.String fieldName, int numTokens); /// <summary>Computes the normalization value for a query given the sum of the squared /// weights of each of the query terms. This value is then multipled into the /// weight of each query term. /// /// <p/>This does not affect ranking, but rather just attempts to make scores /// from different queries comparable. /// /// </summary> /// <param name="sumOfSquaredWeights">the sum of the squares of query term weights /// </param> /// <returns> a normalization factor for query weights /// </returns> public abstract float QueryNorm(float sumOfSquaredWeights); /// <summary>Encodes a normalization factor for storage in an index. /// /// <p/>The encoding uses a three-bit mantissa, a five-bit exponent, and /// the zero-exponent point at 15, thus /// representing values from around 7x10^9 to 2x10^-9 with about one /// significant decimal digit of accuracy. Zero is also represented. /// Negative numbers are rounded up to zero. Values too large to represent /// are rounded down to the largest representable value. Positive values too /// small to represent are rounded up to the smallest positive representable /// value. /// /// </summary> /// <seealso cref="Lucene.Net.Documents.AbstractField.Boost" /> /// <seealso cref="Lucene.Net.Util.SmallFloat" /> public static byte EncodeNorm(float f) { return (byte) SmallFloat.FloatToByte315(f); } /// <summary>Computes a score factor based on a term or phrase's frequency in a /// document. This value is multiplied by the <see cref="Idf(int, int)" /> /// factor for each term in the query and these products are then summed to /// form the initial score for a document. /// /// <p/>Terms and phrases repeated in a document indicate the topic of the /// document, so implementations of this method usually return larger values /// when <c>freq</c> is large, and smaller values when <c>freq</c> /// is small. /// /// <p/>The default implementation calls <see cref="Tf(float)" />. /// /// </summary> /// <param name="freq">the frequency of a term within a document /// </param> /// <returns> a score factor based on a term's within-document frequency /// </returns> public virtual float Tf(int freq) { return Tf((float) freq); } /// <summary>Computes the amount of a sloppy phrase match, based on an edit distance. /// This value is summed for each sloppy phrase match in a document to form /// the frequency that is passed to <see cref="Tf(float)" />. /// /// <p/>A phrase match with a small edit distance to a document passage more /// closely matches the document, so implementations of this method usually /// return larger values when the edit distance is small and smaller values /// when it is large. /// /// </summary> /// <seealso cref="PhraseQuery.Slop" /> /// <param name="distance">the edit distance of this sloppy phrase match </param> /// <returns> the frequency increment for this match </returns> public abstract float SloppyFreq(int distance); /// <summary>Computes a score factor based on a term or phrase's frequency in a /// document. This value is multiplied by the <see cref="Idf(int, int)" /> /// factor for each term in the query and these products are then summed to /// form the initial score for a document. /// /// <p/>Terms and phrases repeated in a document indicate the topic of the /// document, so implementations of this method usually return larger values /// when <c>freq</c> is large, and smaller values when <c>freq</c> /// is small. /// /// </summary> /// <param name="freq">the frequency of a term within a document /// </param> /// <returns> a score factor based on a term's within-document frequency /// </returns> public abstract float Tf(float freq); /// <summary> Computes a score factor for a simple term and returns an explanation /// for that score factor. /// /// <p/> /// The default implementation uses: /// /// <code> /// idf(searcher.docFreq(term), searcher.MaxDoc); /// </code> /// /// Note that <see cref="Searcher.MaxDoc" /> is used instead of /// <see cref="Lucene.Net.Index.IndexReader.NumDocs()" /> because it is /// proportional to <see cref="Searcher.DocFreq(Term)" /> , i.e., when one is /// inaccurate, so is the other, and in the same direction. /// /// </summary> /// <param name="term">the term in question /// </param> /// <param name="searcher">the document collection being searched /// </param> /// <returns> an IDFExplain object that includes both an idf score factor /// and an explanation for the term. /// </returns> /// <throws> IOException </throws> public virtual IDFExplanation IdfExplain(Term term, Searcher searcher) { int df = searcher.DocFreq(term); int max = searcher.MaxDoc; float idf2 = Idf(df, max); return new AnonymousClassIDFExplanation1(df, max, idf2, this); } /// <summary> Computes a score factor for a phrase. /// /// <p/> /// The default implementation sums the idf factor for /// each term in the phrase. /// /// </summary> /// <param name="terms">the terms in the phrase /// </param> /// <param name="searcher">the document collection being searched /// </param> /// <returns> an IDFExplain object that includes both an idf /// score factor for the phrase and an explanation /// for each term. /// </returns> /// <throws> IOException </throws> public virtual IDFExplanation IdfExplain(ICollection<Term> terms, Searcher searcher) { int max = searcher.MaxDoc; float idf2 = 0.0f; System.Text.StringBuilder exp = new System.Text.StringBuilder(); foreach (Term term in terms) { int df = searcher.DocFreq(term); idf2 += Idf(df, max); exp.Append(" "); exp.Append(term.Text); exp.Append("="); exp.Append(df); } float fIdf = idf2; return new AnonymousClassIDFExplanation3(fIdf, exp, this); } /// <summary>Computes a score factor based on a term's document frequency (the number /// of documents which contain the term). This value is multiplied by the /// <see cref="Tf(int)" /> factor for each term in the query and these products are /// then summed to form the initial score for a document. /// /// <p/>Terms that occur in fewer documents are better indicators of topic, so /// implementations of this method usually return larger values for rare terms, /// and smaller values for common terms. /// /// </summary> /// <param name="docFreq">the number of documents which contain the term /// </param> /// <param name="numDocs">the total number of documents in the collection /// </param> /// <returns> a score factor based on the term's document frequency /// </returns> public abstract float Idf(int docFreq, int numDocs); /// <summary>Computes a score factor based on the fraction of all query terms that a /// document contains. This value is multiplied into scores. /// /// <p/>The presence of a large portion of the query terms indicates a better /// match with the query, so implementations of this method usually return /// larger values when the ratio between these parameters is large and smaller /// values when the ratio between them is small. /// /// </summary> /// <param name="overlap">the number of query terms matched in the document /// </param> /// <param name="maxOverlap">the total number of terms in the query /// </param> /// <returns> a score factor based on term overlap with the query /// </returns> public abstract float Coord(int overlap, int maxOverlap); /// <summary> Calculate a scoring factor based on the data in the payload. Overriding implementations /// are responsible for interpreting what is in the payload. Lucene makes no assumptions about /// what is in the byte array. /// <p/> /// The default implementation returns 1. /// /// </summary> /// <param name="docId">The docId currently being scored. If this value is <see cref="NO_DOC_ID_PROVIDED" />, then it should be assumed that the PayloadQuery implementation does not provide document information /// </param> /// <param name="fieldName">The fieldName of the term this payload belongs to /// </param> /// <param name="start">The start position of the payload /// </param> /// <param name="end">The end position of the payload /// </param> /// <param name="payload">The payload byte array to be scored /// </param> /// <param name="offset">The offset into the payload array /// </param> /// <param name="length">The length in the array /// </param> /// <returns> An implementation dependent float to be used as a scoring factor /// /// </returns> public virtual float ScorePayload(int docId, System.String fieldName, int start, int end, byte[] payload, int offset, int length) { return 1; } static Similarity() { { for (int i = 0; i < 256; i++) NORM_TABLE[i] = SmallFloat.Byte315ToFloat((byte) i); } } } }