context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using UnityEngine; using UnityEngine.UI; namespace UnityEditor.UI { [CustomPropertyDrawer(typeof(FontData), true)] public class FontDataDrawer : PropertyDrawer { static private class Styles { public static GUIStyle alignmentButtonLeft = new GUIStyle(EditorStyles.miniButtonLeft); public static GUIStyle alignmentButtonMid = new GUIStyle(EditorStyles.miniButtonMid); public static GUIStyle alignmentButtonRight = new GUIStyle(EditorStyles.miniButtonRight); public static GUIContent m_EncodingContent; public static GUIContent m_LeftAlignText; public static GUIContent m_CenterAlignText; public static GUIContent m_RightAlignText; public static GUIContent m_TopAlignText; public static GUIContent m_MiddleAlignText; public static GUIContent m_BottomAlignText; public static GUIContent m_LeftAlignTextActive; public static GUIContent m_CenterAlignTextActive; public static GUIContent m_RightAlignTextActive; public static GUIContent m_TopAlignTextActive; public static GUIContent m_MiddleAlignTextActive; public static GUIContent m_BottomAlignTextActive; static Styles() { m_EncodingContent = new GUIContent("Rich Text", "Use emoticons and colors"); // Horizontal Aligment Icons m_LeftAlignText = EditorGUIUtility.IconContent(@"GUISystem/align_horizontally_left", "Left Align"); m_CenterAlignText = EditorGUIUtility.IconContent(@"GUISystem/align_horizontally_center", "Center Align"); m_RightAlignText = EditorGUIUtility.IconContent(@"GUISystem/align_horizontally_right", "Right Align"); m_LeftAlignTextActive = EditorGUIUtility.IconContent(@"GUISystem/align_horizontally_left_active", "Left Align"); m_CenterAlignTextActive = EditorGUIUtility.IconContent(@"GUISystem/align_horizontally_center_active", "Center Align"); m_RightAlignTextActive = EditorGUIUtility.IconContent(@"GUISystem/align_horizontally_right_active", "Right Align"); // Vertical Aligment Icons m_TopAlignText = EditorGUIUtility.IconContent(@"GUISystem/align_vertically_top", "Top Align"); m_MiddleAlignText = EditorGUIUtility.IconContent(@"GUISystem/align_vertically_center", "Middle Align"); m_BottomAlignText = EditorGUIUtility.IconContent(@"GUISystem/align_vertically_bottom", "Bottom Align"); m_TopAlignTextActive = EditorGUIUtility.IconContent(@"GUISystem/align_vertically_top_active", "Top Align"); m_MiddleAlignTextActive = EditorGUIUtility.IconContent(@"GUISystem/align_vertically_center_active", "Middle Align"); m_BottomAlignTextActive = EditorGUIUtility.IconContent(@"GUISystem/align_vertically_bottom_active", "Bottom Align"); FixAlignmentButtonStyles(alignmentButtonLeft, alignmentButtonMid, alignmentButtonRight); } static void FixAlignmentButtonStyles(params GUIStyle[] styles) { foreach (GUIStyle style in styles) { style.padding.left = 2; style.padding.right = 2; } } } private enum VerticalTextAligment { Top, Middle, Bottom } private enum HorizontalTextAligment { Left, Center, Right } private const int kAlignmentButtonWidth = 20; static int s_TextAlignmentHash = "DoTextAligmentControl".GetHashCode(); private SerializedProperty m_SupportEncoding; private SerializedProperty m_Font; private SerializedProperty m_FontSize; private SerializedProperty m_LineSpacing; private SerializedProperty m_FontStyle; private SerializedProperty m_ResizeTextForBestFit; private SerializedProperty m_ResizeTextMinSize; private SerializedProperty m_ResizeTextMaxSize; private SerializedProperty m_HorizontalOverflow; private SerializedProperty m_VerticalOverflow; private SerializedProperty m_Alignment; private float m_FontFieldfHeight = 0f; private float m_FontStyleHeight = 0f; private float m_FontSizeHeight = 0f; private float m_LineSpacingHeight = 0f; private float m_EncodingHeight = 0f; private float m_ResizeTextForBestFitHeight = 0f; private float m_ResizeTextMinSizeHeight = 0f; private float m_ResizeTextMaxSizeHeight = 0f; private float m_HorizontalOverflowHeight = 0f; private float m_VerticalOverflowHeight = 0f; protected void Init(SerializedProperty property) { m_SupportEncoding = property.FindPropertyRelative("m_RichText"); m_Font = property.FindPropertyRelative("m_Font"); m_FontSize = property.FindPropertyRelative("m_FontSize"); m_LineSpacing = property.FindPropertyRelative("m_LineSpacing"); m_FontStyle = property.FindPropertyRelative("m_FontStyle"); m_ResizeTextForBestFit = property.FindPropertyRelative("m_BestFit"); m_ResizeTextMinSize = property.FindPropertyRelative("m_MinSize"); m_ResizeTextMaxSize = property.FindPropertyRelative("m_MaxSize"); m_HorizontalOverflow = property.FindPropertyRelative("m_HorizontalOverflow"); m_VerticalOverflow = property.FindPropertyRelative("m_VerticalOverflow"); m_Alignment = property.FindPropertyRelative("m_Alignment"); } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { Init(property); m_FontFieldfHeight = EditorGUI.GetPropertyHeight(m_Font); m_FontStyleHeight = EditorGUI.GetPropertyHeight(m_FontStyle); m_FontSizeHeight = EditorGUI.GetPropertyHeight(m_FontSize); m_LineSpacingHeight = EditorGUI.GetPropertyHeight(m_LineSpacing); m_EncodingHeight = EditorGUI.GetPropertyHeight(m_SupportEncoding); m_ResizeTextForBestFitHeight = EditorGUI.GetPropertyHeight(m_ResizeTextForBestFit); m_ResizeTextMinSizeHeight = EditorGUI.GetPropertyHeight(m_ResizeTextMinSize); m_ResizeTextMaxSizeHeight = EditorGUI.GetPropertyHeight(m_ResizeTextMaxSize); m_HorizontalOverflowHeight = EditorGUI.GetPropertyHeight(m_HorizontalOverflow); m_VerticalOverflowHeight = EditorGUI.GetPropertyHeight(m_VerticalOverflow); var height = m_FontFieldfHeight + m_FontStyleHeight + m_FontSizeHeight + m_LineSpacingHeight + m_EncodingHeight + m_ResizeTextForBestFitHeight + m_HorizontalOverflowHeight + m_VerticalOverflowHeight + EditorGUIUtility.singleLineHeight * 3 + EditorGUIUtility.standardVerticalSpacing * 10; if (m_ResizeTextForBestFit.boolValue) { height += m_ResizeTextMinSizeHeight + m_ResizeTextMaxSizeHeight + EditorGUIUtility.standardVerticalSpacing * 2; } return height; } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { Init(property); Rect rect = position; rect.height = EditorGUIUtility.singleLineHeight; EditorGUI.LabelField(rect, "Character", EditorStyles.boldLabel); rect.y += rect.height + EditorGUIUtility.standardVerticalSpacing; ++EditorGUI.indentLevel; { Font font = m_Font.objectReferenceValue as Font; rect.height = m_FontFieldfHeight; EditorGUI.BeginChangeCheck(); EditorGUI.PropertyField(rect, m_Font); if (EditorGUI.EndChangeCheck()) { font = m_Font.objectReferenceValue as Font; if (font != null && !font.dynamic) m_FontSize.intValue = font.fontSize; } rect.y += rect.height + EditorGUIUtility.standardVerticalSpacing; rect.height = m_FontStyleHeight; EditorGUI.BeginDisabledGroup(!m_Font.hasMultipleDifferentValues && font != null && !font.dynamic); EditorGUI.PropertyField(rect, m_FontStyle); EditorGUI.EndDisabledGroup(); rect.y += rect.height + EditorGUIUtility.standardVerticalSpacing; rect.height = m_FontSizeHeight; EditorGUI.PropertyField(rect, m_FontSize); rect.y += rect.height + EditorGUIUtility.standardVerticalSpacing; rect.height = m_LineSpacingHeight; EditorGUI.PropertyField(rect, m_LineSpacing); rect.y += rect.height + EditorGUIUtility.standardVerticalSpacing; rect.height = m_EncodingHeight; EditorGUI.PropertyField(rect, m_SupportEncoding, Styles.m_EncodingContent); } --EditorGUI.indentLevel; rect.y += rect.height + EditorGUIUtility.standardVerticalSpacing; rect.height = EditorGUIUtility.singleLineHeight; EditorGUI.LabelField(rect, "Paragraph", EditorStyles.boldLabel); rect.y += rect.height + EditorGUIUtility.standardVerticalSpacing; ++EditorGUI.indentLevel; { rect.height = EditorGUIUtility.singleLineHeight; DoTextAligmentControl(rect, m_Alignment); rect.y += rect.height + EditorGUIUtility.standardVerticalSpacing; rect.height = m_HorizontalOverflowHeight; EditorGUI.PropertyField(rect, m_HorizontalOverflow); rect.y += rect.height + EditorGUIUtility.standardVerticalSpacing; rect.height = m_VerticalOverflowHeight; EditorGUI.PropertyField(rect, m_VerticalOverflow); rect.y += rect.height + EditorGUIUtility.standardVerticalSpacing; rect.height = m_ResizeTextMaxSizeHeight; EditorGUI.PropertyField(rect, m_ResizeTextForBestFit); if (m_ResizeTextForBestFit.boolValue) { EditorGUILayout.EndFadeGroup(); rect.y += rect.height + EditorGUIUtility.standardVerticalSpacing; rect.height = m_ResizeTextMinSizeHeight; EditorGUI.PropertyField(rect, m_ResizeTextMinSize); rect.y += rect.height + EditorGUIUtility.standardVerticalSpacing; rect.height = m_ResizeTextMaxSizeHeight; EditorGUI.PropertyField(rect, m_ResizeTextMaxSize); } } --EditorGUI.indentLevel; } private void DoTextAligmentControl(Rect position, SerializedProperty alignment) { GUIContent alingmentContent = new GUIContent("Alignment"); int id = EditorGUIUtility.GetControlID(s_TextAlignmentHash, EditorGUIUtility.native, position); EditorGUIUtility.SetIconSize(new Vector2(15, 15)); EditorGUI.BeginProperty(position, alingmentContent, alignment); { Rect controlArea = EditorGUI.PrefixLabel(position, id, alingmentContent); float width = kAlignmentButtonWidth * 3; float spacing = Mathf.Clamp(controlArea.width - width * 2, 2, 10); Rect horizontalAligment = new Rect(controlArea.x, controlArea.y, width, controlArea.height); Rect verticalAligment = new Rect(horizontalAligment.xMax + spacing, controlArea.y, width, controlArea.height); DoHorizontalAligmentControl(horizontalAligment, alignment); DoVerticalAligmentControl(verticalAligment, alignment); } EditorGUI.EndProperty(); EditorGUIUtility.SetIconSize(Vector2.zero); } private static void DoHorizontalAligmentControl(Rect position, SerializedProperty alignment) { TextAnchor ta = (TextAnchor)alignment.intValue; HorizontalTextAligment horizontalAlignment = GetHorizontalAlgiment(ta); bool leftAlign = (horizontalAlignment == HorizontalTextAligment.Left); bool centerAlign = (horizontalAlignment == HorizontalTextAligment.Center); bool rightAlign = (horizontalAlignment == HorizontalTextAligment.Right); if (alignment.hasMultipleDifferentValues) { foreach (var obj in alignment.serializedObject.targetObjects) { Text text = obj as Text; horizontalAlignment = GetHorizontalAlgiment(text.alignment); leftAlign = leftAlign || (horizontalAlignment == HorizontalTextAligment.Left); centerAlign = centerAlign || (horizontalAlignment == HorizontalTextAligment.Center); rightAlign = rightAlign || (horizontalAlignment == HorizontalTextAligment.Right); } } position.width = kAlignmentButtonWidth; EditorGUI.BeginChangeCheck(); EditorToggle(position, leftAlign, leftAlign ? Styles.m_LeftAlignTextActive : Styles.m_LeftAlignText, Styles.alignmentButtonLeft); if (EditorGUI.EndChangeCheck()) { SetHorizontalAlignment(alignment, HorizontalTextAligment.Left); } position.x += position.width; EditorGUI.BeginChangeCheck(); EditorToggle(position, centerAlign, centerAlign ? Styles.m_CenterAlignTextActive : Styles.m_CenterAlignText, Styles.alignmentButtonMid); if (EditorGUI.EndChangeCheck()) { SetHorizontalAlignment(alignment, HorizontalTextAligment.Center); } position.x += position.width; EditorGUI.BeginChangeCheck(); EditorToggle(position, rightAlign, rightAlign ? Styles.m_RightAlignTextActive : Styles.m_RightAlignText, Styles.alignmentButtonRight); if (EditorGUI.EndChangeCheck()) { SetHorizontalAlignment(alignment, HorizontalTextAligment.Right); } } private static void DoVerticalAligmentControl(Rect position, SerializedProperty alignment) { TextAnchor ta = (TextAnchor)alignment.intValue; VerticalTextAligment verticalTextAligment = GetVerticalAlgiment(ta); bool topAlign = (verticalTextAligment == VerticalTextAligment.Top); bool middleAlign = (verticalTextAligment == VerticalTextAligment.Middle); bool bottomAlign = (verticalTextAligment == VerticalTextAligment.Bottom); if (alignment.hasMultipleDifferentValues) { foreach (var obj in alignment.serializedObject.targetObjects) { Text text = obj as Text; TextAnchor textAlignment = text.alignment; verticalTextAligment = GetVerticalAlgiment(textAlignment); topAlign = topAlign || (verticalTextAligment == VerticalTextAligment.Top); middleAlign = middleAlign || (verticalTextAligment == VerticalTextAligment.Middle); bottomAlign = bottomAlign || (verticalTextAligment == VerticalTextAligment.Bottom); } } position.width = kAlignmentButtonWidth; // position.x += position.width; EditorGUI.BeginChangeCheck(); EditorToggle(position, topAlign, topAlign ? Styles.m_TopAlignTextActive : Styles.m_TopAlignText, Styles.alignmentButtonLeft); if (EditorGUI.EndChangeCheck()) { SetVerticalAlignment(alignment, VerticalTextAligment.Top); } position.x += position.width; EditorGUI.BeginChangeCheck(); EditorToggle(position, middleAlign, middleAlign ? Styles.m_MiddleAlignTextActive : Styles.m_MiddleAlignText, Styles.alignmentButtonMid); if (EditorGUI.EndChangeCheck()) { SetVerticalAlignment(alignment, VerticalTextAligment.Middle); } position.x += position.width; EditorGUI.BeginChangeCheck(); EditorToggle(position, bottomAlign, bottomAlign ? Styles.m_BottomAlignTextActive : Styles.m_BottomAlignText, Styles.alignmentButtonRight); if (EditorGUI.EndChangeCheck()) { SetVerticalAlignment(alignment, VerticalTextAligment.Bottom); } } private static bool EditorToggle(Rect position, bool value, GUIContent content, GUIStyle style) { int hashCode = "AlignToggle".GetHashCode(); int id = EditorGUIUtility.GetControlID(hashCode, EditorGUIUtility.native, position); Event evt = Event.current; // Toggle selected toggle on space or return key if (EditorGUIUtility.keyboardControl == id && evt.type == EventType.KeyDown && (evt.keyCode == KeyCode.Space || evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter)) { value = !value; evt.Use(); GUI.changed = true; } if (evt.type == EventType.KeyDown && Event.current.button == 0 && position.Contains(Event.current.mousePosition)) { GUIUtility.keyboardControl = id; EditorGUIUtility.editingTextField = false; HandleUtility.Repaint(); } bool returnValue = GUI.Toggle(position, id, value, content, style); return returnValue; } private static HorizontalTextAligment GetHorizontalAlgiment(TextAnchor ta) { switch (ta) { case TextAnchor.MiddleCenter: case TextAnchor.UpperCenter: case TextAnchor.LowerCenter: return HorizontalTextAligment.Center; case TextAnchor.UpperRight: case TextAnchor.MiddleRight: case TextAnchor.LowerRight: return HorizontalTextAligment.Right; case TextAnchor.UpperLeft: case TextAnchor.MiddleLeft: case TextAnchor.LowerLeft: return HorizontalTextAligment.Left; } return HorizontalTextAligment.Left; } private static VerticalTextAligment GetVerticalAlgiment(TextAnchor ta) { switch (ta) { case TextAnchor.UpperLeft: case TextAnchor.UpperCenter: case TextAnchor.UpperRight: return VerticalTextAligment.Top; case TextAnchor.MiddleLeft: case TextAnchor.MiddleCenter: case TextAnchor.MiddleRight: return VerticalTextAligment.Middle; case TextAnchor.LowerLeft: case TextAnchor.LowerCenter: case TextAnchor.LowerRight: return VerticalTextAligment.Bottom; } return VerticalTextAligment.Top; } // We can't go through serialzied properties here since we're showing two controls for a single SerializzedProperty. private static void SetHorizontalAlignment(SerializedProperty alignment, HorizontalTextAligment horizontalAlignment) { foreach (var obj in alignment.serializedObject.targetObjects) { Text text = obj as Text; VerticalTextAligment currentVerticalAligment = GetVerticalAlgiment(text.alignment); Undo.RecordObject(text, "Horizontal Alignment"); text.alignment = GetAnchor(currentVerticalAligment, horizontalAlignment); EditorUtility.SetDirty(obj); } } private static void SetVerticalAlignment(SerializedProperty alignment, VerticalTextAligment verticalAlignment) { foreach (var obj in alignment.serializedObject.targetObjects) { Text text = obj as Text; HorizontalTextAligment currentHorizontalAligment = GetHorizontalAlgiment(text.alignment); Undo.RecordObject(text, "Vertical Alignment"); text.alignment = GetAnchor(verticalAlignment, currentHorizontalAligment); EditorUtility.SetDirty(obj); } } private static TextAnchor GetAnchor(VerticalTextAligment verticalTextAligment, HorizontalTextAligment horizontalTextAligment) { TextAnchor ac = TextAnchor.UpperLeft; switch (horizontalTextAligment) { case HorizontalTextAligment.Left: switch (verticalTextAligment) { case VerticalTextAligment.Bottom: ac = TextAnchor.LowerLeft; break; case VerticalTextAligment.Middle: ac = TextAnchor.MiddleLeft; break; default: ac = TextAnchor.UpperLeft; break; } break; case HorizontalTextAligment.Center: switch (verticalTextAligment) { case VerticalTextAligment.Bottom: ac = TextAnchor.LowerCenter; break; case VerticalTextAligment.Middle: ac = TextAnchor.MiddleCenter; break; default: ac = TextAnchor.UpperCenter; break; } break; default: switch (verticalTextAligment) { case VerticalTextAligment.Bottom: ac = TextAnchor.LowerRight; break; case VerticalTextAligment.Middle: ac = TextAnchor.MiddleRight; break; default: ac = TextAnchor.UpperRight; break; } break; } return ac; } } }
// 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 class represents the Default COM+ binder. // // namespace System { using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Diagnostics; using System.Diagnostics.Contracts; using CultureInfo = System.Globalization.CultureInfo; //Marked serializable even though it has no state. [Serializable] internal class DefaultBinder : Binder { // This method is passed a set of methods and must choose the best // fit. The methods all have the same number of arguments and the object // array args. On exit, this method will choice the best fit method // and coerce the args to match that method. By match, we mean all primitive // arguments are exact matchs and all object arguments are exact or subclasses // of the target. If the target OR is an interface, the object must implement // that interface. There are a couple of exceptions // thrown when a method cannot be returned. If no method matchs the args and // ArgumentException is thrown. If multiple methods match the args then // an AmbiguousMatchException is thrown. // // The most specific match will be selected. // public override MethodBase BindToMethod( BindingFlags bindingAttr, MethodBase[] match, ref Object[] args, ParameterModifier[] modifiers, CultureInfo cultureInfo, String[] names, out Object state) { if (match == null || match.Length == 0) throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), nameof(match)); Contract.EndContractBlock(); MethodBase[] candidates = (MethodBase[])match.Clone(); int i; int j; state = null; #region Map named parameters to candidate parameter postions // We are creating an paramOrder array to act as a mapping // between the order of the args and the actual order of the // parameters in the method. This order may differ because // named parameters (names) may change the order. If names // is not provided, then we assume the default mapping (0,1,...) int[][] paramOrder = new int[candidates.Length][]; for (i = 0; i < candidates.Length; i++) { ParameterInfo[] par = candidates[i].GetParametersNoCopy(); // args.Length + 1 takes into account the possibility of a last paramArray that can be omitted paramOrder[i] = new int[(par.Length > args.Length) ? par.Length : args.Length]; if (names == null) { // Default mapping for (j = 0; j < args.Length; j++) paramOrder[i][j] = j; } else { // Named parameters, reorder the mapping. If CreateParamOrder fails, it means that the method // doesn't have a name that matchs one of the named parameters so we don't consider it any further. if (!CreateParamOrder(paramOrder[i], par, names)) candidates[i] = null; } } #endregion Type[] paramArrayTypes = new Type[candidates.Length]; Type[] argTypes = new Type[args.Length]; #region Cache the type of the provided arguments // object that contain a null are treated as if they were typeless (but match either object // references or value classes). We mark this condition by placing a null in the argTypes array. for (i = 0; i < args.Length; i++) { if (args[i] != null) { argTypes[i] = args[i].GetType(); } } #endregion // Find the method that matches... int CurIdx = 0; bool defaultValueBinding = ((bindingAttr & BindingFlags.OptionalParamBinding) != 0); Type paramArrayType = null; #region Filter methods by parameter count and type for (i = 0; i < candidates.Length; i++) { paramArrayType = null; // If we have named parameters then we may have a hole in the candidates array. if (candidates[i] == null) continue; // Validate the parameters. ParameterInfo[] par = candidates[i].GetParametersNoCopy(); #region Match method by parameter count if (par.Length == 0) { #region No formal parameters if (args.Length != 0) { if ((candidates[i].CallingConvention & CallingConventions.VarArgs) == 0) continue; } // This is a valid routine so we move it up the candidates list. paramOrder[CurIdx] = paramOrder[i]; candidates[CurIdx++] = candidates[i]; continue; #endregion } else if (par.Length > args.Length) { #region Shortage of provided parameters // If the number of parameters is greater than the number of args then // we are in the situation were we may be using default values. for (j = args.Length; j < par.Length - 1; j++) { if (par[j].DefaultValue == System.DBNull.Value) break; } if (j != par.Length - 1) continue; if (par[j].DefaultValue == System.DBNull.Value) { if (!par[j].ParameterType.IsArray) continue; if (!par[j].IsDefined(typeof(ParamArrayAttribute), true)) continue; paramArrayType = par[j].ParameterType.GetElementType(); } #endregion } else if (par.Length < args.Length) { #region Excess provided parameters // test for the ParamArray case int lastArgPos = par.Length - 1; if (!par[lastArgPos].ParameterType.IsArray) continue; if (!par[lastArgPos].IsDefined(typeof(ParamArrayAttribute), true)) continue; if (paramOrder[i][lastArgPos] != lastArgPos) continue; paramArrayType = par[lastArgPos].ParameterType.GetElementType(); #endregion } else { #region Test for paramArray, save paramArray type int lastArgPos = par.Length - 1; if (par[lastArgPos].ParameterType.IsArray && par[lastArgPos].IsDefined(typeof(ParamArrayAttribute), true) && paramOrder[i][lastArgPos] == lastArgPos) { if (!par[lastArgPos].ParameterType.IsAssignableFrom(argTypes[lastArgPos])) paramArrayType = par[lastArgPos].ParameterType.GetElementType(); } #endregion } #endregion Type pCls = null; int argsToCheck = (paramArrayType != null) ? par.Length - 1 : args.Length; #region Match method by parameter type for (j = 0; j < argsToCheck; j++) { #region Classic argument coersion checks // get the formal type pCls = par[j].ParameterType; if (pCls.IsByRef) pCls = pCls.GetElementType(); // the type is the same if (pCls == argTypes[paramOrder[i][j]]) continue; // a default value is available if (defaultValueBinding && args[paramOrder[i][j]] == Type.Missing) continue; // the argument was null, so it matches with everything if (args[paramOrder[i][j]] == null) continue; // the type is Object, so it will match everything if (pCls == typeof(Object)) continue; // now do a "classic" type check if (pCls.IsPrimitive) { if (argTypes[paramOrder[i][j]] == null || !CanConvertPrimitiveObjectToType(args[paramOrder[i][j]], (RuntimeType)pCls)) { break; } } else { if (argTypes[paramOrder[i][j]] == null) continue; if (!pCls.IsAssignableFrom(argTypes[paramOrder[i][j]])) { if (argTypes[paramOrder[i][j]].IsCOMObject) { if (pCls.IsInstanceOfType(args[paramOrder[i][j]])) continue; } break; } } #endregion } if (paramArrayType != null && j == par.Length - 1) { #region Check that excess arguments can be placed in the param array for (; j < args.Length; j++) { if (paramArrayType.IsPrimitive) { if (argTypes[j] == null || !CanConvertPrimitiveObjectToType(args[j], (RuntimeType)paramArrayType)) break; } else { if (argTypes[j] == null) continue; if (!paramArrayType.IsAssignableFrom(argTypes[j])) { if (argTypes[j].IsCOMObject) { if (paramArrayType.IsInstanceOfType(args[j])) continue; } break; } } } #endregion } #endregion if (j == args.Length) { #region This is a valid routine so we move it up the candidates list paramOrder[CurIdx] = paramOrder[i]; paramArrayTypes[CurIdx] = paramArrayType; candidates[CurIdx++] = candidates[i]; #endregion } } #endregion // If we didn't find a method if (CurIdx == 0) throw new MissingMethodException(Environment.GetResourceString("MissingMember")); if (CurIdx == 1) { #region Found only one method if (names != null) { state = new BinderState((int[])paramOrder[0].Clone(), args.Length, paramArrayTypes[0] != null); ReorderParams(paramOrder[0], args); } // If the parameters and the args are not the same length or there is a paramArray // then we need to create a argument array. ParameterInfo[] parms = candidates[0].GetParametersNoCopy(); if (parms.Length == args.Length) { if (paramArrayTypes[0] != null) { Object[] objs = new Object[parms.Length]; int lastPos = parms.Length - 1; Array.Copy(args, 0, objs, 0, lastPos); objs[lastPos] = Array.UnsafeCreateInstance(paramArrayTypes[0], 1); ((Array)objs[lastPos]).SetValue(args[lastPos], 0); args = objs; } } else if (parms.Length > args.Length) { Object[] objs = new Object[parms.Length]; for (i = 0; i < args.Length; i++) objs[i] = args[i]; for (; i < parms.Length - 1; i++) objs[i] = parms[i].DefaultValue; if (paramArrayTypes[0] != null) objs[i] = Array.UnsafeCreateInstance(paramArrayTypes[0], 0); // create an empty array for the else objs[i] = parms[i].DefaultValue; args = objs; } else { if ((candidates[0].CallingConvention & CallingConventions.VarArgs) == 0) { Object[] objs = new Object[parms.Length]; int paramArrayPos = parms.Length - 1; Array.Copy(args, 0, objs, 0, paramArrayPos); objs[paramArrayPos] = Array.UnsafeCreateInstance(paramArrayTypes[0], args.Length - paramArrayPos); Array.Copy(args, paramArrayPos, (System.Array)objs[paramArrayPos], 0, args.Length - paramArrayPos); args = objs; } } #endregion return candidates[0]; } int currentMin = 0; bool ambig = false; for (i = 1; i < CurIdx; i++) { #region Walk all of the methods looking the most specific method to invoke int newMin = FindMostSpecificMethod(candidates[currentMin], paramOrder[currentMin], paramArrayTypes[currentMin], candidates[i], paramOrder[i], paramArrayTypes[i], argTypes, args); if (newMin == 0) { ambig = true; } else if (newMin == 2) { currentMin = i; ambig = false; } #endregion } if (ambig) throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); // Reorder (if needed) if (names != null) { state = new BinderState((int[])paramOrder[currentMin].Clone(), args.Length, paramArrayTypes[currentMin] != null); ReorderParams(paramOrder[currentMin], args); } // If the parameters and the args are not the same length or there is a paramArray // then we need to create a argument array. ParameterInfo[] parameters = candidates[currentMin].GetParametersNoCopy(); if (parameters.Length == args.Length) { if (paramArrayTypes[currentMin] != null) { Object[] objs = new Object[parameters.Length]; int lastPos = parameters.Length - 1; Array.Copy(args, 0, objs, 0, lastPos); objs[lastPos] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], 1); ((Array)objs[lastPos]).SetValue(args[lastPos], 0); args = objs; } } else if (parameters.Length > args.Length) { Object[] objs = new Object[parameters.Length]; for (i = 0; i < args.Length; i++) objs[i] = args[i]; for (; i < parameters.Length - 1; i++) objs[i] = parameters[i].DefaultValue; if (paramArrayTypes[currentMin] != null) { objs[i] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], 0); } else { objs[i] = parameters[i].DefaultValue; } args = objs; } else { if ((candidates[currentMin].CallingConvention & CallingConventions.VarArgs) == 0) { Object[] objs = new Object[parameters.Length]; int paramArrayPos = parameters.Length - 1; Array.Copy(args, 0, objs, 0, paramArrayPos); objs[paramArrayPos] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], args.Length - paramArrayPos); Array.Copy(args, paramArrayPos, (System.Array)objs[paramArrayPos], 0, args.Length - paramArrayPos); args = objs; } } return candidates[currentMin]; } // Given a set of fields that match the base criteria, select a field. // if value is null then we have no way to select a field public override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, Object value, CultureInfo cultureInfo) { if (match == null) { throw new ArgumentNullException(nameof(match)); } int i; // Find the method that match... int CurIdx = 0; Type valueType = null; FieldInfo[] candidates = (FieldInfo[])match.Clone(); // If we are a FieldSet, then use the value's type to disambiguate if ((bindingAttr & BindingFlags.SetField) != 0) { valueType = value.GetType(); for (i = 0; i < candidates.Length; i++) { Type pCls = candidates[i].FieldType; if (pCls == valueType) { candidates[CurIdx++] = candidates[i]; continue; } if (value == Empty.Value) { // the object passed in was null which would match any non primitive non value type if (pCls.IsClass) { candidates[CurIdx++] = candidates[i]; continue; } } if (pCls == typeof(Object)) { candidates[CurIdx++] = candidates[i]; continue; } if (pCls.IsPrimitive) { if (CanConvertPrimitiveObjectToType(value, (RuntimeType)pCls)) { candidates[CurIdx++] = candidates[i]; continue; } } else { if (pCls.IsAssignableFrom(valueType)) { candidates[CurIdx++] = candidates[i]; continue; } } } if (CurIdx == 0) throw new MissingFieldException(Environment.GetResourceString("MissingField")); if (CurIdx == 1) return candidates[0]; } // Walk all of the methods looking the most specific method to invoke int currentMin = 0; bool ambig = false; for (i = 1; i < CurIdx; i++) { int newMin = FindMostSpecificField(candidates[currentMin], candidates[i]); if (newMin == 0) ambig = true; else { if (newMin == 2) { currentMin = i; ambig = false; } } } if (ambig) throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); return candidates[currentMin]; } // Given a set of methods that match the base criteria, select a method based // upon an array of types. This method should return null if no method matchs // the criteria. public override MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers) { int i; int j; Type[] realTypes = new Type[types.Length]; for (i = 0; i < types.Length; i++) { realTypes[i] = types[i].UnderlyingSystemType; if (!(realTypes[i] is RuntimeType)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(types)); } types = realTypes; // We don't automatically jump out on exact match. if (match == null || match.Length == 0) throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), nameof(match)); MethodBase[] candidates = (MethodBase[])match.Clone(); // Find all the methods that can be described by the types parameter. // Remove all of them that cannot. int CurIdx = 0; for (i = 0; i < candidates.Length; i++) { ParameterInfo[] par = candidates[i].GetParametersNoCopy(); if (par.Length != types.Length) continue; for (j = 0; j < types.Length; j++) { Type pCls = par[j].ParameterType; if (pCls == types[j]) continue; if (pCls == typeof(Object)) continue; if (pCls.IsPrimitive) { if (!(types[j].UnderlyingSystemType is RuntimeType) || !CanConvertPrimitive((RuntimeType)types[j].UnderlyingSystemType, (RuntimeType)pCls.UnderlyingSystemType)) break; } else { if (!pCls.IsAssignableFrom(types[j])) break; } } if (j == types.Length) candidates[CurIdx++] = candidates[i]; } if (CurIdx == 0) return null; if (CurIdx == 1) return candidates[0]; // Walk all of the methods looking the most specific method to invoke int currentMin = 0; bool ambig = false; int[] paramOrder = new int[types.Length]; for (i = 0; i < types.Length; i++) paramOrder[i] = i; for (i = 1; i < CurIdx; i++) { int newMin = FindMostSpecificMethod(candidates[currentMin], paramOrder, null, candidates[i], paramOrder, null, types, null); if (newMin == 0) ambig = true; else { if (newMin == 2) { currentMin = i; ambig = false; currentMin = i; } } } if (ambig) throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); return candidates[currentMin]; } // Given a set of properties that match the base criteria, select one. public override PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers) { // Allow a null indexes array. But if it is not null, every element must be non-null as well. if (indexes != null && !Contract.ForAll(indexes, delegate (Type t) { return t != null; })) { throw new ArgumentNullException(nameof(indexes)); } if (match == null || match.Length == 0) throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), nameof(match)); Contract.EndContractBlock(); PropertyInfo[] candidates = (PropertyInfo[])match.Clone(); int i, j = 0; // Find all the properties that can be described by type indexes parameter int CurIdx = 0; int indexesLength = (indexes != null) ? indexes.Length : 0; for (i = 0; i < candidates.Length; i++) { if (indexes != null) { ParameterInfo[] par = candidates[i].GetIndexParameters(); if (par.Length != indexesLength) continue; for (j = 0; j < indexesLength; j++) { Type pCls = par[j].ParameterType; // If the classes exactly match continue if (pCls == indexes[j]) continue; if (pCls == typeof(Object)) continue; if (pCls.IsPrimitive) { if (!(indexes[j].UnderlyingSystemType is RuntimeType) || !CanConvertPrimitive((RuntimeType)indexes[j].UnderlyingSystemType, (RuntimeType)pCls.UnderlyingSystemType)) break; } else { if (!pCls.IsAssignableFrom(indexes[j])) break; } } } if (j == indexesLength) { if (returnType != null) { if (candidates[i].PropertyType.IsPrimitive) { if (!(returnType.UnderlyingSystemType is RuntimeType) || !CanConvertPrimitive((RuntimeType)returnType.UnderlyingSystemType, (RuntimeType)candidates[i].PropertyType.UnderlyingSystemType)) continue; } else { if (!candidates[i].PropertyType.IsAssignableFrom(returnType)) continue; } } candidates[CurIdx++] = candidates[i]; } } if (CurIdx == 0) return null; if (CurIdx == 1) return candidates[0]; // Walk all of the properties looking the most specific method to invoke int currentMin = 0; bool ambig = false; int[] paramOrder = new int[indexesLength]; for (i = 0; i < indexesLength; i++) paramOrder[i] = i; for (i = 1; i < CurIdx; i++) { int newMin = FindMostSpecificType(candidates[currentMin].PropertyType, candidates[i].PropertyType, returnType); if (newMin == 0 && indexes != null) newMin = FindMostSpecific(candidates[currentMin].GetIndexParameters(), paramOrder, null, candidates[i].GetIndexParameters(), paramOrder, null, indexes, null); if (newMin == 0) { newMin = FindMostSpecificProperty(candidates[currentMin], candidates[i]); if (newMin == 0) ambig = true; } if (newMin == 2) { ambig = false; currentMin = i; } } if (ambig) throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); return candidates[currentMin]; } // ChangeType // The default binder doesn't support any change type functionality. // This is because the default is built into the low level invoke code. public override Object ChangeType(Object value, Type type, CultureInfo cultureInfo) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_ChangeType")); } public override void ReorderArgumentArray(ref Object[] args, Object state) { BinderState binderState = (BinderState)state; ReorderParams(binderState.m_argsMap, args); if (binderState.m_isParamArray) { int paramArrayPos = args.Length - 1; if (args.Length == binderState.m_originalSize) args[paramArrayPos] = ((Object[])args[paramArrayPos])[0]; else { // must be args.Length < state.originalSize Object[] newArgs = new Object[args.Length]; Array.Copy(args, 0, newArgs, 0, paramArrayPos); for (int i = paramArrayPos, j = 0; i < newArgs.Length; i++, j++) { newArgs[i] = ((Object[])args[paramArrayPos])[j]; } args = newArgs; } } else { if (args.Length > binderState.m_originalSize) { Object[] newArgs = new Object[binderState.m_originalSize]; Array.Copy(args, 0, newArgs, 0, binderState.m_originalSize); args = newArgs; } } } // Return any exact bindings that may exist. (This method is not defined on the // Binder and is used by RuntimeType.) public static MethodBase ExactBinding(MethodBase[] match, Type[] types, ParameterModifier[] modifiers) { if (match == null) throw new ArgumentNullException(nameof(match)); Contract.EndContractBlock(); MethodBase[] aExactMatches = new MethodBase[match.Length]; int cExactMatches = 0; for (int i = 0; i < match.Length; i++) { ParameterInfo[] par = match[i].GetParametersNoCopy(); if (par.Length == 0) { continue; } int j; for (j = 0; j < types.Length; j++) { Type pCls = par[j].ParameterType; // If the classes exactly match continue if (!pCls.Equals(types[j])) break; } if (j < types.Length) continue; // Add the exact match to the array of exact matches. aExactMatches[cExactMatches] = match[i]; cExactMatches++; } if (cExactMatches == 0) return null; if (cExactMatches == 1) return aExactMatches[0]; return FindMostDerivedNewSlotMeth(aExactMatches, cExactMatches); } // Return any exact bindings that may exist. (This method is not defined on the // Binder and is used by RuntimeType.) public static PropertyInfo ExactPropertyBinding(PropertyInfo[] match, Type returnType, Type[] types, ParameterModifier[] modifiers) { if (match == null) throw new ArgumentNullException(nameof(match)); Contract.EndContractBlock(); PropertyInfo bestMatch = null; int typesLength = (types != null) ? types.Length : 0; for (int i = 0; i < match.Length; i++) { ParameterInfo[] par = match[i].GetIndexParameters(); int j; for (j = 0; j < typesLength; j++) { Type pCls = par[j].ParameterType; // If the classes exactly match continue if (pCls != types[j]) break; } if (j < typesLength) continue; if (returnType != null && returnType != match[i].PropertyType) continue; if (bestMatch != null) throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); bestMatch = match[i]; } return bestMatch; } private static int FindMostSpecific(ParameterInfo[] p1, int[] paramOrder1, Type paramArrayType1, ParameterInfo[] p2, int[] paramOrder2, Type paramArrayType2, Type[] types, Object[] args) { // A method using params is always less specific than one not using params if (paramArrayType1 != null && paramArrayType2 == null) return 2; if (paramArrayType2 != null && paramArrayType1 == null) return 1; // now either p1 and p2 both use params or neither does. bool p1Less = false; bool p2Less = false; for (int i = 0; i < types.Length; i++) { if (args != null && args[i] == Type.Missing) continue; Type c1, c2; // If a param array is present, then either // the user re-ordered the parameters in which case // the argument to the param array is either an array // in which case the params is conceptually ignored and so paramArrayType1 == null // or the argument to the param array is a single element // in which case paramOrder[i] == p1.Length - 1 for that element // or the user did not re-order the parameters in which case // the paramOrder array could contain indexes larger than p.Length - 1 (see VSW 577286) // so any index >= p.Length - 1 is being put in the param array if (paramArrayType1 != null && paramOrder1[i] >= p1.Length - 1) c1 = paramArrayType1; else c1 = p1[paramOrder1[i]].ParameterType; if (paramArrayType2 != null && paramOrder2[i] >= p2.Length - 1) c2 = paramArrayType2; else c2 = p2[paramOrder2[i]].ParameterType; if (c1 == c2) continue; switch (FindMostSpecificType(c1, c2, types[i])) { case 0: return 0; case 1: p1Less = true; break; case 2: p2Less = true; break; } } // Two way p1Less and p2Less can be equal. All the arguments are the // same they both equal false, otherwise there were things that both // were the most specific type on.... if (p1Less == p2Less) { // if we cannot tell which is a better match based on parameter types (p1Less == p2Less), // let's see which one has the most matches without using the params array (the longer one wins). if (!p1Less && args != null) { if (p1.Length > p2.Length) { return 1; } else if (p2.Length > p1.Length) { return 2; } } return 0; } else { return (p1Less == true) ? 1 : 2; } } private static int FindMostSpecificType(Type c1, Type c2, Type t) { // If the two types are exact move on... if (c1 == c2) return 0; if (c1 == t) return 1; if (c2 == t) return 2; bool c1FromC2; bool c2FromC1; if (c1.IsByRef || c2.IsByRef) { if (c1.IsByRef && c2.IsByRef) { c1 = c1.GetElementType(); c2 = c2.GetElementType(); } else if (c1.IsByRef) { if (c1.GetElementType() == c2) return 2; c1 = c1.GetElementType(); } else { if (c2.GetElementType() == c1) return 1; c2 = c2.GetElementType(); } } if (c1.IsPrimitive && c2.IsPrimitive) { c1FromC2 = CanConvertPrimitive((RuntimeType)c2, (RuntimeType)c1); c2FromC1 = CanConvertPrimitive((RuntimeType)c1, (RuntimeType)c2); } else { c1FromC2 = c1.IsAssignableFrom(c2); c2FromC1 = c2.IsAssignableFrom(c1); } if (c1FromC2 == c2FromC1) return 0; if (c1FromC2) { return 2; } else { return 1; } } private static int FindMostSpecificMethod(MethodBase m1, int[] paramOrder1, Type paramArrayType1, MethodBase m2, int[] paramOrder2, Type paramArrayType2, Type[] types, Object[] args) { // Find the most specific method based on the parameters. int res = FindMostSpecific(m1.GetParametersNoCopy(), paramOrder1, paramArrayType1, m2.GetParametersNoCopy(), paramOrder2, paramArrayType2, types, args); // If the match was not ambigous then return the result. if (res != 0) return res; // Check to see if the methods have the exact same name and signature. if (CompareMethodSigAndName(m1, m2)) { // Determine the depth of the declaring types for both methods. int hierarchyDepth1 = GetHierarchyDepth(m1.DeclaringType); int hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType); // The most derived method is the most specific one. if (hierarchyDepth1 == hierarchyDepth2) { return 0; } else if (hierarchyDepth1 < hierarchyDepth2) { return 2; } else { return 1; } } // The match is ambigous. return 0; } private static int FindMostSpecificField(FieldInfo cur1, FieldInfo cur2) { // Check to see if the fields have the same name. if (cur1.Name == cur2.Name) { int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType); int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType); if (hierarchyDepth1 == hierarchyDepth2) { Debug.Assert(cur1.IsStatic != cur2.IsStatic, "hierarchyDepth1 == hierarchyDepth2"); return 0; } else if (hierarchyDepth1 < hierarchyDepth2) return 2; else return 1; } // The match is ambigous. return 0; } private static int FindMostSpecificProperty(PropertyInfo cur1, PropertyInfo cur2) { // Check to see if the fields have the same name. if (cur1.Name == cur2.Name) { int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType); int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType); if (hierarchyDepth1 == hierarchyDepth2) { return 0; } else if (hierarchyDepth1 < hierarchyDepth2) return 2; else return 1; } // The match is ambigous. return 0; } internal static bool CompareMethodSigAndName(MethodBase m1, MethodBase m2) { ParameterInfo[] params1 = m1.GetParametersNoCopy(); ParameterInfo[] params2 = m2.GetParametersNoCopy(); if (params1.Length != params2.Length) return false; int numParams = params1.Length; for (int i = 0; i < numParams; i++) { if (params1[i].ParameterType != params2[i].ParameterType) return false; } return true; } internal static int GetHierarchyDepth(Type t) { int depth = 0; Type currentType = t; do { depth++; currentType = currentType.BaseType; } while (currentType != null); return depth; } internal static MethodBase FindMostDerivedNewSlotMeth(MethodBase[] match, int cMatches) { int deepestHierarchy = 0; MethodBase methWithDeepestHierarchy = null; for (int i = 0; i < cMatches; i++) { // Calculate the depth of the hierarchy of the declaring type of the // current method. int currentHierarchyDepth = GetHierarchyDepth(match[i].DeclaringType); // The two methods have the same name, signature, and hierarchy depth. // This can only happen if at least one is vararg or generic. if (currentHierarchyDepth == deepestHierarchy) { throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); } // Check to see if this method is on the most derived class. if (currentHierarchyDepth > deepestHierarchy) { deepestHierarchy = currentHierarchyDepth; methWithDeepestHierarchy = match[i]; } } return methWithDeepestHierarchy; } // CanConvertPrimitive // This will determine if the source can be converted to the target type [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool CanConvertPrimitive(RuntimeType source, RuntimeType target); // CanConvertPrimitiveObjectToType // This method will determine if the primitive object can be converted // to a type. [MethodImplAttribute(MethodImplOptions.InternalCall)] static internal extern bool CanConvertPrimitiveObjectToType(Object source, RuntimeType type); // This method will sort the vars array into the mapping order stored // in the paramOrder array. private static void ReorderParams(int[] paramOrder, Object[] vars) { object[] varsCopy = new object[vars.Length]; for (int i = 0; i < vars.Length; i++) varsCopy[i] = vars[i]; for (int i = 0; i < vars.Length; i++) vars[i] = varsCopy[paramOrder[i]]; } // This method will create the mapping between the Parameters and the underlying // data based upon the names array. The names array is stored in the same order // as the values and maps to the parameters of the method. We store the mapping // from the parameters to the names in the paramOrder array. All parameters that // don't have matching names are then stored in the array in order. private static bool CreateParamOrder(int[] paramOrder, ParameterInfo[] pars, String[] names) { bool[] used = new bool[pars.Length]; // Mark which parameters have not been found in the names list for (int i = 0; i < pars.Length; i++) paramOrder[i] = -1; // Find the parameters with names. for (int i = 0; i < names.Length; i++) { int j; for (j = 0; j < pars.Length; j++) { if (names[i].Equals(pars[j].Name)) { paramOrder[j] = i; used[i] = true; break; } } // This is an error condition. The name was not found. This // method must not match what we sent. if (j == pars.Length) return false; } // Now we fill in the holes with the parameters that are unused. int pos = 0; for (int i = 0; i < pars.Length; i++) { if (paramOrder[i] == -1) { for (; pos < pars.Length; pos++) { if (!used[pos]) { paramOrder[i] = pos; pos++; break; } } } } return true; } internal class BinderState { internal int[] m_argsMap; internal int m_originalSize; internal bool m_isParamArray; internal BinderState(int[] argsMap, int originalSize, bool isParamArray) { m_argsMap = argsMap; m_originalSize = originalSize; m_isParamArray = isParamArray; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; namespace System.IO { /// <summary>Provides an implementation of FileSystem for Unix systems.</summary> internal sealed partial class UnixFileSystem : FileSystem { internal const int DefaultBufferSize = 4096; public override int MaxPath { get { return Interop.Sys.MaxPath; } } public override int MaxDirectoryPath { get { return Interop.Sys.MaxPath; } } public override FileStream Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent) { return new FileStream(fullPath, mode, access, share, bufferSize, options); } public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite) { // The destination path may just be a directory into which the file should be copied. // If it is, append the filename from the source onto the destination directory if (DirectoryExists(destFullPath)) { destFullPath = Path.Combine(destFullPath, Path.GetFileName(sourceFullPath)); } // Copy the contents of the file from the source to the destination, creating the destination in the process using (var src = new FileStream(sourceFullPath, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, FileOptions.None)) using (var dst = new FileStream(destFullPath, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, DefaultBufferSize, FileOptions.None)) { Interop.CheckIo(Interop.Sys.CopyFile(src.SafeFileHandle, dst.SafeFileHandle)); } } public override void ReplaceFile(string sourceFullPath, string destFullPath, string destBackupFullPath, bool ignoreMetadataErrors) { if (destBackupFullPath != null) { // We're backing up the destination file to the backup file, so we need to first delete the backup // file, if it exists. If deletion fails for a reason other than the file not existing, fail. if (Interop.Sys.Unlink(destBackupFullPath) != 0) { Interop.ErrorInfo errno = Interop.Sys.GetLastErrorInfo(); if (errno.Error != Interop.Error.ENOENT) { throw Interop.GetExceptionForIoErrno(errno, destBackupFullPath); } } // Now that the backup is gone, link the backup to point to the same file as destination. // This way, we don't lose any data in the destination file, no copy is necessary, etc. Interop.CheckIo(Interop.Sys.Link(destFullPath, destBackupFullPath), destFullPath); } else { // There is no backup file. Just make sure the destination file exists, throwing if it doesn't. Interop.Sys.FileStatus ignored; if (Interop.Sys.Stat(destFullPath, out ignored) != 0) { Interop.ErrorInfo errno = Interop.Sys.GetLastErrorInfo(); if (errno.Error == Interop.Error.ENOENT) { throw Interop.GetExceptionForIoErrno(errno, destBackupFullPath); } } } // Finally, rename the source to the destination, overwriting the destination. Interop.CheckIo(Interop.Sys.Rename(sourceFullPath, destFullPath)); } public override void MoveFile(string sourceFullPath, string destFullPath) { // The desired behavior for Move(source, dest) is to not overwrite the destination file // if it exists. Since rename(source, dest) will replace the file at 'dest' if it exists, // link/unlink are used instead. However, if the source path and the dest path refer to // the same file, then do a rename rather than a link and an unlink. This is important // for case-insensitive file systems (e.g. renaming a file in a way that just changes casing), // so that we support changing the casing in the naming of the file. If this fails in any // way (e.g. source file doesn't exist, dest file doesn't exist, rename fails, etc.), we // just fall back to trying the link/unlink approach and generating any exceptional messages // from there as necessary. Interop.Sys.FileStatus sourceStat, destStat; if (Interop.Sys.LStat(sourceFullPath, out sourceStat) == 0 && // source file exists Interop.Sys.LStat(destFullPath, out destStat) == 0 && // dest file exists sourceStat.Dev == destStat.Dev && // source and dest are on the same device sourceStat.Ino == destStat.Ino && // and source and dest are the same file on that device Interop.Sys.Rename(sourceFullPath, destFullPath) == 0) // try the rename { // Renamed successfully. return; } if (Interop.Sys.Link(sourceFullPath, destFullPath) < 0) { // If link fails, we can fall back to doing a full copy, but we'll only do so for // cases where we expect link could fail but such a copy could succeed. We don't // want to do so for all errors, because the copy could incur a lot of cost // even if we know it'll eventually fail, e.g. EROFS means that the source file // system is read-only and couldn't support the link being added, but if it's // read-only, then the move should fail any way due to an inability to delete // the source file. Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EXDEV || // rename fails across devices / mount points errorInfo.Error == Interop.Error.EPERM || // permissions might not allow creating hard links even if a copy would work errorInfo.Error == Interop.Error.EOPNOTSUPP || // links aren't supported by the source file system errorInfo.Error == Interop.Error.EMLINK) // too many hard links to the source file { CopyFile(sourceFullPath, destFullPath, overwrite: false); } else { // The operation failed. Within reason, try to determine which path caused the problem // so we can throw a detailed exception. string path = null; bool isDirectory = false; if (errorInfo.Error == Interop.Error.ENOENT) { if (!Directory.Exists(Path.GetDirectoryName(destFullPath))) { // The parent directory of destFile can't be found. // Windows distinguishes between whether the directory or the file isn't found, // and throws a different exception in these cases. We attempt to approximate that // here; there is a race condition here, where something could change between // when the error occurs and our checks, but it's the best we can do, and the // worst case in such a race condition (which could occur if the file system is // being manipulated concurrently with these checks) is that we throw a // FileNotFoundException instead of DirectoryNotFoundexception. path = destFullPath; isDirectory = true; } else { path = sourceFullPath; } } else if (errorInfo.Error == Interop.Error.EEXIST) { path = destFullPath; } throw Interop.GetExceptionForIoErrno(errorInfo, path, isDirectory); } } DeleteFile(sourceFullPath); } public override void DeleteFile(string fullPath) { if (Interop.Sys.Unlink(fullPath) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); // ENOENT means it already doesn't exist; nop if (errorInfo.Error != Interop.Error.ENOENT) { if (errorInfo.Error == Interop.Error.EISDIR) errorInfo = Interop.Error.EACCES.Info(); throw Interop.GetExceptionForIoErrno(errorInfo, fullPath); } } } public override void CreateDirectory(string fullPath) { // NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory. int length = fullPath.Length; // We need to trim the trailing slash or the code will try to create 2 directories of the same name. if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath)) { length--; } // For paths that are only // or /// if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1])) { throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath)); } // We can save a bunch of work if the directory we want to create already exists. if (DirectoryExists(fullPath)) { return; } // Attempt to figure out which directories don't exist, and only create the ones we need. bool somepathexists = false; Stack<string> stackDir = new Stack<string>(); int lengthRoot = PathInternal.GetRootLength(fullPath); if (length > lengthRoot) { int i = length - 1; while (i >= lengthRoot && !somepathexists) { string dir = fullPath.Substring(0, i + 1); if (!DirectoryExists(dir)) // Create only the ones missing { stackDir.Push(dir); } else { somepathexists = true; } while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i])) { i--; } i--; } } int count = stackDir.Count; if (count == 0 && !somepathexists) { string root = Directory.InternalGetDirectoryRoot(fullPath); if (!DirectoryExists(root)) { throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true); } return; } // Create all the directories int result = 0; Interop.ErrorInfo firstError = default(Interop.ErrorInfo); string errorString = fullPath; while (stackDir.Count > 0) { string name = stackDir.Pop(); if (name.Length >= MaxDirectoryPath) { throw new PathTooLongException(SR.IO_PathTooLong); } // The mkdir command uses 0777 by default (it'll be AND'd with the process umask internally). // We do the same. result = Interop.Sys.MkDir(name, (int)Interop.Sys.Permissions.Mask); if (result < 0 && firstError.Error == 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); // While we tried to avoid creating directories that don't // exist above, there are a few cases that can fail, e.g. // a race condition where another process or thread creates // the directory first, or there's a file at the location. if (errorInfo.Error != Interop.Error.EEXIST) { firstError = errorInfo; } else if (FileExists(name) || (!DirectoryExists(name, out errorInfo) && errorInfo.Error == Interop.Error.EACCES)) { // If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw. firstError = errorInfo; errorString = name; } } } // Only throw an exception if creating the exact directory we wanted failed to work correctly. if (result < 0 && firstError.Error != 0) { throw Interop.GetExceptionForIoErrno(firstError, errorString, isDirectory: true); } } public override void MoveDirectory(string sourceFullPath, string destFullPath) { // Windows doesn't care if you try and copy a file via "MoveDirectory"... if (FileExists(sourceFullPath)) { // ... but it doesn't like the source to have a trailing slash ... // On Windows we end up with ERROR_INVALID_NAME, which is // "The filename, directory name, or volume label syntax is incorrect." // // This surfaces as a IOException, if we let it go beyond here it would // give DirectoryNotFound. if (PathHelpers.EndsInDirectorySeparator(sourceFullPath)) throw new IOException(SR.Format(SR.IO_PathNotFound_Path, sourceFullPath)); // ... but it doesn't care if the destination has a trailing separator. destFullPath = PathHelpers.TrimEndingDirectorySeparator(destFullPath); } if (Interop.Sys.Rename(sourceFullPath, destFullPath) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); switch (errorInfo.Error) { case Interop.Error.EACCES: // match Win32 exception throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), errorInfo.RawErrno); default: throw Interop.GetExceptionForIoErrno(errorInfo, sourceFullPath, isDirectory: true); } } } public override void RemoveDirectory(string fullPath, bool recursive) { var di = new DirectoryInfo(fullPath); if (!di.Exists) { throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true); } RemoveDirectoryInternal(di, recursive, throwOnTopLevelDirectoryNotFound: true); } private void RemoveDirectoryInternal(DirectoryInfo directory, bool recursive, bool throwOnTopLevelDirectoryNotFound) { Exception firstException = null; if ((directory.Attributes & FileAttributes.ReparsePoint) != 0) { DeleteFile(directory.FullName); return; } if (recursive) { try { foreach (string item in EnumeratePaths(directory.FullName, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both)) { if (!ShouldIgnoreDirectory(Path.GetFileName(item))) { try { var childDirectory = new DirectoryInfo(item); if (childDirectory.Exists) { RemoveDirectoryInternal(childDirectory, recursive, throwOnTopLevelDirectoryNotFound: false); } else { DeleteFile(item); } } catch (Exception exc) { if (firstException != null) { firstException = exc; } } } } } catch (Exception exc) { if (firstException != null) { firstException = exc; } } if (firstException != null) { throw firstException; } } if (Interop.Sys.RmDir(directory.FullName) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); switch (errorInfo.Error) { case Interop.Error.EACCES: case Interop.Error.EPERM: case Interop.Error.EROFS: case Interop.Error.EISDIR: throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, directory.FullName)); // match Win32 exception case Interop.Error.ENOENT: if (!throwOnTopLevelDirectoryNotFound) { return; } goto default; default: throw Interop.GetExceptionForIoErrno(errorInfo, directory.FullName, isDirectory: true); } } } public override bool DirectoryExists(string fullPath) { Interop.ErrorInfo ignored; return DirectoryExists(fullPath, out ignored); } private static bool DirectoryExists(string fullPath, out Interop.ErrorInfo errorInfo) { return FileExists(fullPath, Interop.Sys.FileTypes.S_IFDIR, out errorInfo); } public override bool FileExists(string fullPath) { Interop.ErrorInfo ignored; // Windows doesn't care about the trailing separator return FileExists(PathHelpers.TrimEndingDirectorySeparator(fullPath), Interop.Sys.FileTypes.S_IFREG, out ignored); } private static bool FileExists(string fullPath, int fileType, out Interop.ErrorInfo errorInfo) { Debug.Assert(fileType == Interop.Sys.FileTypes.S_IFREG || fileType == Interop.Sys.FileTypes.S_IFDIR); Interop.Sys.FileStatus fileinfo; errorInfo = default(Interop.ErrorInfo); // First use stat, as we want to follow symlinks. If that fails, it could be because the symlink // is broken, we don't have permissions, etc., in which case fall back to using LStat to evaluate // based on the symlink itself. if (Interop.Sys.Stat(fullPath, out fileinfo) < 0 && Interop.Sys.LStat(fullPath, out fileinfo) < 0) { errorInfo = Interop.Sys.GetLastErrorInfo(); return false; } // Something exists at this path. If the caller is asking for a directory, return true if it's // a directory and false for everything else. If the caller is asking for a file, return false for // a directory and true for everything else. return (fileType == Interop.Sys.FileTypes.S_IFDIR) == ((fileinfo.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR); } public override IEnumerable<string> EnumeratePaths(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { return new FileSystemEnumerable<string>(path, searchPattern, searchOption, searchTarget, (p, _) => p); } public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { switch (searchTarget) { case SearchTarget.Files: return new FileSystemEnumerable<FileInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => new FileInfo(path, null)); case SearchTarget.Directories: return new FileSystemEnumerable<DirectoryInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => new DirectoryInfo(path, null)); default: return new FileSystemEnumerable<FileSystemInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => isDir ? (FileSystemInfo)new DirectoryInfo(path, null) : (FileSystemInfo)new FileInfo(path, null)); } } private sealed class FileSystemEnumerable<T> : IEnumerable<T> { private readonly PathPair _initialDirectory; private readonly string _searchPattern; private readonly SearchOption _searchOption; private readonly bool _includeFiles; private readonly bool _includeDirectories; private readonly Func<string, bool, T> _translateResult; private IEnumerator<T> _firstEnumerator; internal FileSystemEnumerable( string userPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget, Func<string, bool, T> translateResult) { // Basic validation of the input path if (userPath == null) { throw new ArgumentNullException("path"); } if (string.IsNullOrWhiteSpace(userPath)) { throw new ArgumentException(SR.Argument_EmptyPath, "path"); } // Validate and normalize the search pattern. If after doing so it's empty, // matching Win32 behavior we can skip all additional validation and effectively // return an empty enumerable. searchPattern = NormalizeSearchPattern(searchPattern); if (searchPattern.Length > 0) { PathHelpers.CheckSearchPattern(searchPattern); PathHelpers.ThrowIfEmptyOrRootedPath(searchPattern); // If the search pattern contains any paths, make sure we factor those into // the user path, and then trim them off. int lastSlash = searchPattern.LastIndexOf(Path.DirectorySeparatorChar); if (lastSlash >= 0) { if (lastSlash >= 1) { userPath = Path.Combine(userPath, searchPattern.Substring(0, lastSlash)); } searchPattern = searchPattern.Substring(lastSlash + 1); } string fullPath = Path.GetFullPath(userPath); // Store everything for the enumerator _initialDirectory = new PathPair(userPath, fullPath); _searchPattern = searchPattern; _searchOption = searchOption; _includeFiles = (searchTarget & SearchTarget.Files) != 0; _includeDirectories = (searchTarget & SearchTarget.Directories) != 0; _translateResult = translateResult; } // Open the first enumerator so that any errors are propagated synchronously. _firstEnumerator = Enumerate(); } public IEnumerator<T> GetEnumerator() { return Interlocked.Exchange(ref _firstEnumerator, null) ?? Enumerate(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private IEnumerator<T> Enumerate() { return Enumerate( _initialDirectory.FullPath != null ? OpenDirectory(_initialDirectory.FullPath) : null); } private IEnumerator<T> Enumerate(Microsoft.Win32.SafeHandles.SafeDirectoryHandle dirHandle) { if (dirHandle == null) { // Empty search yield break; } Debug.Assert(!dirHandle.IsInvalid); Debug.Assert(!dirHandle.IsClosed); // Maintain a stack of the directories to explore, in the case of SearchOption.AllDirectories // Lazily-initialized only if we find subdirectories that will be explored. Stack<PathPair> toExplore = null; PathPair dirPath = _initialDirectory; while (dirHandle != null) { try { // Read each entry from the enumerator Interop.Sys.DirectoryEntry dirent; while (Interop.Sys.ReadDir(dirHandle, out dirent) == 0) { // Get from the dir entry whether the entry is a file or directory. // We classify everything as a file unless we know it to be a directory. bool isDir; if (dirent.InodeType == Interop.Sys.NodeType.DT_DIR) { // We know it's a directory. isDir = true; } else if (dirent.InodeType == Interop.Sys.NodeType.DT_LNK || dirent.InodeType == Interop.Sys.NodeType.DT_UNKNOWN) { // It's a symlink or unknown: stat to it to see if we can resolve it to a directory. // If we can't (e.g. symlink to a file, broken symlink, etc.), we'll just treat it as a file. Interop.ErrorInfo errnoIgnored; isDir = DirectoryExists(Path.Combine(dirPath.FullPath, dirent.InodeName), out errnoIgnored); } else { // Otherwise, treat it as a file. This includes regular files, FIFOs, etc. isDir = false; } // Yield the result if the user has asked for it. In the case of directories, // always explore it by pushing it onto the stack, regardless of whether // we're returning directories. if (isDir) { if (!ShouldIgnoreDirectory(dirent.InodeName)) { string userPath = null; if (_searchOption == SearchOption.AllDirectories) { if (toExplore == null) { toExplore = new Stack<PathPair>(); } userPath = Path.Combine(dirPath.UserPath, dirent.InodeName); toExplore.Push(new PathPair(userPath, Path.Combine(dirPath.FullPath, dirent.InodeName))); } if (_includeDirectories && Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0) { yield return _translateResult(userPath ?? Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/true); } } } else if (_includeFiles && Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0) { yield return _translateResult(Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/false); } } } finally { // Close the directory enumerator dirHandle.Dispose(); dirHandle = null; } if (toExplore != null && toExplore.Count > 0) { // Open the next directory. dirPath = toExplore.Pop(); dirHandle = OpenDirectory(dirPath.FullPath); } } } private static string NormalizeSearchPattern(string searchPattern) { if (searchPattern == "." || searchPattern == "*.*") { searchPattern = "*"; } else if (PathHelpers.EndsInDirectorySeparator(searchPattern)) { searchPattern += "*"; } return searchPattern; } private static Microsoft.Win32.SafeHandles.SafeDirectoryHandle OpenDirectory(string fullPath) { Microsoft.Win32.SafeHandles.SafeDirectoryHandle handle = Interop.Sys.OpenDir(fullPath); if (handle.IsInvalid) { throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), fullPath, isDirectory: true); } return handle; } } /// <summary>Determines whether the specified directory name should be ignored.</summary> /// <param name="name">The name to evaluate.</param> /// <returns>true if the name is "." or ".."; otherwise, false.</returns> private static bool ShouldIgnoreDirectory(string name) { return name == "." || name == ".."; } public override string GetCurrentDirectory() { return Interop.Sys.GetCwd(); } public override void SetCurrentDirectory(string fullPath) { Interop.CheckIo(Interop.Sys.ChDir(fullPath), fullPath, isDirectory:true); } public override FileAttributes GetAttributes(string fullPath) { FileAttributes attributes = new FileInfo(fullPath, null).Attributes; if (attributes == (FileAttributes)(-1)) FileSystemInfo.ThrowNotFound(fullPath); return attributes; } public override void SetAttributes(string fullPath, FileAttributes attributes) { new FileInfo(fullPath, null).Attributes = attributes; } public override DateTimeOffset GetCreationTime(string fullPath) { return new FileInfo(fullPath, null).CreationTime; } public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory) { IFileSystemObject info = asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); info.CreationTime = time; } public override DateTimeOffset GetLastAccessTime(string fullPath) { return new FileInfo(fullPath, null).LastAccessTime; } public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory) { IFileSystemObject info = asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); info.LastAccessTime = time; } public override DateTimeOffset GetLastWriteTime(string fullPath) { return new FileInfo(fullPath, null).LastWriteTime; } public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory) { IFileSystemObject info = asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); info.LastWriteTime = time; } public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory) { return asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); } public override string[] GetLogicalDrives() { return DriveInfoInternal.GetLogicalDrives(); } } }
/* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */ using System; using System.Collections; using System.IO; using System.IO.Compression; using System.Net; using System.Net.Sockets; using System.Reflection; using Razorvine.Pickle; using Razorvine.Pickle.Objects; namespace Razorvine.Pyro { /// <summary> /// Proxy for Pyro objects. /// </summary> public class PyroProxy : IDisposable { public string hostname {get;set;} public int port {get;set;} public string objectid {get;set;} private ushort sequenceNr = 0; private TcpClient sock; private NetworkStream sock_stream; static PyroProxy() { Unpickler.registerConstructor("Pyro4.errors", "PyroError", new AnyClassConstructor(typeof(PyroException))); Unpickler.registerConstructor("Pyro4.errors", "CommunicationError", new AnyClassConstructor(typeof(PyroException))); Unpickler.registerConstructor("Pyro4.errors", "ConnectionClosedError", new AnyClassConstructor(typeof(PyroException))); Unpickler.registerConstructor("Pyro4.errors", "TimeoutError", new AnyClassConstructor(typeof(PyroException))); Unpickler.registerConstructor("Pyro4.errors", "ProtocolError", new AnyClassConstructor(typeof(PyroException))); Unpickler.registerConstructor("Pyro4.errors", "NamingError", new AnyClassConstructor(typeof(PyroException))); Unpickler.registerConstructor("Pyro4.errors", "DaemonError", new AnyClassConstructor(typeof(PyroException))); Unpickler.registerConstructor("Pyro4.errors", "SecurityError", new AnyClassConstructor(typeof(PyroException))); Unpickler.registerConstructor("Pyro4.errors", "AsyncResultTimeout", new AnyClassConstructor(typeof(PyroException))); Unpickler.registerConstructor("Pyro4.core", "Proxy", new ProxyClassConstructor()); Unpickler.registerConstructor("Pyro4.util", "Serializer", new AnyClassConstructor(typeof(DummyPyroSerializer))); Unpickler.registerConstructor("Pyro4.utils.flame", "FlameBuiltin", new AnyClassConstructor(typeof(FlameBuiltin))); Unpickler.registerConstructor("Pyro4.utils.flame", "FlameModule", new AnyClassConstructor(typeof(FlameModule))); Unpickler.registerConstructor("Pyro4.utils.flame", "RemoteInteractiveConsole", new AnyClassConstructor(typeof(FlameRemoteConsole))); // make sure a PyroURI can also be pickled even when not directly imported: Unpickler.registerConstructor("Pyro4.core", "URI", new AnyClassConstructor(typeof(PyroURI))); Pickler.registerCustomPickler(typeof(PyroURI), new PyroUriPickler()); } /** * No-args constructor for (un)pickling support */ public PyroProxy() { } /** * Create a proxy for the remote Pyro object denoted by the uri */ public PyroProxy(PyroURI uri) : this(uri.host, uri.port, uri.objectid) { } /** * Create a proxy for the remote Pyro object on the given host and port, with the given objectid/name. */ public PyroProxy(string hostname, int port, string objectid) { this.hostname = hostname; this.port = port; this.objectid = objectid; } /** * Release resources when descructed */ ~PyroProxy() { this.close(); } public void Dispose() { close(); } /** * (re)connect the proxy to the remote Pyro daemon. */ protected void connect() { if (sock == null) { sock = new TcpClient(); sock.Connect(hostname,port); sock.NoDelay=true; sock_stream=sock.GetStream(); sequenceNr = 0; handshake(); } } /** * Call a method on the remote Pyro object this proxy is for. * @param method the name of the method you want to call * @param arguments zero or more arguments for the remote method * @return the result Object from the remote method call (can be anything, you need to typecast/introspect yourself). */ public object call(string method, params object[] arguments) { return call(method, 0, arguments); } /** * Call a method on the remote Pyro object this proxy is for, using Oneway call semantics (return immediately). * @param method the name of the method you want to call * @param arguments zero or more arguments for the remote method */ public void call_oneway(string method, params object[] arguments) { call(method, MessageFactory.FLAGS_ONEWAY, arguments); } /** * Internal call method to actually perform the Pyro method call and process the result. */ private object call(string method, int flags, params object[] parameters) { lock(this) { connect(); unchecked { sequenceNr++; // unchecked so this ushort wraps around 0-65535 instead of raising an OverflowException } Console.WriteLine("seq="+sequenceNr); } if (parameters == null) parameters = new object[] {}; object[] invokeparams = new object[] { objectid, method, parameters, // vargs new Hashtable(0) // no kwargs }; Pickler pickler=new Pickler(false); byte[] pickle = pickler.dumps(invokeparams); pickler.close(); byte[] headerdata = MessageFactory.createMsgHeader(MessageFactory.MSG_INVOKE, pickle, flags, sequenceNr); Message resultmsg; lock (this.sock) { IOUtil.send(sock_stream, headerdata); IOUtil.send(sock_stream, pickle); if(Config.MSG_TRACE_DIR!=null) { MessageFactory.TraceMessageSend(sequenceNr, headerdata, pickle); } pickle = null; headerdata = null; if ((flags & MessageFactory.FLAGS_ONEWAY) != 0) return null; resultmsg = MessageFactory.getMessage(sock_stream, MessageFactory.MSG_RESULT); } if (resultmsg.sequence != sequenceNr) { throw new PyroException("result msg out of sync"); } if ((resultmsg.flags & MessageFactory.FLAGS_COMPRESSED) != 0) { // we need to skip the first 2 bytes in the buffer due to a tiny mismatch between zlib-written // data and the deflate data bytes that .net expects. // See http://www.chiramattel.com/george/blog/2007/09/09/deflatestream-block-length-does-not-match.html using(MemoryStream compressed=new MemoryStream(resultmsg.data, 2, resultmsg.data.Length-2, false)) { using(DeflateStream decompresser=new DeflateStream(compressed, CompressionMode.Decompress)) { MemoryStream bos = new MemoryStream(resultmsg.data.Length); byte[] buffer = new byte[4096]; int numRead; while ((numRead = decompresser.Read(buffer, 0, buffer.Length)) != 0) { bos.Write(buffer, 0, numRead); } resultmsg.data=bos.ToArray(); } } } if ((resultmsg.flags & MessageFactory.FLAGS_EXCEPTION) != 0) { using(Unpickler unpickler=new Unpickler()) { Exception rx = (Exception) unpickler.loads(resultmsg.data); if (rx is PyroException) { throw (PyroException) rx; } else { PyroException px = new PyroException("remote exception occurred", rx); PropertyInfo remotetbProperty=rx.GetType().GetProperty("_pyroTraceback"); if(remotetbProperty!=null) { string remotetb=(string)remotetbProperty.GetValue(rx,null); px._pyroTraceback=remotetb; } throw px; } } } using(Unpickler unpickler=new Unpickler()) { return unpickler.loads(resultmsg.data); } } /** * Close the network connection of this Proxy. * If you re-use the proxy, it will automatically reconnect. */ public void close() { if (this.sock != null) { if(this.sock_stream!=null) this.sock_stream.Close(); this.sock.Client.Close(); this.sock.Close(); this.sock=null; this.sock_stream=null; } } /** * Perform the Pyro protocol connection handshake with the Pyro daemon. */ protected void handshake() { // do connection handshake MessageFactory.getMessage(sock_stream, MessageFactory.MSG_CONNECTOK); // message data is ignored for now, should be 'ok' :) } /** * called by the Unpickler to restore state. * args: pyroUri, pyroOneway(hashset), pyroSerializer, pyroTimeout */ public void __setstate__(object[] args) { PyroURI uri=(PyroURI)args[0]; // ignore the oneway hashset, the serializer object and the timeout // the only thing we need here is the uri. this.hostname=uri.host; this.port=uri.port; this.objectid=uri.objectid; this.sock=null; this.sock_stream=null; } } }
using System; using System.Globalization; using Android.App; using Android.Content; using Android.OS; using Android.Preferences; using Plugin.Settings.Abstractions; using Android.Runtime; namespace Plugin.Settings { /// <summary> /// Main Implementation for ISettings /// </summary> [Preserve(AllMembers = true)] public class SettingsImplementation : ISettings { private readonly object locker = new object(); #region Internal /// <summary> /// Gets the current value or the default that you specify. /// </summary> /// <typeparam name="T">Vaue of t (bool, int, float, long, string)</typeparam> /// <param name="key">Key for settings</param> /// <param name="defaultValue">default value if not set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>Value or default</returns> T GetValueOrDefaultInternal<T>(string key, T defaultValue = default(T), string fileName = null) { if (Application.Context == null) return defaultValue; if (!Contains(key, fileName)) { return defaultValue; } lock (locker) { using (var sharedPreferences = GetSharedPreference(fileName)) { return GetValueOrDefaultCore(sharedPreferences, key, defaultValue, fileName); } } } T GetValueOrDefaultCore<T>(ISharedPreferences sharedPreferences, string key, T defaultValue, string fileName) { Type typeOf = typeof(T); if (typeOf.IsGenericType && typeOf.GetGenericTypeDefinition() == typeof(Nullable<>)) { typeOf = Nullable.GetUnderlyingType(typeOf); } object value = null; var typeCode = Type.GetTypeCode(typeOf); bool resave = false; switch (typeCode) { case TypeCode.Decimal: //Android doesn't have decimal in shared prefs so get string and convert var savedDecimal = string.Empty; try { savedDecimal = sharedPreferences.GetString(key, string.Empty); } catch (Java.Lang.ClassCastException) { Console.WriteLine("Settings 1.5 change, have to remove key."); try { Console.WriteLine("Attempting to get old value."); savedDecimal = sharedPreferences.GetLong(key, (long)Convert.ToDecimal(defaultValue, CultureInfo.InvariantCulture)).ToString(); Console.WriteLine("Old value has been parsed and will be updated and saved."); } catch (Java.Lang.ClassCastException) { Console.WriteLine("Could not parse old value, will be lost."); } Remove(key, fileName); resave = true; } if (string.IsNullOrWhiteSpace(savedDecimal)) value = Convert.ToDecimal(defaultValue, CultureInfo.InvariantCulture); else value = Convert.ToDecimal(savedDecimal, CultureInfo.InvariantCulture); if (resave) AddOrUpdateValueInternal(key, value); break; case TypeCode.Boolean: value = sharedPreferences.GetBoolean(key, Convert.ToBoolean(defaultValue)); break; case TypeCode.Int64: value = sharedPreferences.GetLong(key, Convert.ToInt64(defaultValue, CultureInfo.InvariantCulture)); break; case TypeCode.String: value = sharedPreferences.GetString(key, Convert.ToString(defaultValue)); break; case TypeCode.Double: //Android doesn't have double, so must get as string and parse. var savedDouble = string.Empty; try { savedDouble = sharedPreferences.GetString(key, string.Empty); } catch (Java.Lang.ClassCastException) { Console.WriteLine("Settings 1.5 change, have to remove key."); try { Console.WriteLine("Attempting to get old value."); savedDouble = sharedPreferences.GetLong(key, (long)Convert.ToDouble(defaultValue, CultureInfo.InvariantCulture)) .ToString(); Console.WriteLine("Old value has been parsed and will be updated and saved."); } catch (Java.Lang.ClassCastException) { Console.WriteLine("Could not parse old value, will be lost."); } Remove(key, fileName); resave = true; } if (string.IsNullOrWhiteSpace(savedDouble)) value = defaultValue; else { if (!double.TryParse(savedDouble, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out double outDouble)) { var maxString = Convert.ToString(double.MaxValue, CultureInfo.InvariantCulture); outDouble = savedDouble.Equals(maxString) ? double.MaxValue : double.MinValue; } value = outDouble; } if (resave) AddOrUpdateValueInternal(key, value, fileName); break; case TypeCode.Int32: value = sharedPreferences.GetInt(key, Convert.ToInt32(defaultValue, CultureInfo.InvariantCulture)); break; case TypeCode.Single: value = sharedPreferences.GetFloat(key, Convert.ToSingle(defaultValue, CultureInfo.InvariantCulture)); break; case TypeCode.DateTime: if (sharedPreferences.Contains(key)) { var ticks = sharedPreferences.GetLong(key, 0); if (ticks >= 0) { //Old value, stored before update to UTC values value = new DateTime(ticks); } else { //New value, UTC value = new DateTime(-ticks, DateTimeKind.Utc); } } else { return defaultValue; } break; default: if (defaultValue is Guid) { var outGuid = Guid.Empty; Guid.TryParse(sharedPreferences.GetString(key, Guid.Empty.ToString()), out outGuid); value = outGuid; } else { throw new ArgumentException($"Value of type {typeCode} is not supported."); } break; } return null != value ? (T)value : defaultValue; } /// <summary> /// Adds or updates a value /// </summary> /// <param name="key">key to update</param> /// <param name="value">value to set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>True if added or update and you need to save</returns> bool AddOrUpdateValueInternal<T>(string key, T value, string fileName = null) { if (Application.Context == null) return false; if (value == null) { Remove(key, fileName); return true; } Type typeOf = typeof(T); if (typeOf.IsGenericType && typeOf.GetGenericTypeDefinition() == typeof(Nullable<>)) { typeOf = Nullable.GetUnderlyingType(typeOf); } var typeCode = Type.GetTypeCode(typeOf); return AddOrUpdateValueCore(key, value, typeCode, fileName); } bool AddOrUpdateValueCore(string key, object value, TypeCode typeCode, string fileName) { lock (locker) { using (var sharedPreferences = GetSharedPreference(fileName)) { using (var sharedPreferencesEditor = sharedPreferences.Edit()) { switch (typeCode) { case TypeCode.Decimal: sharedPreferencesEditor.PutString(key, Convert.ToString(value, CultureInfo.InvariantCulture)); break; case TypeCode.Boolean: sharedPreferencesEditor.PutBoolean(key, Convert.ToBoolean(value)); break; case TypeCode.Int64: sharedPreferencesEditor.PutLong(key, (long)Convert.ToInt64(value, CultureInfo.InvariantCulture)); break; case TypeCode.String: sharedPreferencesEditor.PutString(key, Convert.ToString(value)); break; case TypeCode.Double: var valueString = Convert.ToString(value, CultureInfo.InvariantCulture); sharedPreferencesEditor.PutString(key, valueString); break; case TypeCode.Int32: sharedPreferencesEditor.PutInt(key, Convert.ToInt32(value, CultureInfo.InvariantCulture)); break; case TypeCode.Single: sharedPreferencesEditor.PutFloat(key, Convert.ToSingle(value, CultureInfo.InvariantCulture)); break; case TypeCode.DateTime: sharedPreferencesEditor.PutLong(key, -(Convert.ToDateTime(value)).ToUniversalTime().Ticks); break; default: if (value is Guid) { sharedPreferencesEditor.PutString(key, ((Guid)value).ToString()); } else { throw new ArgumentException($"Value of type {typeCode} is not supported."); } break; } sharedPreferencesEditor.Commit(); } } } return true; } ISharedPreferences GetSharedPreference(string fileName) { return string.IsNullOrWhiteSpace(fileName) ? PreferenceManager.GetDefaultSharedPreferences(Application.Context) : Application.Context.GetSharedPreferences(fileName, FileCreationMode.Private); } #endregion /// <summary> /// Removes a desired key from the settings /// </summary> /// <param name="key">Key for setting</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> public void Remove(string key, string fileName = null) { if (Application.Context == null) return; lock (locker) { using (var sharedPreferences = GetSharedPreference(fileName)) { using (var sharedPreferencesEditor = sharedPreferences.Edit()) { sharedPreferencesEditor.Remove(key); sharedPreferencesEditor.Commit(); } } } } /// <summary> /// Clear all keys from settings /// </summary> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> public void Clear(string fileName = null) { if (Application.Context == null) return; lock (locker) { using (var sharedPreferences = GetSharedPreference(fileName)) { using (var sharedPreferencesEditor = sharedPreferences.Edit()) { sharedPreferencesEditor.Clear(); sharedPreferencesEditor.Commit(); } } } } /// <summary> /// Checks to see if the key has been added. /// </summary> /// <param name="key">Key to check</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>True if contains key, else false</returns> public bool Contains(string key, string fileName = null) { if (Application.Context == null) return false; lock (locker) { using (var sharedPreferences = GetSharedPreference(fileName)) { if (sharedPreferences == null) return false; return sharedPreferences.Contains(key); } } } #region GetValueOrDefault /// <summary> /// Gets the current value or the default that you specify. /// </summary> /// <param name="key">Key for settings</param> /// <param name="defaultValue">default value if not set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>Value or default</returns> public decimal GetValueOrDefault(string key, decimal defaultValue, string fileName = null) => GetValueOrDefaultInternal(key, defaultValue, fileName); /// <summary> /// Gets the current value or the default that you specify. /// </summary> /// <param name="key">Key for settings</param> /// <param name="defaultValue">default value if not set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>Value or default</returns> public bool GetValueOrDefault(string key, bool defaultValue, string fileName = null) => GetValueOrDefaultInternal(key, defaultValue, fileName); /// <summary> /// Gets the current value or the default that you specify. /// </summary> /// <param name="key">Key for settings</param> /// <param name="defaultValue">default value if not set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>Value or default</returns> public long GetValueOrDefault(string key, long defaultValue, string fileName = null) => GetValueOrDefaultInternal(key, defaultValue, fileName); /// <summary> /// Gets the current value or the default that you specify. /// </summary> /// <param name="key">Key for settings</param> /// <param name="defaultValue">default value if not set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>Value or default</returns> public string GetValueOrDefault(string key, string defaultValue, string fileName = null) => GetValueOrDefaultInternal(key, defaultValue, fileName); /// <summary> /// Gets the current value or the default that you specify. /// </summary> /// <param name="key">Key for settings</param> /// <param name="defaultValue">default value if not set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>Value or default</returns> public int GetValueOrDefault(string key, int defaultValue, string fileName = null) => GetValueOrDefaultInternal(key, defaultValue, fileName); /// <summary> /// Gets the current value or the default that you specify. /// </summary> /// <param name="key">Key for settings</param> /// <param name="defaultValue">default value if not set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>Value or default</returns> public float GetValueOrDefault(string key, float defaultValue, string fileName = null) => GetValueOrDefaultInternal(key, defaultValue, fileName); /// <summary> /// Gets the current value or the default that you specify. /// </summary> /// <param name="key">Key for settings</param> /// <param name="defaultValue">default value if not set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>Value or default</returns> public DateTime GetValueOrDefault(string key, DateTime defaultValue, string fileName = null) => GetValueOrDefaultInternal(key, defaultValue, fileName); /// <summary> /// Gets the current value or the default that you specify. /// </summary> /// <param name="key">Key for settings</param> /// <param name="defaultValue">default value if not set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>Value or default</returns> public Guid GetValueOrDefault(string key, Guid defaultValue, string fileName = null) => GetValueOrDefaultInternal(key, defaultValue, fileName); /// <summary> /// Gets the current value or the default that you specify. /// </summary> /// <param name="key">Key for settings</param> /// <param name="defaultValue">default value if not set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>Value or default</returns> public double GetValueOrDefault(string key, double defaultValue, string fileName = null) => GetValueOrDefaultInternal(key, defaultValue, fileName); #endregion #region AddOrUpdateValue /// <summary> /// Adds or updates the value /// </summary> /// <param name="key">Key for settting</param> /// <param name="value">Value to set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>True of was added or updated and you need to save it.</returns> public bool AddOrUpdateValue(string key, decimal value, string fileName = null) => AddOrUpdateValueInternal(key, value, fileName); /// <summary> /// Adds or updates the value /// </summary> /// <param name="key">Key for settting</param> /// <param name="value">Value to set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>True of was added or updated and you need to save it.</returns> public bool AddOrUpdateValue(string key, bool value, string fileName = null) => AddOrUpdateValueInternal(key, value, fileName); /// <summary> /// Adds or updates the value /// </summary> /// <param name="key">Key for settting</param> /// <param name="value">Value to set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>True of was added or updated and you need to save it.</returns> public bool AddOrUpdateValue(string key, long value, string fileName = null) => AddOrUpdateValueInternal(key, value, fileName); /// <summary> /// Adds or updates the value /// </summary> /// <param name="key">Key for settting</param> /// <param name="value">Value to set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>True of was added or updated and you need to save it.</returns> public bool AddOrUpdateValue(string key, string value, string fileName = null) => AddOrUpdateValueInternal(key, value, fileName); /// <summary> /// Adds or updates the value /// </summary> /// <param name="key">Key for settting</param> /// <param name="value">Value to set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>True of was added or updated and you need to save it.</returns> public bool AddOrUpdateValue(string key, int value, string fileName = null) => AddOrUpdateValueInternal(key, value, fileName); /// <summary> /// Adds or updates the value /// </summary> /// <param name="key">Key for settting</param> /// <param name="value">Value to set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>True of was added or updated and you need to save it.</returns> public bool AddOrUpdateValue(string key, float value, string fileName = null) => AddOrUpdateValueInternal(key, value, fileName); /// <summary> /// Adds or updates the value /// </summary> /// <param name="key">Key for settting</param> /// <param name="value">Value to set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>True of was added or updated and you need to save it.</returns> public bool AddOrUpdateValue(string key, DateTime value, string fileName = null) => AddOrUpdateValueInternal(key, value, fileName); /// <summary> /// Adds or updates the value /// </summary> /// <param name="key">Key for settting</param> /// <param name="value">Value to set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>True of was added or updated and you need to save it.</returns> public bool AddOrUpdateValue(string key, Guid value, string fileName = null) => AddOrUpdateValueInternal(key, value, fileName); /// <summary> /// Adds or updates the value /// </summary> /// <param name="key">Key for settting</param> /// <param name="value">Value to set</param> /// <param name="fileName">Name of file for settings to be stored and retrieved </param> /// <returns>True of was added or updated and you need to save it.</returns> public bool AddOrUpdateValue(string key, double value, string fileName = null) => AddOrUpdateValueInternal(key, value, fileName); #endregion /// <summary> /// Opens settings to app page /// </summary> /// <returns>true if could open.</returns> public bool OpenAppSettings() { var context = Application.Context; if (context == null) return false; try { var settingsIntent = new Intent(); settingsIntent.SetAction(Android.Provider.Settings.ActionApplicationDetailsSettings); settingsIntent.AddCategory(Intent.CategoryDefault); settingsIntent.SetData(Android.Net.Uri.Parse("package:" + context.PackageName)); settingsIntent.AddFlags(ActivityFlags.NewTask); settingsIntent.AddFlags(ActivityFlags.ClearTask); settingsIntent.AddFlags(ActivityFlags.NoHistory); settingsIntent.AddFlags(ActivityFlags.ExcludeFromRecents); context.StartActivity(settingsIntent); return true; } catch { return false; } } } }
using System; using CuttingEdge.Conditions; namespace Netco.Monads { /// <summary> /// Helper class that allows to pass out method call results without using exceptions /// </summary> /// <typeparam name="T">type of the associated data</typeparam> public sealed class Result< T > : IEquatable< Result< T > > { private readonly T _value; private readonly string _error; private Result( bool isSuccess, T value, string error ) { this.IsSuccess = isSuccess; this._value = value; this._error = error; } /// <summary> /// Error message associated with this failure /// </summary> [ Obsolete( "Use Error instead" ) ] public string ErrorMessage { get { return this._error; } } /// <summary> Creates failure result </summary> /// <param name="errorFormatString">format string for the error message</param> /// <param name="args">The arguments.</param> /// <returns>result that is a failure</returns> /// <exception cref="ArgumentNullException">if format string is null</exception> public static Result< T > CreateError( string errorFormatString, params object[] args ) { Condition.Requires( errorFormatString, "errorFormatString" ).IsNotNull(); return CreateError( string.Format( errorFormatString, args ) ); } /// <summary> /// Creates the success result. /// </summary> /// <param name="value">The value.</param> /// <returns>result encapsulating the success value</returns> /// <exception cref="ArgumentNullException">if value is a null reference type</exception> public static Result< T > CreateSuccess( T value ) { // ReSharper disable CompareNonConstrainedGenericWithNull if( value == null ) throw new ArgumentNullException( "value" ); // ReSharper restore CompareNonConstrainedGenericWithNull return new Result< T >( true, value, default( string ) ); } /// <summary> /// Converts value of this instance /// using the provided <paramref name="converter"/> /// </summary> /// <typeparam name="TTarget">The type of the target.</typeparam> /// <param name="converter">The converter.</param> /// <returns>Converted result</returns> /// <exception cref="ArgumentNullException"> if <paramref name="converter"/> is null</exception> public Result< TTarget > Convert< TTarget >( Func< T, TTarget > converter ) { Condition.Requires( converter, "converter" ).IsNotNull(); if( !this.IsSuccess ) return Result< TTarget >.CreateError( this._error ); return converter( this._value ); } /// <summary> /// Creates the error result. /// </summary> /// <param name="error">The error.</param> /// <returns>result encapsulating the error value</returns> /// <exception cref="ArgumentNullException">if error is null</exception> public static Result< T > CreateError( string error ) { Condition.Requires( error, "error" ).IsNotNull(); return new Result< T >( false, default( T ), error ); } /// <summary> /// Performs an implicit conversion from <typeparamref name="T"/> to <see cref="Result{T}"/>. /// </summary> /// <param name="value">The item.</param> /// <returns>The result of the conversion.</returns> /// <exception cref="ArgumentNullException">if <paramref name="value"/> is a reference type that is null</exception> public static implicit operator Result< T >( T value ) { // ReSharper disable CompareNonConstrainedGenericWithNull if( value == null ) throw new ArgumentNullException( "value" ); // ReSharper restore CompareNonConstrainedGenericWithNull return new Result< T >( true, value, null ); } /// <summary> /// Combines this <see cref="Result{T}"/> with the result returned /// by <paramref name="converter"/>. /// </summary> /// <typeparam name="TTarget">The type of the target.</typeparam> /// <param name="converter">The converter.</param> /// <returns>Combined result.</returns> public Result< TTarget > Combine< TTarget >( Func< T, Result< TTarget > > converter ) { if( !this.IsSuccess ) return Result< TTarget >.CreateError( this._error ); return converter( this._value ); } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false. /// </returns> /// <exception cref="T:System.NullReferenceException"> /// The <paramref name="obj"/> parameter is null. /// </exception> public override bool Equals( object obj ) { if( ReferenceEquals( null, obj ) ) return false; if( ReferenceEquals( this, obj ) ) return true; if( obj.GetType() != typeof( Result< T > ) ) return false; return this.Equals( ( Result< T > )obj ); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { unchecked { var result = this.IsSuccess.GetHashCode(); result = ( result * 397 ) ^ this._value.GetHashCode(); result = ( result * 397 ) ^ ( this._error != null ? this._error.GetHashCode() : 0 ); return result; } } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> public bool Equals( Result< T > other ) { if( ReferenceEquals( null, other ) ) return false; if( ReferenceEquals( this, other ) ) return true; return other.IsSuccess.Equals( this.IsSuccess ) && Equals( other._value, this._value ) && Equals( other._error, this._error ); } /// <summary> /// Applies the specified <paramref name="action"/> /// to this <see cref="Result{T}"/>, if it has value. /// </summary> /// <param name="action">The action to apply.</param> /// <returns>returns same instance for inlining</returns> /// <exception cref="ArgumentNullException">if <paramref name="action"/> is null</exception> public Result< T > Apply( Action< T > action ) { Condition.Requires( action, "action" ).IsNotNull(); if( this.IsSuccess ) action( this._value ); return this; } /// <summary> /// Handles the specified handler. /// </summary> /// <param name="handler">The handler.</param> /// <returns>same instance for the inlining</returns> public Result< T > Handle( Action< string > handler ) { Condition.Requires( handler, "handler" ).IsNotNull(); if( !this.IsSuccess ) handler( this._error ); return this; } /// <summary> /// Gets a value indicating whether this result is valid. /// </summary> /// <value><c>true</c> if this result is valid; otherwise, <c>false</c>.</value> public bool IsSuccess { get; private set; } /// <summary> /// item associated with this result /// </summary> public T Value { get { Condition.WithExceptionOnFailure< InvalidOperationException >().Requires( this.IsSuccess, "IsSuccess" ).IsTrue( "Code should not access value when the result has failed." ); return this._value; } } /// <summary> /// Error message associated with this failure /// </summary> public string Error { get { Condition.WithExceptionOnFailure< InvalidOperationException >().Requires( this.IsSuccess, "IsSuccess" ).IsFalse( "Code should not access error message when the result is valid." ); return this._error; } } /// <summary> /// Converts this <see cref="Result{T}"/> to <see cref="Maybe{T}"/>, /// using the <paramref name="converter"/> to perform the value conversion. /// </summary> /// <typeparam name="TTarget">The type of the target.</typeparam> /// <param name="converter">The reflector.</param> /// <returns><see cref="Maybe{T}"/> that represents the original value behind the <see cref="Result{T}"/> after the conversion</returns> public Maybe< TTarget > ToMaybe< TTarget >( Func< T, TTarget > converter ) { Condition.Requires( converter, "converter" ).IsNotNull(); if( !this.IsSuccess ) return Maybe< TTarget >.Empty; return converter( this._value ); } /// <summary> /// Converts this <see cref="Result{T}"/> to <see cref="Maybe{T}"/>, /// with the original value reference, if there is any. /// </summary> /// <returns><see cref="Maybe{T}"/> that represents the original value behind the <see cref="Result{T}"/>.</returns> public Maybe< T > ToMaybe() { if( !this.IsSuccess ) return Maybe< T >.Empty; return this._value; } /// <summary> /// Exposes result failure as the exception (providing compatibility, with the exception -expecting code). /// </summary> /// <param name="exception">The function to generate exception, provided the error string.</param> /// <returns>result value</returns> public T ExposeException( Func< string, Exception > exception ) { Condition.Requires( exception, "exception" ).IsNotNull(); if( !this.IsSuccess ) throw exception( this.Error ); // abdullin: we can return value here, since failure chain ends here return this.Value; } /// <summary> /// Performs an implicit conversion from <see cref="System.String"/> to <see cref="Result{T}"/>. /// </summary> /// <param name="error">The error.</param> /// <returns>The result of the conversion.</returns> /// <exception cref="ArgumentNullException">If value is a null reference type</exception> public static implicit operator Result< T >( string error ) { Condition.Requires( error, "error" ).IsNotNull(); return CreateError( error ); } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { if( !this.IsSuccess ) return "<Error: '" + this._error + "'>"; return "<Value: '" + this._value + "'>"; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text.RegularExpressions; using EnvDTE; using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Project; using Microsoft.VisualStudio.Project.Designers; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using VSLangProj; using VsWebSite; using MsBuildProject = Microsoft.Build.Evaluation.Project; using Project = EnvDTE.Project; using ProjectItem = EnvDTE.ProjectItem; namespace NuGet.VisualStudio { public static class ProjectExtensions { private const string WebConfig = "web.config"; private const string AppConfig = "app.config"; private const string BinFolder = "Bin"; private static readonly Dictionary<string, string> _knownNestedFiles = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "web.debug.config", "web.config" }, { "web.release.config", "web.config" } }; private static readonly HashSet<string> _supportedProjectTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { VsConstants.WebSiteProjectTypeGuid, VsConstants.CsharpProjectTypeGuid, VsConstants.VbProjectTypeGuid, VsConstants.CppProjectTypeGuid, VsConstants.JsProjectTypeGuid, VsConstants.FsharpProjectTypeGuid, VsConstants.NemerleProjectTypeGuid, VsConstants.WixProjectTypeGuid, VsConstants.SynergexProjectTypeGuid, VsConstants.NomadForVisualStudioProjectTypeGuid }; private static readonly HashSet<string> _unsupportedProjectTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { VsConstants.LightSwitchProjectTypeGuid, VsConstants.InstallShieldLimitedEditionTypeGuid }; private static readonly IEnumerable<string> _fileKinds = new[] { VsConstants.VsProjectItemKindPhysicalFile, VsConstants.VsProjectItemKindSolutionItem }; private static readonly IEnumerable<string> _folderKinds = new[] { VsConstants.VsProjectItemKindPhysicalFolder }; // List of project types that cannot have references added to them private static readonly string[] _unsupportedProjectTypesForAddingReferences = new[] { VsConstants.WixProjectTypeGuid, VsConstants.CppProjectTypeGuid, }; // List of project types that cannot have binding redirects added private static readonly string[] _unsupportedProjectTypesForBindingRedirects = new[] { VsConstants.WixProjectTypeGuid, VsConstants.JsProjectTypeGuid, VsConstants.NemerleProjectTypeGuid, VsConstants.CppProjectTypeGuid, VsConstants.SynergexProjectTypeGuid, VsConstants.NomadForVisualStudioProjectTypeGuid, }; private static readonly char[] PathSeparatorChars = new[] { Path.DirectorySeparatorChar }; // Get the ProjectItems for a folder path public static ProjectItems GetProjectItems(this Project project, string folderPath, bool createIfNotExists = false) { if (String.IsNullOrEmpty(folderPath)) { return project.ProjectItems; } // Traverse the path to get at the directory string[] pathParts = folderPath.Split(PathSeparatorChars, StringSplitOptions.RemoveEmptyEntries); // 'cursor' can contain a reference to either a Project instance or ProjectItem instance. // Both types have the ProjectItems property that we want to access. object cursor = project; string fullPath = project.GetFullPath(); string folderRelativePath = String.Empty; foreach (string part in pathParts) { fullPath = Path.Combine(fullPath, part); folderRelativePath = Path.Combine(folderRelativePath, part); cursor = GetOrCreateFolder(project, cursor, fullPath, folderRelativePath, part, createIfNotExists); if (cursor == null) { return null; } } return GetProjectItems(cursor); } public static ProjectItem GetProjectItem(this Project project, string path) { string folderPath = Path.GetDirectoryName(path); string itemName = Path.GetFileName(path); ProjectItems container = GetProjectItems(project, folderPath); ProjectItem projectItem; // If we couldn't get the folder, or the child item doesn't exist, return null if (container == null || (!container.TryGetFile(itemName, out projectItem) && !container.TryGetFolder(itemName, out projectItem))) { return null; } return projectItem; } /// <summary> /// Recursively retrieves all supported child projects of a virtual folder. /// </summary> /// <param name="project">The root container project</param> public static IEnumerable<Project> GetSupportedChildProjects(this Project project) { if (!project.IsSolutionFolder()) { yield break; } var containerProjects = new Queue<Project>(); containerProjects.Enqueue(project); while (containerProjects.Any()) { var containerProject = containerProjects.Dequeue(); foreach (ProjectItem item in containerProject.ProjectItems) { var nestedProject = item.SubProject; if (nestedProject == null) { continue; } else if (nestedProject.IsSupported()) { yield return nestedProject; } else if (nestedProject.IsSolutionFolder()) { containerProjects.Enqueue(nestedProject); } } } } public static bool DeleteProjectItem(this Project project, string path) { ProjectItem projectItem = GetProjectItem(project, path); if (projectItem == null) { return false; } projectItem.Delete(); return true; } public static bool TryGetFolder(this ProjectItems projectItems, string name, out ProjectItem projectItem) { projectItem = GetProjectItem(projectItems, name, _folderKinds); return projectItem != null; } public static bool TryGetFile(this ProjectItems projectItems, string name, out ProjectItem projectItem) { projectItem = GetProjectItem(projectItems, name, _fileKinds); if (projectItem == null) { // Try to get the nested project item return TryGetNestedFile(projectItems, name, out projectItem); } return projectItem != null; } public static bool ContainsFile(this Project project, string path) { if (string.Equals(project.Kind, VsConstants.WixProjectTypeGuid, StringComparison.OrdinalIgnoreCase) || string.Equals(project.Kind, VsConstants.NemerleProjectTypeGuid, StringComparison.OrdinalIgnoreCase)) { // For Wix project, IsDocumentInProject() returns not found // even though the file is in the project. So we use GetProjectItem() // instead. ProjectItem item = project.GetProjectItem(path); return item != null; } else { IVsProject vsProject = (IVsProject)project.ToVsHierarchy(); if (vsProject == null) { return false; } int pFound; uint itemId; int hr = vsProject.IsDocumentInProject(path, out pFound, new VSDOCUMENTPRIORITY[0], out itemId); return ErrorHandler.Succeeded(hr) && pFound == 1; } } /// <summary> /// If we didn't find the project item at the top level, then we look one more level down. /// In VS files can have other nested files like foo.aspx and foo.aspx.cs or web.config and web.debug.config. /// These are actually top level files in the file system but are represented as nested project items in VS. /// </summary> private static bool TryGetNestedFile(ProjectItems projectItems, string name, out ProjectItem projectItem) { string parentFileName; if (!_knownNestedFiles.TryGetValue(name, out parentFileName)) { parentFileName = Path.GetFileNameWithoutExtension(name); } // If it's not one of the known nested files then we're going to look up prefixes backwards // i.e. if we're looking for foo.aspx.cs then we look for foo.aspx then foo.aspx.cs as a nested file ProjectItem parentProjectItem = GetProjectItem(projectItems, parentFileName, _fileKinds); if (parentProjectItem != null) { // Now try to find the nested file projectItem = GetProjectItem(parentProjectItem.ProjectItems, name, _fileKinds); } else { projectItem = null; } return projectItem != null; } public static bool SupportsConfig(this Project project) { return !IsClassLibrary(project); } public static string GetUniqueName(this Project project) { if (project.IsWixProject()) { // Wix project doesn't offer UniqueName property return project.FullName; } try { return project.UniqueName; } catch (COMException) { return project.FullName; } } private static bool IsClassLibrary(this Project project) { if (project.IsWebSite()) { return false; } // Consider class libraries projects that have one project type guid and an output type of project library. var outputType = project.GetPropertyValue<prjOutputType>("OutputType"); return project.GetProjectTypeGuids().Length == 1 && outputType == prjOutputType.prjOutputTypeLibrary; } public static bool IsJavaScriptProject(this Project project) { return project != null && VsConstants.JsProjectTypeGuid.Equals(project.Kind, StringComparison.OrdinalIgnoreCase); } public static bool IsNativeProject(this Project project) { return project != null && VsConstants.CppProjectTypeGuid.Equals(project.Kind, StringComparison.OrdinalIgnoreCase); } // TODO: Return null for library projects public static string GetConfigurationFile(this Project project) { return project.IsWebProject() ? WebConfig : AppConfig; } private static ProjectItem GetProjectItem(this ProjectItems projectItems, string name, IEnumerable<string> allowedItemKinds) { try { ProjectItem projectItem = projectItems.Item(name); if (projectItem != null && allowedItemKinds.Contains(projectItem.Kind, StringComparer.OrdinalIgnoreCase)) { return projectItem; } } catch { } return null; } public static IEnumerable<ProjectItem> GetChildItems(this Project project, string path, string filter, params string[] kinds) { ProjectItems projectItems = GetProjectItems(project, path); if (projectItems == null) { return Enumerable.Empty<ProjectItem>(); } Regex matcher = filter.Equals("*.*", StringComparison.OrdinalIgnoreCase) ? null : GetFilterRegex(filter); return from ProjectItem p in projectItems where kinds.Contains(p.Kind) && (matcher == null || matcher.IsMatch(p.Name)) select p; } public static string GetFullPath(this Project project) { string fullPath = project.GetPropertyValue<string>("FullPath"); if (!String.IsNullOrEmpty(fullPath)) { // Some Project System implementations (JS metro app) return the project // file as FullPath. We only need the parent directory if (File.Exists(fullPath)) { fullPath = Path.GetDirectoryName(fullPath); } } else { // C++ projects do not have FullPath property, but do have ProjectDirectory one. fullPath = project.GetPropertyValue<string>("ProjectDirectory"); } return fullPath; } public static string GetTargetFramework(this Project project) { if (project == null) { return null; } if (project.IsJavaScriptProject()) { // HACK: The JS Metro project does not have a TargetFrameworkMoniker property set. // We hard-code the return value so that it behaves as if it had a WinRT target // framework, i.e. .NETCore, Version=4.5 // Review: What about future versions? Let's not worry about that for now. return ".NETCore, Version=4.5"; } if (project.IsNativeProject()) { // The C++ project does not have a TargetFrameworkMoniker property set. // We hard-code the return value to Native. return "Native, Version=0.0"; } return project.GetPropertyValue<string>("TargetFrameworkMoniker"); } public static FrameworkName GetTargetFrameworkName(this Project project) { string targetFrameworkMoniker = project.GetTargetFramework(); if (targetFrameworkMoniker != null) { return new FrameworkName(targetFrameworkMoniker); } return null; } public static T GetPropertyValue<T>(this Project project, string propertyName) { if (project.Properties == null) { // this happens in unit tests return default(T); } try { Property property = project.Properties.Item(propertyName); if (property != null) { // REVIEW: Should this cast or convert? return (T)property.Value; } } catch (ArgumentException) { } return default(T); } private static Regex GetFilterRegex(string wildcard) { string pattern = String.Join(String.Empty, wildcard.Split('.').Select(GetPattern)); return new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); } private static string GetPattern(string token) { return token == "*" ? @"(.*)" : @"(" + token + ")"; } // 'parentItem' can be either a Project or ProjectItem private static ProjectItem GetOrCreateFolder( Project project, object parentItem, string fullPath, string folderRelativePath, string folderName, bool createIfNotExists) { if (parentItem == null) { return null; } ProjectItem subFolder; ProjectItems projectItems = GetProjectItems(parentItem); if (projectItems.TryGetFolder(folderName, out subFolder)) { // Get the sub folder return subFolder; } else if (createIfNotExists) { // The JS Metro project system has a bug whereby calling AddFolder() to an existing folder that // does not belong to the project will throw. To work around that, we have to manually include // it into our project. if (project.IsJavaScriptProject() && Directory.Exists(fullPath)) { bool succeeded = IncludeExistingFolderToProject(project, folderRelativePath); if (succeeded) { // IMPORTANT: after including the folder into project, we need to get // a new ProjectItems snapshot from the parent item. Otherwise, reusing // the old snapshot from above won't have access to the added folder. projectItems = GetProjectItems(parentItem); if (projectItems.TryGetFolder(folderName, out subFolder)) { // Get the sub folder return subFolder; } } return null; } try { return projectItems.AddFromDirectory(fullPath); } catch (NotImplementedException) { // This is the case for F#'s project system, we can't add from directory so we fall back // to this impl return projectItems.AddFolder(folderName); } } return null; } private static ProjectItems GetProjectItems(object parent) { var project = parent as Project; if (project != null) { return project.ProjectItems; } var projectItem = parent as ProjectItem; if (projectItem != null) { return projectItem.ProjectItems; } return null; } private static bool IncludeExistingFolderToProject(Project project, string folderRelativePath) { IVsUIHierarchy projectHierarchy = (IVsUIHierarchy)project.ToVsHierarchy(); uint itemId; int hr = projectHierarchy.ParseCanonicalName(folderRelativePath, out itemId); if (!ErrorHandler.Succeeded(hr)) { return false; } // Execute command to include the existing folder into project. Must do this on UI thread. hr = ThreadHelper.Generic.Invoke(() => projectHierarchy.ExecCommand( itemId, ref VsMenus.guidStandardCommandSet2K, (int)VSConstants.VSStd2KCmdID.INCLUDEINPROJECT, 0, IntPtr.Zero, IntPtr.Zero)); return ErrorHandler.Succeeded(hr); } public static bool IsWebProject(this Project project) { string[] types = project.GetProjectTypeGuids(); return types.Contains(VsConstants.WebSiteProjectTypeGuid, StringComparer.OrdinalIgnoreCase) || types.Contains(VsConstants.WebApplicationProjectTypeGuid, StringComparer.OrdinalIgnoreCase); } public static bool IsWebSite(this Project project) { return project.Kind != null && project.Kind.Equals(VsConstants.WebSiteProjectTypeGuid, StringComparison.OrdinalIgnoreCase); } public static bool IsWindowsStoreApp(this Project project) { string[] types = project.GetProjectTypeGuids(); return types.Contains(VsConstants.WindowsStoreProjectTypeGuid, StringComparer.OrdinalIgnoreCase); } public static bool IsWixProject(this Project project) { return project.Kind != null && project.Kind.Equals(VsConstants.WixProjectTypeGuid, StringComparison.OrdinalIgnoreCase); } public static bool IsSupported(this Project project) { return project.Kind != null && _supportedProjectTypes.Contains(project.Kind); } public static bool IsExplicitlyUnsupported(this Project project) { return project.Kind == null || _unsupportedProjectTypes.Contains(project.Kind); } public static bool IsSolutionFolder(this Project project) { return project.Kind != null && project.Kind.Equals(VsConstants.VsProjectItemKindSolutionFolder, StringComparison.OrdinalIgnoreCase); } public static bool IsTopLevelSolutionFolder(this Project project) { return IsSolutionFolder(project) && project.ParentProjectItem == null; } public static bool SupportsReferences(this Project project) { return project.Kind != null && !_unsupportedProjectTypesForAddingReferences.Contains(project.Kind, StringComparer.OrdinalIgnoreCase); } public static bool SupportsBindingRedirects(this Project project) { return (project.Kind != null & !_unsupportedProjectTypesForBindingRedirects.Contains(project.Kind, StringComparer.OrdinalIgnoreCase)) && !project.IsWindowsStoreApp(); } public static bool IsUnloaded(this Project project) { return VsConstants.UnloadedProjectTypeGuid.Equals(project.Kind, StringComparison.OrdinalIgnoreCase); } public static string GetOutputPath(this Project project) { // For Websites the output path is the bin folder string outputPath = project.IsWebSite() ? BinFolder : project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value.ToString(); return Path.Combine(project.GetFullPath(), outputPath); } public static IVsHierarchy ToVsHierarchy(this Project project) { IVsHierarchy hierarchy; // Get the vs solution IVsSolution solution = ServiceLocator.GetInstance<IVsSolution>(); int hr = solution.GetProjectOfUniqueName(project.GetUniqueName(), out hierarchy); if (hr != VsConstants.S_OK) { Marshal.ThrowExceptionForHR(hr); } return hierarchy; } public static IVsProjectBuildSystem ToVsProjectBuildSystem(this Project project) { if (project == null) { throw new ArgumentNullException("project"); } // Convert the project to an IVsHierarchy and see if it implements IVsProjectBuildSystem return project.ToVsHierarchy() as IVsProjectBuildSystem; } public static bool IsCompatible(this Project project, IPackage package) { if (package == null) { return true; } // if there is any file under content/lib which has no target framework, we consider the package // compatible with any project, because that file will be the fallback if no supported frameworks matches the project's. // REVIEW: what about install.ps1 and uninstall.ps1? if (package.HasFileWithNullTargetFramework()) { return true; } FrameworkName frameworkName = project.GetTargetFrameworkName(); // if the target framework cannot be determined the frameworkName becomes null (for example, for WiX projects). // indicate it as compatible, because we cannot determine that ourselves. Offer the capability to the end-user. if (frameworkName == null) { return true; } return VersionUtility.IsCompatible(frameworkName, package.GetSupportedFrameworks()); } public static string[] GetProjectTypeGuids(this Project project) { // Get the vs hierarchy as an IVsAggregatableProject to get the project type guids var hierarchy = project.ToVsHierarchy(); var aggregatableProject = hierarchy as IVsAggregatableProject; if (aggregatableProject != null) { string projectTypeGuids; int hr = aggregatableProject.GetAggregateProjectTypeGuids(out projectTypeGuids); if (hr != VsConstants.S_OK) { Marshal.ThrowExceptionForHR(hr); } return projectTypeGuids.Split(';'); } else if (!String.IsNullOrEmpty(project.Kind)) { return new[] { project.Kind }; } else { return new string[0]; } } internal static IList<Project> GetReferencedProjects(this Project project) { if (project.IsWebSite()) { return GetWebsiteReferencedProjects(project); } var projects = new List<Project>(); References references; try { references = project.Object.References; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) { //References property doesn't exist, project does not have references references = null; } if (references != null) { foreach (Reference reference in references) { // Get the referenced project from the reference if any if (reference.SourceProject != null) { projects.Add(reference.SourceProject); } } } return projects; } internal static HashSet<string> GetAssemblyClosure(this Project project, IFileSystemProvider projectFileSystemProvider, IDictionary<string, HashSet<string>> visitedProjects) { HashSet<string> assemblies; if (visitedProjects.TryGetValue(project.UniqueName, out assemblies)) { return assemblies; } assemblies = new HashSet<string>(PathComparer.Default); assemblies.AddRange(GetLocalProjectAssemblies(project, projectFileSystemProvider)); assemblies.AddRange(project.GetReferencedProjects().SelectMany(p => GetAssemblyClosure(p, projectFileSystemProvider, visitedProjects))); visitedProjects.Add(project.UniqueName, assemblies); return assemblies; } private static IList<Project> GetWebsiteReferencedProjects(Project project) { var projects = new List<Project>(); AssemblyReferences references = project.Object.References; foreach (AssemblyReference reference in references) { if (reference.ReferencedProject != null) { projects.Add(reference.ReferencedProject); } } return projects; } private static HashSet<string> GetLocalProjectAssemblies(Project project, IFileSystemProvider projectFileSystemProvider) { if (project.IsWebSite()) { return GetWebsiteLocalAssemblies(project, projectFileSystemProvider); } var assemblies = new HashSet<string>(PathComparer.Default); References references; try { references = project.Object.References; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) { //References property doesn't exist, project does not have references references = null; } if (references != null) { foreach (Reference reference in references) { // Get the referenced project from the reference if any if (reference.SourceProject == null && reference.CopyLocal && File.Exists(reference.Path)) { assemblies.Add(reference.Path); } } } return assemblies; } private static HashSet<string> GetWebsiteLocalAssemblies(Project project, IFileSystemProvider projectFileSystemProvider) { var assemblies = new HashSet<string>(PathComparer.Default); AssemblyReferences references = project.Object.References; foreach (AssemblyReference reference in references) { // For websites only include bin assemblies if (reference.ReferencedProject == null && reference.ReferenceKind == AssemblyReferenceType.AssemblyReferenceBin && File.Exists(reference.FullPath)) { assemblies.Add(reference.FullPath); } } // For website projects, we always add .refresh files that point to the corresponding binaries in packages. In the event of bin deployed assemblies that are also GACed, // the ReferenceKind is not AssemblyReferenceBin. Consequently, we work around this by looking for any additional assembly declarations specified via .refresh files. string projectPath = project.GetFullPath(); var fileSystem = projectFileSystemProvider.GetFileSystem(projectPath); assemblies.AddRange(fileSystem.ResolveRefreshPaths()); return assemblies; } public static MsBuildProject AsMSBuildProject(this Project project) { return ProjectCollection.GlobalProjectCollection.GetLoadedProjects(project.FullName).FirstOrDefault() ?? ProjectCollection.GlobalProjectCollection.LoadProject(project.FullName); } /// <summary> /// Returns the unique name of the specified project including all solution folder names containing it. /// </summary> /// <remarks> /// This is different from the DTE Project.UniqueName property, which is the absolute path to the project file. /// </remarks> public static string GetCustomUniqueName(this Project project) { if (project.IsWebSite()) { // website projects always have unique name return project.Name; } else { Stack<string> nameParts = new Stack<string>(); Project cursor = project; nameParts.Push(cursor.Name); // walk up till the solution root while (cursor.ParentProjectItem != null && cursor.ParentProjectItem.ContainingProject != null) { cursor = cursor.ParentProjectItem.ContainingProject; nameParts.Push(cursor.Name); } return String.Join("\\", nameParts); } } public static void AddImportStatement(this Project project, string targetsPath, ProjectImportLocation location) { AddImportStatement(project.AsMSBuildProject(), targetsPath, location); } public static void AddImportStatement(this MsBuildProject buildProject, string targetsPath, ProjectImportLocation location) { // adds an <Import> element to this project file if it doesn't already exist. if (buildProject.Xml.Imports == null || buildProject.Xml.Imports.All(import => !targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase))) { ProjectImportElement pie = buildProject.Xml.AddImport(targetsPath); pie.Condition = "Exists('" + targetsPath + "')"; if (location == ProjectImportLocation.Top) { // There's no public constructor to create a ProjectImportElement directly. // So we have to cheat by adding Import at the end, then remove it and insert at the beginning pie.Parent.RemoveChild(pie); buildProject.Xml.InsertBeforeChild(pie, buildProject.Xml.FirstChild); } buildProject.ReevaluateIfNecessary(); } } public static void RemoveImportStatement(this Project project, string targetsPath) { RemoveImportStatement(project.AsMSBuildProject(), targetsPath); } public static void RemoveImportStatement(this MsBuildProject buildProject, string targetsPath) { if (buildProject.Xml.Imports != null) { // search for this import statement and remove it var importElement = buildProject.Xml.Imports.FirstOrDefault( import => targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase)); if (importElement != null) { importElement.Parent.RemoveChild(importElement); buildProject.ReevaluateIfNecessary(); } } } // This method should only be called in VS 2012 or above [MethodImpl(MethodImplOptions.NoInlining)] public static void DoWorkInWriterLock(this Project project, Action<MsBuildProject> action) { IVsBrowseObjectContext context = project.Object as IVsBrowseObjectContext; if (context == null) { IVsHierarchy hierarchy = project.ToVsHierarchy(); context = hierarchy as IVsBrowseObjectContext; } if (context != null) { var service = context.UnconfiguredProject.ProjectService.Services.DirectAccessService; if (service != null) { // This has to run on Main thread, otherwise it will dead-lock (for C++ projects at least) ThreadHelper.Generic.Invoke(() => service.Write( context.UnconfiguredProject.FullPath, dwa => { MsBuildProject buildProject = dwa.GetProject(context.UnconfiguredProject.Services.SuggestedConfiguredProject); action(buildProject); }, ProjectAccess.Read | ProjectAccess.Write) ); } } } public static bool IsParentProjectExplicitlyUnsupported(this Project project) { if (project.ParentProjectItem == null || project.ParentProjectItem.ContainingProject == null) { // this project is not a child of another project return false; } Project parentProject = project.ParentProjectItem.ContainingProject; return parentProject.IsExplicitlyUnsupported(); } public static void EnsureCheckedOutIfExists(this Project project, IFileSystem fileSystem, string path) { var fullPath = fileSystem.GetFullPath(path); if (fileSystem.FileExists(path)) { fileSystem.MakeFileWritable(path); if (project.DTE.SourceControl != null && project.DTE.SourceControl.IsItemUnderSCC(fullPath) && !project.DTE.SourceControl.IsItemCheckedOut(fullPath)) { // Check out the item project.DTE.SourceControl.CheckOutItem(fullPath); } } } /// <summary> /// This method truncates Website projects into the VS-format, e.g. C:\..\WebSite1 /// This is used for displaying in the projects combo box. /// </summary> public static string GetDisplayName(this Project project, ISolutionManager solutionManager) { return GetDisplayName(project, solutionManager.GetProjectSafeName); } /// <summary> /// This method truncates Website projects into the VS-format, e.g. C:\..\WebSite1, but it uses Name instead of SafeName from Solution Manager. /// </summary> public static string GetDisplayName(this Project project) { return GetDisplayName(project, p => p.Name); } private static string GetDisplayName(this Project project, Func<Project, string> nameSelector) { string name = nameSelector(project); if (project.IsWebSite()) { name = PathHelper.SmartTruncate(name, 40); } return name; } private class PathComparer : IEqualityComparer<string> { public static readonly PathComparer Default = new PathComparer(); public bool Equals(string x, string y) { return Path.GetFileName(x).Equals(Path.GetFileName(y)); } public int GetHashCode(string obj) { return Path.GetFileName(obj).GetHashCode(); } } } }
// *********************************************************************** // Copyright (c) 2009-2015 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.Collections; using System.Collections.Generic; using System.Reflection; using System.Linq; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.TestData.TestCaseSourceAttributeFixture; using NUnit.TestUtilities; namespace NUnit.Framework.Attributes { [TestFixture] public class TestCaseSourceTests : TestSourceMayBeInherited { #region Tests With Static and Instance Members as Source [Test, TestCaseSource("StaticProperty")] public void SourceCanBeStaticProperty(string source) { Assert.AreEqual("StaticProperty", source); } [Test, TestCaseSource("InheritedStaticProperty")] public void TestSourceCanBeInheritedStaticProperty(bool source) { Assert.AreEqual(true, source); } static IEnumerable StaticProperty { get { return new object[] { new object[] { "StaticProperty" } }; } } [Test] public void SourceUsingInstancePropertyIsNotRunnable() { var result = TestBuilder.RunParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), "MethodWithInstancePropertyAsSource"); Assert.AreEqual(result.Children.ToArray()[0].ResultState, ResultState.NotRunnable); } [Test, TestCaseSource("StaticMethod")] public void SourceCanBeStaticMethod(string source) { Assert.AreEqual("StaticMethod", source); } static IEnumerable StaticMethod() { return new object[] { new object[] { "StaticMethod" } }; } [Test] public void SourceUsingInstanceMethodIsNotRunnable() { var result = TestBuilder.RunParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), "MethodWithInstanceMethodAsSource"); Assert.AreEqual(result.Children.ToArray()[0].ResultState, ResultState.NotRunnable); } IEnumerable InstanceMethod() { return new object[] { new object[] { "InstanceMethod" } }; } [Test, TestCaseSource("StaticField")] public void SourceCanBeStaticField(string source) { Assert.AreEqual("StaticField", source); } static object[] StaticField = { new object[] { "StaticField" } }; [Test] public void SourceUsingInstanceFieldIsNotRunnable() { var result = TestBuilder.RunParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), "MethodWithInstanceFieldAsSource"); Assert.AreEqual(result.Children.ToArray()[0].ResultState, ResultState.NotRunnable); } #endregion #region Test With IEnumerable Class as Source [Test, TestCaseSource(typeof(DataSourceClass))] public void SourceCanBeInstanceOfIEnumerable(string source) { Assert.AreEqual("DataSourceClass", source); } class DataSourceClass : IEnumerable { public DataSourceClass() { } public IEnumerator GetEnumerator() { yield return "DataSourceClass"; } } #endregion [Test, TestCaseSource("MyData")] public void SourceMayReturnArgumentsAsObjectArray(int n, int d, int q) { Assert.AreEqual(q, n / d); } [TestCaseSource("MyData")] public void TestAttributeIsOptional(int n, int d, int q) { Assert.AreEqual(q, n / d); } [Test, TestCaseSource("MyIntData")] public void SourceMayReturnArgumentsAsIntArray(int n, int d, int q) { Assert.AreEqual(q, n / d); } [Test, TestCaseSource("EvenNumbers")] public void SourceMayReturnSinglePrimitiveArgumentAlone(int n) { Assert.AreEqual(0, n % 2); } [Test, TestCaseSource("Params")] public int SourceMayReturnArgumentsAsParamSet(int n, int d) { return n / d; } [Test] [TestCaseSource("MyData")] [TestCaseSource("MoreData", Category = "Extra")] [TestCase(12, 2, 6)] public void TestMayUseMultipleSourceAttributes(int n, int d, int q) { Assert.AreEqual(q, n / d); } [Test, TestCaseSource("FourArgs")] public void TestWithFourArguments(int n, int d, int q, int r) { Assert.AreEqual(q, n / d); Assert.AreEqual(r, n % d); } [Test, Category("Top"), TestCaseSource(typeof(DivideDataProvider), "HereIsTheData")] public void SourceMayBeInAnotherClass(int n, int d, int q) { Assert.AreEqual(q, n / d); } [Test, Category("Top"), TestCaseSource(typeof(DivideDataProvider), "HereIsTheDataWithParameters", new object[] { 100, 4, 25 })] public void SourceInAnotherClassPassingSomeDataToConstructor(int n, int d, int q) { Assert.AreEqual(q, n / d); } [Test, Category("Top"), TestCaseSource("StaticMethodDataWithParameters", new object[] { 8000, 8, 1000 })] public void SourceCanBeStaticMethodPassingSomeDataToConstructor(int n, int d, int q) { Assert.AreEqual(q, n / d); } [Test] public void SourceInAnotherClassPassingParamsToField() { var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseSourceAttributeFixture), "SourceInAnotherClassPassingParamsToField").Tests[0]; Assert.AreEqual(RunState.NotRunnable, testMethod.RunState); ITestResult result = TestBuilder.RunTest(testMethod, null); Assert.AreEqual(ResultState.NotRunnable, result.ResultState); Assert.AreEqual("You have specified a data source field but also given a set of parameters. Fields cannot take parameters, " + "please revise the 3rd parameter passed to the TestCaseSourceAttribute and either remove " + "it or specify a method.", result.Message); } [Test] public void SourceInAnotherClassPassingParamsToProperty() { var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseSourceAttributeFixture), "SourceInAnotherClassPassingParamsToProperty").Tests[0]; Assert.AreEqual(RunState.NotRunnable, testMethod.RunState); ITestResult result = TestBuilder.RunTest(testMethod, null); Assert.AreEqual(ResultState.NotRunnable, result.ResultState); Assert.AreEqual("You have specified a data source property but also given a set of parameters. " + "Properties cannot take parameters, please revise the 3rd parameter passed to the " + "TestCaseSource attribute and either remove it or specify a method.", result.Message); } [Test] public void SourceInAnotherClassPassingSomeDataToConstructorWrongNumberParam() { var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseSourceAttributeFixture), "SourceInAnotherClassPassingSomeDataToConstructorWrongNumberParam").Tests[0]; Assert.AreEqual(RunState.NotRunnable, testMethod.RunState); ITestResult result = TestBuilder.RunTest(testMethod, null); Assert.AreEqual(ResultState.NotRunnable, result.ResultState); Assert.AreEqual("You have given the wrong number of arguments to the method in the TestCaseSourceAttribute" + ", please check the number of parameters passed in the object is correct in the 3rd parameter for the " + "TestCaseSourceAttribute and this matches the number of parameters in the target method and try again.", result.Message); } [Test, TestCaseSource(typeof(DivideDataProviderWithReturnValue), "TestCases")] public int SourceMayBeInAnotherClassWithReturn(int n, int d) { return n / d; } [Test] public void IgnoreTakesPrecedenceOverExpectedException() { var result = TestBuilder.RunParameterizedMethodSuite( typeof(TestCaseSourceAttributeFixture), "MethodCallsIgnore").Children.ToArray()[0]; Assert.AreEqual(ResultState.Ignored, result.ResultState); Assert.AreEqual("Ignore this", result.Message); } [Test] public void CanIgnoreIndividualTestCases() { TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseSourceAttributeFixture), "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)); Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Don't Run Me!")); } [Test] public void CanMarkIndividualTestCasesExplicit() { TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseSourceAttributeFixture), "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")); } [Test] public void HandlesExceptionInTestCaseSource() { var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseSourceAttributeFixture), "MethodWithSourceThrowingException").Tests[0]; Assert.AreEqual(RunState.NotRunnable, testMethod.RunState); ITestResult result = TestBuilder.RunTest(testMethod, null); Assert.AreEqual(ResultState.NotRunnable, result.ResultState); Assert.AreEqual("System.Exception : my message", result.Message); } [TestCaseSource("exception_source"), Explicit("Used for GUI tests")] public void HandlesExceptionInTestCaseSource_GuiDisplay(string lhs, string rhs) { Assert.AreEqual(lhs, rhs); } private static IEnumerable<TestCaseData> ZeroTestCasesSource() => Enumerable.Empty<TestCaseData>(); [TestCaseSource("ZeroTestCasesSource")] public void TestWithZeroTestSourceCasesShouldPassWithoutRequiringArguments(int requiredParameter) { } static object[] testCases = { new TestCaseData( new string[] { "A" }, new string[] { "B" }) }; [Test, TestCaseSource("testCases")] public void MethodTakingTwoStringArrays(string[] a, string[] b) { Assert.That(a, Is.TypeOf(typeof(string[]))); Assert.That(b, Is.TypeOf(typeof(string[]))); } [TestCaseSource("SingleMemberArrayAsArgument")] public void Issue1337SingleMemberArrayAsArgument(string[] args) { Assert.That(args.Length == 1 && args[0] == "1"); } static string[][] SingleMemberArrayAsArgument = { new[] { "1" } }; #region Sources used by the tests static object[] MyData = new object[] { new object[] { 12, 3, 4 }, new object[] { 12, 4, 3 }, new object[] { 12, 6, 2 } }; static object[] MyIntData = new object[] { new int[] { 12, 3, 4 }, new int[] { 12, 4, 3 }, new int[] { 12, 6, 2 } }; public static IEnumerable StaticMethodDataWithParameters(int inject1, int inject2, int inject3) { yield return new object[] { inject1, inject2, inject3 }; } static object[] FourArgs = new object[] { new TestCaseData( 12, 3, 4, 0 ), new TestCaseData( 12, 4, 3, 0 ), new TestCaseData( 12, 5, 2, 2 ) }; static int[] EvenNumbers = new int[] { 2, 4, 6, 8 }; static object[] MoreData = new object[] { new object[] { 12, 1, 12 }, new object[] { 12, 2, 6 } }; static object[] Params = new object[] { new TestCaseData(24, 3).Returns(8), new TestCaseData(24, 2).Returns(12) }; private class DivideDataProvider { #pragma warning disable 0169 // x is never assigned private static object[] myObject; #pragma warning restore 0169 public static IEnumerable HereIsTheDataWithParameters(int inject1, int inject2, int inject3) { yield return new object[] { inject1, inject2, inject3 }; } public static IEnumerable HereIsTheData { get { yield return new object[] { 100, 20, 5 }; yield return new object[] { 100, 4, 25 }; } } } public class DivideDataProviderWithReturnValue { public static IEnumerable TestCases { get { return new object[] { new TestCaseData(12, 3).Returns(4).SetName("TC1"), new TestCaseData(12, 2).Returns(6).SetName("TC2"), new TestCaseData(12, 4).Returns(3).SetName("TC3") }; } } } private static IEnumerable exception_source { get { yield return new TestCaseData("a", "a"); yield return new TestCaseData("b", "b"); throw new System.Exception("my message"); } } #endregion } public class TestSourceMayBeInherited { protected static IEnumerable<bool> InheritedStaticProperty { get { yield return true; } } } }
using System; using System.Collections.Generic; using System.Text; using UnityEngine.EventSystems; namespace UnityEngine.UI { [AddComponentMenu("Event/Graphic Raycaster")] [RequireComponent(typeof(Canvas))] public class GraphicRaycaster : BaseRaycaster { protected const int kNoEventMaskSet = -1; public enum BlockingObjects { None = 0, TwoD = 1, ThreeD = 2, All = 3, } public override int sortOrderPriority { get { // We need to return the sorting order here as distance will all be 0 for overlay. if (canvas.renderMode == RenderMode.ScreenSpaceOverlay) return canvas.sortingOrder; return base.sortOrderPriority; } } public override int renderOrderPriority { get { // We need to return the sorting order here as distance will all be 0 for overlay. if (canvas.renderMode == RenderMode.ScreenSpaceOverlay) return canvas.renderOrder; return base.renderOrderPriority; } } [SerializeField] private bool m_IgnoreReversedGraphics = true; [SerializeField] private BlockingObjects m_BlockingObjects = BlockingObjects.None; public bool ignoreReversedGraphics { get {return m_IgnoreReversedGraphics; } set{ m_IgnoreReversedGraphics = value; } } public BlockingObjects blockingObjects { get {return m_BlockingObjects; } set{ m_BlockingObjects = value; } } [SerializeField] protected LayerMask m_BlockingMask = kNoEventMaskSet; private Canvas m_Canvas; protected GraphicRaycaster() { } private Canvas canvas { get { if (m_Canvas != null) return m_Canvas; m_Canvas = GetComponent<Canvas>(); return m_Canvas; } } [NonSerialized] private List<Graphic> m_RaycastResults = new List<Graphic>(); public override void Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList) { if (canvas == null) return; // Convert to view space Vector2 pos; if (eventCamera == null) pos = new Vector2(eventData.position.x / Screen.width, eventData.position.y / Screen.height); else pos = eventCamera.ScreenToViewportPoint(eventData.position); // If it's outside the camera's viewport, do nothing if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f) return; float hitDistance = float.MaxValue; Ray ray = new Ray(); if (eventCamera != null) ray = eventCamera.ScreenPointToRay(eventData.position); if (canvas.renderMode != RenderMode.ScreenSpaceOverlay && blockingObjects != BlockingObjects.None) { float dist = eventCamera.farClipPlane - eventCamera.nearClipPlane; if (blockingObjects == BlockingObjects.ThreeD || blockingObjects == BlockingObjects.All) { RaycastHit hit; if (Physics.Raycast(ray, out hit, dist, m_BlockingMask)) { hitDistance = hit.distance; } } if (blockingObjects == BlockingObjects.TwoD || blockingObjects == BlockingObjects.All) { RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, dist, m_BlockingMask); if (hit.collider != null) { hitDistance = hit.fraction * dist; } } } m_RaycastResults.Clear(); Raycast(canvas, eventCamera, eventData.position, m_RaycastResults); for (var index = 0; index < m_RaycastResults.Count; index++) { var go = m_RaycastResults[index].gameObject; bool appendGraphic = true; if (ignoreReversedGraphics) { if (eventCamera == null) { // If we dont have a camera we know that we should always be facing forward var dir = go.transform.rotation * Vector3.forward; appendGraphic = Vector3.Dot(Vector3.forward, dir) > 0; } else { // If we have a camera compare the direction against the cameras forward. var cameraFoward = eventCamera.transform.rotation * Vector3.forward; var dir = go.transform.rotation * Vector3.forward; appendGraphic = Vector3.Dot(cameraFoward, dir) > 0; } } if (appendGraphic) { float distance = 0; if (eventCamera == null || canvas.renderMode == RenderMode.ScreenSpaceOverlay) distance = 0; else { // http://geomalgorithms.com/a06-_intersect-2.html distance = (Vector3.Dot(go.transform.forward, go.transform.position - ray.origin) / Vector3.Dot(go.transform.forward, ray.direction)); // Check to see if the go is behind the camera. if (distance < 0) continue; } if (distance >= hitDistance) continue; var castResult = new RaycastResult { gameObject = go, module = this, distance = distance, index = resultAppendList.Count, depth = m_RaycastResults[index].depth, sortingLayer = canvas.sortingLayerID, sortingOrder = canvas.sortingOrder }; resultAppendList.Add(castResult); } } } public override Camera eventCamera { get { if (canvas.renderMode == RenderMode.ScreenSpaceOverlay || (canvas.renderMode == RenderMode.ScreenSpaceCamera && canvas.worldCamera == null)) return null; return canvas.worldCamera != null ? canvas.worldCamera : Camera.main; } } /// <summary> /// Perform a raycast into the screen and collect all graphics underneath it. /// </summary> [NonSerialized] static readonly List<Graphic> s_SortedGraphics = new List<Graphic>(); private static void Raycast(Canvas canvas, Camera eventCamera, Vector2 pointerPosition, List<Graphic> results) { // Debug.Log("ttt" + pointerPoision + ":::" + camera); // Necessary for the event system var foundGraphics = GraphicRegistry.GetGraphicsForCanvas(canvas); s_SortedGraphics.Clear(); for (int i = 0; i < foundGraphics.Count; ++i) { Graphic graphic = foundGraphics[i]; // -1 means it hasn't been processed by the canvas, which means it isn't actually drawn if (graphic.depth == -1) continue; if (!RectTransformUtility.RectangleContainsScreenPoint(graphic.rectTransform, pointerPosition, eventCamera)) continue; if (graphic.Raycast(pointerPosition, eventCamera)) { s_SortedGraphics.Add(graphic); } } s_SortedGraphics.Sort((g1, g2) => g2.depth.CompareTo(g1.depth)); // StringBuilder cast = new StringBuilder(); for (int i = 0; i < s_SortedGraphics.Count; ++i) results.Add(s_SortedGraphics[i]); // Debug.Log (cast.ToString()); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; namespace Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdprfx { /// <summary> /// The RemoteeFX decoder. /// </summary> public class RemoteFXDecoder { protected const int DWT_PREC = 4; protected const int TileSize = 64; #region public methods /// <summary> /// Decode the tile data /// </summary> /// <param name="codecContext">The decoding context</param> /// <param name="yData">The Y data to be decoded.</param> /// <param name="cbData">The Cb data to be decoded.</param> /// <param name="crData">The Cr data to be decoded.</param> public static void DecodeTile(RemoteFXCodecContext codecContext, byte[] yData, byte[] cbData, byte[] crData) { //Load the encoded tile data FileEncodedData(codecContext, yData, cbData, crData); //Do ALGR decode RLGRDecode(codecContext); //Do reconstruction SubBandReconstruction(codecContext); //Dequantization Dequantization(codecContext); //Inverse DWT InverseDWT(codecContext); //Color coversion YCbCrToRGB(codecContext); } //Load encoded data into decoding context public static void FileEncodedData(RemoteFXCodecContext codecContext, byte[] yData, byte[] cbData, byte[] crData) { codecContext.YData = new byte[yData.Length]; codecContext.CbData = new byte[cbData.Length]; codecContext.CrData = new byte[crData.Length]; Array.Copy(yData, codecContext.YData, yData.Length); Array.Copy(cbData, codecContext.CbData, cbData.Length); Array.Copy(crData, codecContext.CrData, crData.Length); } //RLGR decode public static void RLGRDecode(RemoteFXCodecContext codecContext) { RLGRDecoder decoder = new RLGRDecoder(); int comLen = TileSize * TileSize; codecContext.YComponent = decoder.Decode(codecContext.YData, codecContext.Mode, comLen); codecContext.CbComponent = decoder.Decode(codecContext.CbData, codecContext.Mode, comLen); codecContext.CrComponent = decoder.Decode(codecContext.CrData, codecContext.Mode, comLen); } //Sub-Band Reconstruction public static void SubBandReconstruction(RemoteFXCodecContext codecContext) { reconstruction_Component(codecContext.YComponent, out codecContext.YSet); reconstruction_Component(codecContext.CbComponent, out codecContext.CbSet); reconstruction_Component(codecContext.CrComponent, out codecContext.CrSet); } //Dequantization public static void Dequantization(RemoteFXCodecContext codecContext) { dequantization_Component(codecContext.YSet, codecContext.CodecQuantVals[codecContext.QuantIdxY]); dequantization_Component(codecContext.CbSet, codecContext.CodecQuantVals[codecContext.QuantIdxCb]); dequantization_Component(codecContext.CrSet, codecContext.CodecQuantVals[codecContext.QuantIdxCr]); } //InverseDWT public static void InverseDWT(RemoteFXCodecContext codecContext) { InverseDWT_Component(codecContext.YSet); InverseDWT_Component(codecContext.CbSet); InverseDWT_Component(codecContext.CrSet); } //YCbCrToRGB public static void YCbCrToRGB(RemoteFXCodecContext codecContext) { YCbCrToRGB(codecContext.YSet, codecContext.CbSet, codecContext.CrSet, out codecContext.RSet, out codecContext.GSet, out codecContext.BSet); } public static void getColFrom2DArr<T>(T[,] input2D, out T[] output1D, int xIdx, int len) { output1D = new T[len]; for (int i = 0; i < len; i++) { output1D[i] = input2D[xIdx, i]; } } public static void getRowFrom2DArr<T>(T[,] input2D, out T[] output1D, int yIdx, int len) { output1D = new T[len]; for (int i = 0; i < len; i++) { output1D[i] = input2D[i, yIdx]; } } #endregion #region Private Methods protected static void reconstruction_Component(short[] component1D, out short[,] compontent2D) { //sequence: HL1, LH1, HH1, HL2, LH2, HH2, HL3, LH3, HH3, and LL3 //lineOutput = new short[TileSize * TileSize]; compontent2D = new short[TileSize, TileSize]; int top, left, right, bottom; int offset = 0; for (int i = 0; i <= 2; i++) { int levelSize = TileSize >> i; //HL top = 0; left = levelSize / 2; right = levelSize - 1; bottom = levelSize / 2 - 1; reconstruction_SubBand(compontent2D, left, top, right, bottom, component1D, ref offset); //LH top = levelSize / 2; left = 0; right = levelSize / 2 - 1; bottom = levelSize - 1; reconstruction_SubBand(compontent2D, left, top, right, bottom, component1D, ref offset); //HH top = levelSize / 2; left = levelSize / 2; right = levelSize - 1; bottom = levelSize - 1; reconstruction_SubBand(compontent2D, left, top, right, bottom, component1D, ref offset); } //LL top = 0; left = 0; right = TileSize / 8 - 1; bottom = TileSize / 8 - 1; int llLen = (right - left + 1) * (bottom - top + 1); short[] llBand = new short[llLen]; Array.Copy(component1D, offset, llBand, 0, llLen); for (int i = 1; i < llLen; i++) { llBand[i] = (short)(llBand[i - 1] + llBand[i]); } int llOffset = 0; reconstruction_SubBand(compontent2D, left, top, right, bottom, llBand, ref llOffset); } private static void reconstruction_SubBand(short[,] input, int left, int top, int right, int bottom, short[] bandOutput, ref int offset) { //int totalNum = (right - left + 1) * (bottom - top + 1); //bandOutput = new short[totalNum]; for (int y = top; y <= bottom; y++) { for (int x = left; x <= right; x++) { input[x, y] = bandOutput[offset++]; } } } protected static void dequantization_Component(short[,] compontent, TS_RFX_CODEC_QUANT tsRfxCodecQuant) { // Quantization factor: HL1, LH1, HH1, HL2, LH2, HH2, HL3, LH3, HH3, LL3 Hashtable scaleValueTable = new Hashtable(); int HL1_Factor = tsRfxCodecQuant.HL1_HH1 & 0x0f; int LH1_Factor = (tsRfxCodecQuant.HH2_LH1 & 0xf0) >> 4; int HH1_Factor = (tsRfxCodecQuant.HL1_HH1 & 0xf0) >> 4; int HL2_Factor = (tsRfxCodecQuant.LH2_HL2 & 0xf0) >> 4; int LH2_Factor = tsRfxCodecQuant.LH2_HL2 & 0x0f; int HH2_Factor = tsRfxCodecQuant.HH2_LH1 & 0x0f; int HL3_Factor = tsRfxCodecQuant.HL3_HH3 & 0x0f; int LH3_Factor = (tsRfxCodecQuant.LL3_LH3 & 0xf0) >> 4; int HH3_Factor = (tsRfxCodecQuant.HL3_HH3 & 0xf0) >> 4; int LL3_Factor = tsRfxCodecQuant.LL3_LH3 & 0x0f; int[] HL_Factor = { HL1_Factor, HL2_Factor, HL3_Factor }; int[] LH_Factor = { LH1_Factor, LH2_Factor, LH3_Factor }; int[] HH_Factor = { HH1_Factor, HH2_Factor, HH3_Factor }; int top, left, right, bottom; //Level 1, 2, 3 for (int i = 0; i <= 2; i++) { int levelSize = TileSize >> i; //HL1,2,3 top = 0; left = levelSize / 2; right = levelSize - 1; bottom = levelSize / 2 - 1; doDequantization_Subband(compontent, left, top, right, bottom, HL_Factor[i]); //LH1,2,3 top = levelSize / 2; left = 0; right = levelSize / 2 - 1; bottom = levelSize - 1; doDequantization_Subband(compontent, left, top, right, bottom, LH_Factor[i]); //HH1,2,3 top = levelSize / 2; left = levelSize / 2; right = levelSize - 1; bottom = levelSize - 1; doDequantization_Subband(compontent, left, top, right, bottom, HH_Factor[i]); } //LL3 top = 0; left = 0; right = TileSize / 8 - 1; bottom = TileSize / 8 - 1; doDequantization_Subband(compontent, left, top, right, bottom, LL3_Factor); } private static void doDequantization_Subband(short[,] input, int left, int top, int right, int bottom, int factor) { for (int x = left; x <= right; x++) { for (int y = top; y <= bottom; y++) { input[x, y] = (short)(input[x, y] << (factor - 6));//<< DWT_PREC); } } } protected static void InverseDWT_Component(short[,] component) { //Level 3, 2, 1 InverseDWT_2D(component, 3); InverseDWT_2D(component, 2); InverseDWT_2D(component, 1); } private static void InverseDWT_2D(short[,] data2D, int level) { //level > 0 //data2D.Length % (1<<(level - 1)) == 0 int inScopelen = TileSize >> (level - 1); //Horizontal DWT for (int y = 0; y < inScopelen; y++) { short[] row; getRowFrom2DArr<short>(data2D, out row, y, inScopelen); row = InverseDWT_1D(row); for (int x = 0; x < inScopelen; x++) { data2D[x, y] = row[x]; } } //Vertical DWT for (int x = 0; x < inScopelen; x++) { short[] col; getColFrom2DArr<short>(data2D, out col, x, inScopelen); col = InverseDWT_1D(col); for (int y = 0; y < inScopelen; y++) { data2D[x, y] = col[y]; } } } private static short[] InverseDWT_1D(short[] encodedData) { int hOffset = encodedData.Length / 2; short[] decodedData = new short[encodedData.Length]; for (int i = 1; 2 * i < encodedData.Length; i++) { //X[2n] = L[n] - (H[n-1] + H[n] + 1) / 2 decodedData[2 * i] = (short)Math.Round(encodedData[i] - (encodedData[hOffset + i - 1] + encodedData[hOffset + i] + 1.0f) / 2); } for (int i = 1; 2 * i + 2 < encodedData.Length; i++) { //X[2n + 1] = 2*H[n] + (X[2n] + X[2n + 2])/2 decodedData[2 * i + 1] = (short)Math.Round(2 * encodedData[hOffset + i] + (decodedData[2 * i] + decodedData[2 * i + 2] + 0.0f) / 2); } //Handle X[0], [1], [len-1] //H(-1) = H[0] decodedData[0] = (short)Math.Round(encodedData[0] - (encodedData[hOffset] + encodedData[hOffset] + 1.0f) / 2); decodedData[1] = (short)Math.Round(2 * encodedData[hOffset] + (decodedData[0] + decodedData[2] + 0.0f) / 2); decodedData[decodedData.Length - 1] = (short)(2 * encodedData[hOffset + hOffset - 1] + decodedData[decodedData.Length - 2]); return decodedData; } protected static void YCbCrToRGB(short[,] ySet, short[,] cbSet, short[,] crSet, out byte[,] rSet, out byte[,] gSet, out byte[,] bSet) { rSet = new byte[TileSize, TileSize]; gSet = new byte[TileSize, TileSize]; bSet = new byte[TileSize, TileSize]; for (int x = 0; x < TileSize; x++) { for (int y = 0; y < TileSize; y++) { byte[] rgb = yuvToRGB(ySet[x, y], cbSet[x, y], crSet[x, y]); rSet[x, y] = rgb[0]; gSet[x, y] = rgb[1]; bSet[x, y] = rgb[2]; } } } private static byte[] yuvToRGB(short y, short cb, short cr) { byte[] rgb = new byte[3]; double yF = (y + 128.0f); double cbF = cb; double crF = cr; short r = (short)Math.Round((yF * 1.0 + cbF * 0 + crF * 1.403)); //R short g = (short)Math.Round((yF * 1.0 + cbF * (-0.344) + crF * (-0.714))); short b = (short)Math.Round((yF * 1.0 + cbF * 1.77 + crF * 0.0)); if (r > 255) r = 255; if (r < 0) r = 0; if (g > 255) g = 255; if (g < 0) g = 0; if (b > 255) b = 255; if (b < 0) b = 0; rgb[0] = (byte)r; rgb[1] = (byte)g; rgb[2] = (byte)b; return rgb; } #endregion } }
using System; using System.Collections.Generic; using System.IO; using Moq; using NuGet.Test.Mocks; using Xunit; using System.Runtime.Versioning; namespace NuGet.Test { public class PackageManagerTest { [Fact] public void CtorThrowsIfDependenciesAreNull() { // Act & Assert ExceptionAssert.ThrowsArgNull(() => new PackageManager(null, new DefaultPackagePathResolver("foo"), new MockProjectSystem(), new MockPackageRepository()), "sourceRepository"); ExceptionAssert.ThrowsArgNull(() => new PackageManager(new MockPackageRepository(), null, new MockProjectSystem(), new MockPackageRepository()), "pathResolver"); ExceptionAssert.ThrowsArgNull(() => new PackageManager(new MockPackageRepository(), new DefaultPackagePathResolver("foo"), null, new MockPackageRepository()), "fileSystem"); ExceptionAssert.ThrowsArgNull(() => new PackageManager(new MockPackageRepository(), new DefaultPackagePathResolver("foo"), new MockProjectSystem(), null), "localRepository"); } [Fact] public void InstallingPackageWithUnknownDependencyAndIgnoreDepencenciesInstallsPackageWithoutDependencies() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("C") }); IPackage packageC = PackageUtility.CreatePackage("C", "1.0"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageC); // Act packageManager.InstallPackage("A", version: null, ignoreDependencies: true, allowPrereleaseVersions: true); // Assert Assert.True(localRepository.Exists(packageA)); Assert.False(localRepository.Exists(packageC)); } [Fact] public void UninstallingUnknownPackageThrows() { // Arrange PackageManager packageManager = CreatePackageManager(); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => packageManager.UninstallPackage("foo"), "Unable to find package 'foo'."); } [Fact] public void UninstallingUnknownNullOrEmptyPackageIdThrows() { // Arrange PackageManager packageManager = CreatePackageManager(); // Act & Assert ExceptionAssert.ThrowsArgNullOrEmpty(() => packageManager.UninstallPackage((string)null), "packageId"); ExceptionAssert.ThrowsArgNullOrEmpty(() => packageManager.UninstallPackage(String.Empty), "packageId"); } [Fact] public void UninstallingPackageWithNoDependents() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); var package = PackageUtility.CreatePackage("foo", "1.2.33"); localRepository.AddPackage(package); // Act packageManager.UninstallPackage("foo"); // Assert Assert.False(packageManager.LocalRepository.Exists(package)); } [Fact] public void InstallingUnknownPackageThrows() { // Arrange PackageManager packageManager = CreatePackageManager(); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => packageManager.InstallPackage("unknown"), "Unable to find package 'unknown'."); } [Fact] public void InstallPackageNullOrEmptyPackageIdThrows() { // Arrange PackageManager packageManager = CreatePackageManager(); // Act & Assert ExceptionAssert.ThrowsArgNullOrEmpty(() => packageManager.InstallPackage((string)null), "packageId"); ExceptionAssert.ThrowsArgNullOrEmpty(() => packageManager.InstallPackage(String.Empty), "packageId"); } [Fact] public void InstallPackageAddsAllFilesToFileSystem() { // Arrange var projectSystem = new MockProjectSystem(); var sourceRepository = new MockPackageRepository(); var pathResolver = new DefaultPackagePathResolver(projectSystem); var packageManager = new PackageManager(sourceRepository, pathResolver, projectSystem, new LocalPackageRepository(pathResolver, projectSystem)); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", new[] { "contentFile", @"sub\contentFile" }, new[] { @"lib\reference.dll" }, new[] { @"readme.txt" }); sourceRepository.AddPackage(packageA); // Act packageManager.InstallPackage("A"); // Assert Assert.Equal(0, projectSystem.References.Count); Assert.Equal(5, projectSystem.Paths.Count); Assert.True(projectSystem.FileExists(@"A.1.0\content\contentFile")); Assert.True(projectSystem.FileExists(@"A.1.0\content\sub\contentFile")); Assert.True(projectSystem.FileExists(@"A.1.0\lib\reference.dll")); Assert.True(projectSystem.FileExists(@"A.1.0\tools\readme.txt")); Assert.True(projectSystem.FileExists(@"A.1.0\A.1.0.nupkg")); } [Fact] public void InstallingSatellitePackageCopiesFilesIntoRuntimePackageFolderWhenRuntimeIsInstalledAsADependency() { // Arrange // Create a runtime package and a satellite package that has a dependency on the runtime package, and uses the // local suffix convention. var runtimePackage = PackageUtility.CreatePackage("foo", "1.0.0", assemblyReferences: new[] { @"lib\foo.dll" }); var satellitePackage = PackageUtility.CreatePackage("foo.ja-jp", "1.0.0", language: "ja-jp", satelliteAssemblies: new[] { @"lib\ja-jp\foo.resources.dll", @"lib\ja-jp\foo.xml" }, dependencies: new[] { new PackageDependency("foo") }); var projectSystem = new MockProjectSystem(); var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); sourceRepository.AddPackage(runtimePackage); sourceRepository.AddPackage(satellitePackage); // Act packageManager.InstallPackage("foo.ja-jp"); // Assert Assert.Equal(5, projectSystem.Paths.Count); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\foo.dll")); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\ja-jp\foo.resources.dll")); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\ja-jp\foo.xml")); Assert.True(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\ja-jp\foo.resources.dll")); Assert.True(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\ja-jp\foo.xml")); } [Fact] public void InstallingSatellitePackageCopiesFilesIntoRuntimePackageFolderWhenRuntimeIsAlreadyInstalled() { // Arrange // Create a runtime package and a satellite package that has a dependency on the runtime package, and uses the // local suffix convention. var runtimePackage = PackageUtility.CreatePackage("foo", "1.0.0", assemblyReferences: new[] { @"lib\foo.dll" }); var satellitePackage = PackageUtility.CreatePackage("foo.ja-jp", "1.0.0", language: "ja-jp", satelliteAssemblies: new[] { @"lib\ja-jp\foo.resources.dll", @"lib\ja-jp\foo.xml" }, dependencies: new[] { new PackageDependency("foo") }); var projectSystem = new MockProjectSystem(); var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); sourceRepository.AddPackage(runtimePackage); sourceRepository.AddPackage(satellitePackage); // Act packageManager.InstallPackage("foo"); packageManager.InstallPackage("foo.ja-jp"); // Assert Assert.Equal(5, projectSystem.Paths.Count); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\foo.dll")); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\ja-jp\foo.resources.dll")); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\ja-jp\foo.xml")); Assert.True(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\ja-jp\foo.resources.dll")); Assert.True(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\ja-jp\foo.xml")); } [Fact] public void InstallingSatellitePackageOnlyCopiesCultureSpecificLibFolderContents() { // Arrange // Create a runtime package and a satellite package that has a dependency on the runtime package, and uses the // local suffix convention. var runtimePackage = PackageUtility.CreatePackage("foo", "1.0.0", assemblyReferences: new[] { @"lib\foo.dll" }, content: new[] { @"english.txt" }); var satellitePackage = PackageUtility.CreatePackage("foo.ja-jp", "1.0.0", language: "ja-jp", satelliteAssemblies: new[] { @"lib\ja-jp\foo.resources.dll", @"lib\ja-jp\foo.xml", @"lib\japanese.xml" }, content: new[] { @"english.txt", @"japanese.txt" }, dependencies: new[] { new PackageDependency("foo") }); var projectSystem = new MockProjectSystem(); var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); sourceRepository.AddPackage(runtimePackage); sourceRepository.AddPackage(satellitePackage); // Act packageManager.InstallPackage("foo"); packageManager.InstallPackage("foo.ja-jp"); // Assert Assert.Equal(9, projectSystem.Paths.Count); Assert.True(projectSystem.FileExists(@"foo.1.0.0\content\english.txt")); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\foo.dll")); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\ja-jp\foo.resources.dll")); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\ja-jp\foo.xml")); Assert.True(projectSystem.FileExists(@"foo.ja-jp.1.0.0\content\english.txt")); Assert.True(projectSystem.FileExists(@"foo.ja-jp.1.0.0\content\japanese.txt")); Assert.True(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\japanese.xml")); Assert.True(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\ja-jp\foo.resources.dll")); Assert.True(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\ja-jp\foo.xml")); Assert.False(projectSystem.FileExists(@"foo.1.0.0\lib\japanese.xml")); Assert.False(projectSystem.FileExists(@"foo.1.0.0\content\japanese.txt")); } [Fact] public void UninstallingSatellitePackageRemovesFilesFromRuntimePackageFolder() { // Arrange // Create a runtime package and a satellite package that has a dependency on the runtime package, and uses the // local suffix convention. var runtimePackage = PackageUtility.CreatePackage("foo", "1.0.0", assemblyReferences: new[] { @"lib\foo.dll" }, content: new[] { @"english.txt" }); var satellitePackage = PackageUtility.CreatePackage("foo.ja-jp", "1.0.0", language: "ja-jp", satelliteAssemblies: new[] { @"lib\ja-jp\foo.resources.dll", @"lib\ja-jp\foo.xml", @"lib\japanese.xml" }, content: new[] { @"english.txt", @"japanese.txt" }, dependencies: new[] { new PackageDependency("foo") }); var projectSystem = new MockProjectSystem(); var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); sourceRepository.AddPackage(runtimePackage); sourceRepository.AddPackage(satellitePackage); // Act packageManager.InstallPackage("foo"); packageManager.InstallPackage("foo.ja-jp"); packageManager.UninstallPackage("foo.ja-jp"); // Assert Assert.Equal(2, projectSystem.Paths.Count); Assert.True(projectSystem.FileExists(@"foo.1.0.0\content\english.txt")); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\foo.dll")); Assert.False(projectSystem.FileExists(@"foo.1.0.0\lib\ja-jp\foo.resources.dll")); Assert.False(projectSystem.FileExists(@"foo.1.0.0\lib\ja-jp\foo.xml")); Assert.False(projectSystem.FileExists(@"foo.ja-jp.1.0.0\content\english.txt")); Assert.False (projectSystem.FileExists(@"foo.ja-jp.1.0.0\content\japanese.txt")); Assert.False(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\japanese.xml")); Assert.False(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\ja-jp\foo.resources.dll")); Assert.False(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\ja-jp\foo.xml")); Assert.False(projectSystem.FileExists(@"foo.1.0.0\lib\japanese.xml")); Assert.False(projectSystem.FileExists(@"foo.1.0.0\content\japanese.txt")); } /// <summary> /// This test demonstrates that satellite packages that have satellite files /// that match the files in the runtime package can cause the runtime package's /// file to be removed when the satellite package is uninstalled. /// </summary> /// <remarks> /// This is an acceptable limitation of the design: during uninstallation of the satellite package, /// we don't check the runtime package to see if files qualified as satellite files /// already existed in the runtime package. /// <para> /// And as the uninstall.ps1 end-to-end tests demonstrate, the only way this collision can cause the /// runtime package's file to be removed is when the files are exact matches of one another. Otherwise, /// the file will be recognized as different, and it won't be uninstalled when uninstalling ja-jp. /// </para> /// </remarks> [Fact] public void UninstallingSatellitePackageRemovesCollidingRuntimeFiles() { // Arrange // Create a runtime package and a satellite package that has a dependency on the runtime package, and uses the // local suffix convention. var runtimePackage = PackageUtility.CreatePackage("foo", "1.0.0", assemblyReferences: new[] { @"lib\ja-jp\collision.txt" }); var satellitePackage = PackageUtility.CreatePackage("foo.ja-jp", "1.0.0", language: "ja-jp", satelliteAssemblies: new[] { @"lib\ja-jp\collision.txt" }, dependencies: new[] { new PackageDependency("foo") }); var projectSystem = new MockProjectSystem(); var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); sourceRepository.AddPackage(runtimePackage); sourceRepository.AddPackage(satellitePackage); // Act packageManager.InstallPackage("foo"); packageManager.InstallPackage("foo.ja-jp"); packageManager.UninstallPackage("foo.ja-jp"); // Assert Assert.Equal(0, projectSystem.Paths.Count); Assert.False(projectSystem.FileExists(@"foo.1.0.0\lib\ja-jp\collision.txt")); } [Fact] public void UninstallingPackageUninstallsPackageButNotDependencies() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); // Act packageManager.UninstallPackage("A"); // Assert Assert.False(localRepository.Exists(packageA)); Assert.True(localRepository.Exists(packageB)); } [Fact] public void ReInstallingPackageAfterUninstallingDependencyShouldReinstallAllDependencies() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); PackageManager packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("C") }); var packageC = PackageUtility.CreatePackage("C", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); sourceRepository.AddPackage(packageC); // Act packageManager.InstallPackage("A"); // Assert Assert.True(localRepository.Exists(packageA)); Assert.True(localRepository.Exists(packageB)); Assert.True(localRepository.Exists(packageC)); } [Fact] public void InstallPackageThrowsExceptionPackageIsNotInstalled() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new Mock<IProjectSystem>(); projectSystem.Setup(m => m.AddFile(@"A.1.0\content\file", It.IsAny<Stream>())).Throws<UnauthorizedAccessException>(); projectSystem.Setup(m => m.Root).Returns("FakeRoot"); PackageManager packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem.Object), projectSystem.Object, localRepository); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", new[] { "file" }); sourceRepository.AddPackage(packageA); // Act ExceptionAssert.Throws<UnauthorizedAccessException>(() => packageManager.InstallPackage("A")); // Assert Assert.False(packageManager.LocalRepository.Exists(packageA)); } [Fact] public void UpdatePackageUninstallsPackageAndInstallsNewPackage() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); PackageManager packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage A10 = PackageUtility.CreatePackage("A", "1.0"); IPackage A20 = PackageUtility.CreatePackage("A", "2.0"); localRepository.Add(A10); sourceRepository.Add(A20); // Act packageManager.UpdatePackage("A", updateDependencies: true, allowPrereleaseVersions: false); // Assert Assert.False(localRepository.Exists("A", new SemanticVersion("1.0"))); Assert.True(localRepository.Exists("A", new SemanticVersion("2.0"))); } [Fact] public void UpdatePackageThrowsIfPackageNotInstalled() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); PackageManager packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage A20 = PackageUtility.CreatePackage("A", "2.0"); sourceRepository.Add(A20); // Act ExceptionAssert.Throws<InvalidOperationException>(() => packageManager.UpdatePackage("A", updateDependencies: true, allowPrereleaseVersions: false), "Unable to find package 'A'."); } [Fact] public void UpdatePackageDoesNothingIfNoUpdatesAvailable() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); PackageManager packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage A10 = PackageUtility.CreatePackage("A", "1.0"); localRepository.Add(A10); // Act packageManager.UpdatePackage("A", updateDependencies: true, allowPrereleaseVersions: false); // Assert Assert.True(localRepository.Exists("A", new SemanticVersion("1.0"))); } [Fact] public void InstallPackageInstallsPrereleasePackages() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage packageA = PackageUtility.CreatePackage("A", "1.0.0-beta", dependencies: new[] { new PackageDependency("C") }); IPackage packageC = PackageUtility.CreatePackage("C", "1.0.0"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageC); // Act packageManager.InstallPackage("A", version: null, ignoreDependencies: false, allowPrereleaseVersions: true); // Assert Assert.True(localRepository.Exists(packageA)); Assert.True(localRepository.Exists(packageC)); } [Fact] public void InstallPackageInstallsPackagesWithPrereleaseDependenciesIfFlagIsSet() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage packageA = PackageUtility.CreatePackage("A", "1.0.0", dependencies: new[] { new PackageDependency("C") }); IPackage packageC = PackageUtility.CreatePackage("C", "1.0.0-RC-1"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageC); // Act packageManager.InstallPackage("A", version: null, ignoreDependencies: false, allowPrereleaseVersions: true); // Assert Assert.True(localRepository.Exists(packageA)); Assert.True(localRepository.Exists(packageC)); } [Fact] public void InstallPackageThrowsIfDependencyIsPrereleaseAndFlagIsNotSet() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage packageA = PackageUtility.CreatePackage("A", "1.0.0", dependencies: new[] { new PackageDependency("C") }); IPackage packageC = PackageUtility.CreatePackage("C", "1.0.0-RC-1"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageC); // Act and Assert ExceptionAssert.Throws<InvalidOperationException>( () => packageManager.InstallPackage("A", version: null, ignoreDependencies: false, allowPrereleaseVersions: false), "Unable to resolve dependency 'C'."); } [Fact] public void InstallPackageInstallsLowerReleaseVersionIfPrereleaseFlagIsNotSet() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage packageA = PackageUtility.CreatePackage("A", "1.0.0", dependencies: new[] { new PackageDependency("C") }); IPackage packageC_RC = PackageUtility.CreatePackage("C", "1.0.0-RC-1"); IPackage packageC = PackageUtility.CreatePackage("C", "0.9"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageC); sourceRepository.AddPackage(packageC_RC); // Act packageManager.InstallPackage("A", version: null, ignoreDependencies: false, allowPrereleaseVersions: false); // Assert Assert.True(localRepository.Exists(packageA)); Assert.True(localRepository.Exists(packageC)); } [Fact] public void InstallPackageConsidersAlreadyInstalledPrereleasePackagesWhenResolvingDependencies() { // Arrange var packageB_05 = PackageUtility.CreatePackage("B", "0.5.0"); var packageB_10a = PackageUtility.CreatePackage("B", "1.0.0-a"); var packageA = PackageUtility.CreatePackage("A", dependencies: new[] { new PackageDependency("B", VersionUtility.ParseVersionSpec("[0.5.0, 2.0.0)")) }); var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB_10a); sourceRepository.AddPackage(packageB_05); // Act // The allowPrereleaseVersions flag should be irrelevant since we specify a version. packageManager.InstallPackage("B", version: new SemanticVersion("1.0.0-a"), ignoreDependencies: false, allowPrereleaseVersions: false); // Verify we actually did install B.1.0.0a Assert.True(localRepository.Exists(packageB_10a)); packageManager.InstallPackage("A"); // Assert Assert.True(localRepository.Exists(packageA)); Assert.True(localRepository.Exists(packageB_10a)); } [Fact] public void InstallPackageNotifiesBatchProcessorWhenExpandingPackageFiles() { // Arrange var package = PackageUtility.CreatePackage("B", "0.5.0", content: new[] { "content.txt" }, assemblyReferences: new[] { "Ref.dll" }); var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var fileSystem = new Mock<MockFileSystem> { CallBase = true }; var batchProcessor = fileSystem.As<IBatchProcessor<string>>(); batchProcessor.Setup(s => s.BeginProcessing(It.IsAny<IEnumerable<string>>(), PackageAction.Install)) .Callback((IEnumerable<string> files, PackageAction _) => Assert.Equal(new[] { @"content\content.txt", "Ref.dll" }, files)) .Verifiable(); batchProcessor.Setup(s => s.EndProcessing()).Verifiable(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(fileSystem.Object), fileSystem.Object, localRepository); sourceRepository.AddPackage(package); // Act packageManager.InstallPackage("B"); // Assert Assert.True(localRepository.Exists(package)); batchProcessor.Verify(); } private PackageManager CreatePackageManager() { var projectSystem = new MockProjectSystem(); return new PackageManager( new MockPackageRepository(), new DefaultPackagePathResolver(projectSystem), projectSystem, new MockPackageRepository()); } } }
/* * 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.Linq; using System.Diagnostics; using System.Collections.Generic; using System.Threading; using System.Security.Cryptography.X509Certificates; using Thrift.Collections; using Thrift.Protocol; using Thrift.Transport; using Thrift.Test; namespace Test { public class TestClient { private class TestParams { public int numIterations = 1; public string host = "localhost"; public int port = 9090; public string url; public string pipe; public bool buffered; public bool framed; public string protocol; public bool encrypted = false; public TTransport CreateTransport() { if (url == null) { // endpoint transport TTransport trans = null; if (pipe != null) trans = new TNamedPipeClientTransport(pipe); else { if (encrypted) { string certPath = "../../../../test/keys/client.p12"; X509Certificate cert = new X509Certificate2(certPath, "thrift"); trans = new TTLSSocket(host, port, cert, (o, c, chain, errors) => true); } else { trans = new TSocket(host, port); } } // layered transport if (buffered) trans = new TBufferedTransport(trans); if (framed) trans = new TFramedTransport(trans); //ensure proper open/close of transport trans.Open(); trans.Close(); return trans; } else { return new THttpClient(new Uri(url)); } } public TProtocol CreateProtocol(TTransport transport) { if (protocol == "compact") return new TCompactProtocol(transport); else if (protocol == "json") return new TJSONProtocol(transport); else return new TBinaryProtocol(transport); } }; private const int ErrorBaseTypes = 1; private const int ErrorStructs = 2; private const int ErrorContainers = 4; private const int ErrorExceptions = 8; private const int ErrorUnknown = 64; private class ClientTest { private readonly TTransport transport; private readonly ThriftTest.Client client; private readonly int numIterations; private bool done; public int ReturnCode { get; set; } public ClientTest(TestParams param) { transport = param.CreateTransport(); client = new ThriftTest.Client(param.CreateProtocol(transport)); numIterations = param.numIterations; } public void Execute() { if (done) { Console.WriteLine("Execute called more than once"); throw new InvalidOperationException(); } for (int i = 0; i < numIterations; i++) { try { if (!transport.IsOpen) transport.Open(); } catch (TTransportException ex) { Console.WriteLine("*** FAILED ***"); Console.WriteLine("Connect failed: " + ex.Message); ReturnCode |= ErrorUnknown; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); continue; } try { ReturnCode |= ExecuteClientTest(client); } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); ReturnCode |= ErrorUnknown; } } try { transport.Close(); } catch(Exception ex) { Console.WriteLine("Error while closing transport"); Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } done = true; } } public static int Execute(string[] args) { try { TestParams param = new TestParams(); int numThreads = 1; try { for (int i = 0; i < args.Length; i++) { if (args[i] == "-u") { param.url = args[++i]; } else if (args[i] == "-n") { param.numIterations = Convert.ToInt32(args[++i]); } else if (args[i] == "-pipe") // -pipe <name> { param.pipe = args[++i]; Console.WriteLine("Using named pipes transport"); } else if (args[i].Contains("--host=")) { param.host = args[i].Substring(args[i].IndexOf("=") + 1); } else if (args[i].Contains("--port=")) { param.port = int.Parse(args[i].Substring(args[i].IndexOf("=")+1)); } else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered") { param.buffered = true; Console.WriteLine("Using buffered sockets"); } else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed") { param.framed = true; Console.WriteLine("Using framed transport"); } else if (args[i] == "-t") { numThreads = Convert.ToInt32(args[++i]); } else if (args[i] == "--compact" || args[i] == "--protocol=compact") { param.protocol = "compact"; Console.WriteLine("Using compact protocol"); } else if (args[i] == "--json" || args[i] == "--protocol=json") { param.protocol = "json"; Console.WriteLine("Using JSON protocol"); } else if (args[i] == "--ssl") { param.encrypted = true; Console.WriteLine("Using encrypted transport"); } } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); Console.WriteLine("Error while parsing arguments"); Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); return ErrorUnknown; } var tests = Enumerable.Range(0, numThreads).Select(_ => new ClientTest(param)).ToArray(); //issue tests on separate threads simultaneously var threads = tests.Select(test => new Thread(test.Execute)).ToArray(); DateTime start = DateTime.Now; foreach (var t in threads) t.Start(); foreach (var t in threads) t.Join(); Console.WriteLine("Total time: " + (DateTime.Now - start)); Console.WriteLine(); return tests.Select(t => t.ReturnCode).Aggregate((r1, r2) => r1 | r2); } catch (Exception outerEx) { Console.WriteLine("*** FAILED ***"); Console.WriteLine("Unexpected error"); Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace); return ErrorUnknown; } } public static string BytesToHex(byte[] data) { return BitConverter.ToString(data).Replace("-", string.Empty); } public static byte[] PrepareTestData(bool randomDist) { byte[] retval = new byte[0x100]; int initLen = Math.Min(0x100,retval.Length); // linear distribution, unless random is requested if (!randomDist) { for (var i = 0; i < initLen; ++i) { retval[i] = (byte)i; } return retval; } // random distribution for (var i = 0; i < initLen; ++i) { retval[i] = (byte)0; } var rnd = new Random(); for (var i = 1; i < initLen; ++i) { while( true) { int nextPos = rnd.Next() % initLen; if (retval[nextPos] == 0) { retval[nextPos] = (byte)i; break; } } } return retval; } public static int ExecuteClientTest(ThriftTest.Client client) { int returnCode = 0; Console.Write("testVoid()"); client.testVoid(); Console.WriteLine(" = void"); Console.Write("testString(\"Test\")"); string s = client.testString("Test"); Console.WriteLine(" = \"" + s + "\""); if ("Test" != s) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testBool(true)"); bool t = client.testBool((bool)true); Console.WriteLine(" = " + t); if (!t) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testBool(false)"); bool f = client.testBool((bool)false); Console.WriteLine(" = " + f); if (f) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testByte(1)"); sbyte i8 = client.testByte((sbyte)1); Console.WriteLine(" = " + i8); if (1 != i8) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testI32(-1)"); int i32 = client.testI32(-1); Console.WriteLine(" = " + i32); if (-1 != i32) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("testI64(-34359738368)"); long i64 = client.testI64(-34359738368); Console.WriteLine(" = " + i64); if (-34359738368 != i64) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } // TODO: Validate received message Console.Write("testDouble(5.325098235)"); double dub = client.testDouble(5.325098235); Console.WriteLine(" = " + dub); if (5.325098235 != dub) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } byte[] binOut = PrepareTestData(true); Console.Write("testBinary(" + BytesToHex(binOut) + ")"); try { byte[] binIn = client.testBinary(binOut); Console.WriteLine(" = " + BytesToHex(binIn)); if (binIn.Length != binOut.Length) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } for (int ofs = 0; ofs < Math.Min(binIn.Length, binOut.Length); ++ofs) if (binIn[ofs] != binOut[ofs]) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } } catch (Thrift.TApplicationException ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } // binary equals? only with hashcode option enabled ... Console.WriteLine("Test CrazyNesting"); if( typeof(CrazyNesting).GetMethod("Equals").DeclaringType == typeof(CrazyNesting)) { CrazyNesting one = new CrazyNesting(); CrazyNesting two = new CrazyNesting(); one.String_field = "crazy"; two.String_field = "crazy"; one.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF }; two.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF }; if (!one.Equals(two)) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorContainers; throw new Exception("CrazyNesting.Equals failed"); } } // TODO: Validate received message Console.Write("testStruct({\"Zero\", 1, -3, -5})"); Xtruct o = new Xtruct(); o.String_thing = "Zero"; o.Byte_thing = (sbyte)1; o.I32_thing = -3; o.I64_thing = -5; Xtruct i = client.testStruct(o); Console.WriteLine(" = {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}"); // TODO: Validate received message Console.Write("testNest({1, {\"Zero\", 1, -3, -5}, 5})"); Xtruct2 o2 = new Xtruct2(); o2.Byte_thing = (sbyte)1; o2.Struct_thing = o; o2.I32_thing = 5; Xtruct2 i2 = client.testNest(o2); i = i2.Struct_thing; Console.WriteLine(" = {" + i2.Byte_thing + ", {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}, " + i2.I32_thing + "}"); Dictionary<int, int> mapout = new Dictionary<int, int>(); for (int j = 0; j < 5; j++) { mapout[j] = j - 10; } Console.Write("testMap({"); bool first = true; foreach (int key in mapout.Keys) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(key + " => " + mapout[key]); } Console.Write("})"); Dictionary<int, int> mapin = client.testMap(mapout); Console.Write(" = {"); first = true; foreach (int key in mapin.Keys) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(key + " => " + mapin[key]); } Console.WriteLine("}"); // TODO: Validate received message List<int> listout = new List<int>(); for (int j = -2; j < 3; j++) { listout.Add(j); } Console.Write("testList({"); first = true; foreach (int j in listout) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.Write("})"); List<int> listin = client.testList(listout); Console.Write(" = {"); first = true; foreach (int j in listin) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.WriteLine("}"); //set // TODO: Validate received message THashSet<int> setout = new THashSet<int>(); for (int j = -2; j < 3; j++) { setout.Add(j); } Console.Write("testSet({"); first = true; foreach (int j in setout) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.Write("})"); THashSet<int> setin = client.testSet(setout); Console.Write(" = {"); first = true; foreach (int j in setin) { if (first) { first = false; } else { Console.Write(", "); } Console.Write(j); } Console.WriteLine("}"); Console.Write("testEnum(ONE)"); Numberz ret = client.testEnum(Numberz.ONE); Console.WriteLine(" = " + ret); if (Numberz.ONE != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(TWO)"); ret = client.testEnum(Numberz.TWO); Console.WriteLine(" = " + ret); if (Numberz.TWO != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(THREE)"); ret = client.testEnum(Numberz.THREE); Console.WriteLine(" = " + ret); if (Numberz.THREE != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(FIVE)"); ret = client.testEnum(Numberz.FIVE); Console.WriteLine(" = " + ret); if (Numberz.FIVE != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testEnum(EIGHT)"); ret = client.testEnum(Numberz.EIGHT); Console.WriteLine(" = " + ret); if (Numberz.EIGHT != ret) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } Console.Write("testTypedef(309858235082523)"); long uid = client.testTypedef(309858235082523L); Console.WriteLine(" = " + uid); if (309858235082523L != uid) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorStructs; } // TODO: Validate received message Console.Write("testMapMap(1)"); Dictionary<int, Dictionary<int, int>> mm = client.testMapMap(1); Console.Write(" = {"); foreach (int key in mm.Keys) { Console.Write(key + " => {"); Dictionary<int, int> m2 = mm[key]; foreach (int k2 in m2.Keys) { Console.Write(k2 + " => " + m2[k2] + ", "); } Console.Write("}, "); } Console.WriteLine("}"); // TODO: Validate received message Insanity insane = new Insanity(); insane.UserMap = new Dictionary<Numberz, long>(); insane.UserMap[Numberz.FIVE] = 5000L; Xtruct truck = new Xtruct(); truck.String_thing = "Truck"; truck.Byte_thing = (sbyte)8; truck.I32_thing = 8; truck.I64_thing = 8; insane.Xtructs = new List<Xtruct>(); insane.Xtructs.Add(truck); Console.Write("testInsanity()"); Dictionary<long, Dictionary<Numberz, Insanity>> whoa = client.testInsanity(insane); Console.Write(" = {"); foreach (long key in whoa.Keys) { Dictionary<Numberz, Insanity> val = whoa[key]; Console.Write(key + " => {"); foreach (Numberz k2 in val.Keys) { Insanity v2 = val[k2]; Console.Write(k2 + " => {"); Dictionary<Numberz, long> userMap = v2.UserMap; Console.Write("{"); if (userMap != null) { foreach (Numberz k3 in userMap.Keys) { Console.Write(k3 + " => " + userMap[k3] + ", "); } } else { Console.Write("null"); } Console.Write("}, "); List<Xtruct> xtructs = v2.Xtructs; Console.Write("{"); if (xtructs != null) { foreach (Xtruct x in xtructs) { Console.Write("{\"" + x.String_thing + "\", " + x.Byte_thing + ", " + x.I32_thing + ", " + x.I32_thing + "}, "); } } else { Console.Write("null"); } Console.Write("}"); Console.Write("}, "); } Console.Write("}, "); } Console.WriteLine("}"); sbyte arg0 = 1; int arg1 = 2; long arg2 = long.MaxValue; Dictionary<short, string> multiDict = new Dictionary<short, string>(); multiDict[1] = "one"; Numberz arg4 = Numberz.FIVE; long arg5 = 5000000; Console.Write("Test Multi(" + arg0 + "," + arg1 + "," + arg2 + "," + multiDict + "," + arg4 + "," + arg5 + ")"); Xtruct multiResponse = client.testMulti(arg0, arg1, arg2, multiDict, arg4, arg5); Console.Write(" = Xtruct(byte_thing:" + multiResponse.Byte_thing + ",String_thing:" + multiResponse.String_thing + ",i32_thing:" + multiResponse.I32_thing + ",i64_thing:" + multiResponse.I64_thing + ")\n"); try { Console.WriteLine("testException(\"Xception\")"); client.testException("Xception"); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Xception ex) { if (ex.ErrorCode != 1001 || ex.Message != "Xception") { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testException(\"TException\")"); client.testException("TException"); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Thrift.TException) { // OK } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testException(\"ok\")"); client.testException("ok"); // OK } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testMultiException(\"Xception\", ...)"); client.testMultiException("Xception", "ignore"); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Xception ex) { if (ex.ErrorCode != 1001 || ex.Message != "This is an Xception") { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testMultiException(\"Xception2\", ...)"); client.testMultiException("Xception2", "ignore"); Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } catch (Xception2 ex) { if (ex.ErrorCode != 2002 || ex.Struct_thing.String_thing != "This is an Xception2") { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } try { Console.WriteLine("testMultiException(\"success\", \"OK\")"); if ("OK" != client.testMultiException("success", "OK").String_thing) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; } } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorExceptions; Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); } Stopwatch sw = new Stopwatch(); sw.Start(); Console.WriteLine("Test Oneway(1)"); client.testOneway(1); sw.Stop(); if (sw.ElapsedMilliseconds > 1000) { Console.WriteLine("*** FAILED ***"); returnCode |= ErrorBaseTypes; } Console.Write("Test Calltime()"); var startt = DateTime.UtcNow; for ( int k=0; k<1000; ++k ) client.testVoid(); Console.WriteLine(" = " + (DateTime.UtcNow - startt).TotalSeconds.ToString() + " ms a testVoid() call" ); return returnCode; } } }
// 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.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.CognitiveServices { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// CognitiveServicesAccountsOperations operations. /// </summary> public partial interface ICognitiveServicesAccountsOperations { /// <summary> /// Create Cognitive Services Account. Accounts is a resource group /// wide resource type. It holds the keys for developer to access /// intelligent APIs. It's also the resource type for billing. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the cognitive services account within the specified /// resource group. Cognitive Services account names must be between /// 3 and 24 characters in length and use numbers and lower-case /// letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<CognitiveServicesAccount>> CreateWithHttpMessagesAsync(string resourceGroupName, string accountName, CognitiveServicesAccountCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates a Cognitive Services account /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the cognitive services account within the specified /// resource group. Cognitive Services account names must be between /// 3 and 24 characters in length and use numbers and lower-case /// letters only. /// </param> /// <param name='sku'> /// </param> /// <param name='tags'> /// Gets or sets a list of key value pairs that describe the resource. /// These tags can be used in viewing and grouping this resource /// (across resource groups). A maximum of 15 tags can be provided /// for a resource. Each tag must have a key no greater than 128 /// characters and value no greater than 256 characters. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<CognitiveServicesAccount>> UpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, Sku sku = default(Sku), IDictionary<string, string> tags = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a Cognitive Services account from the resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the cognitive services account within the specified /// resource group. Cognitive Services account names must be between /// 3 and 24 characters in length and use numbers and lower-case /// letters only. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns a Cognitive Services account specified by the parameters. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the cognitive services account within the specified /// resource group. Cognitive Services account names must be between /// 3 and 24 characters in length and use numbers and lower-case /// letters only. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<CognitiveServicesAccount>> GetPropertiesWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns all the resources of a particular type belonging to a /// resource group /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IEnumerable<CognitiveServicesAccount>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns all the resources of a particular type belonging to a /// subscription. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IEnumerable<CognitiveServicesAccount>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the account keys for the specified Cognitive Services /// account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the cognitive services account within the specified /// resource group. Congitive Services account names must be between /// 3 and 24 characters in length and use numbers and lower-case /// letters only. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<CognitiveServicesAccountKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerates the specified account key for the specified Cognitive /// Services account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the cognitive services account within the specified /// resource group. Cognitive Services account names must be between /// 3 and 24 characters in length and use numbers and lower-case /// letters only. /// </param> /// <param name='keyName'> /// key name to generate (Key1|Key2). Possible values include: 'Key1', /// 'Key2' /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<CognitiveServicesAccountKeys>> RegenerateKeyWithHttpMessagesAsync(string resourceGroupName, string accountName, KeyName? keyName = default(KeyName?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List available SKUs for the requested Cognitive Services account /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the cognitive services account within the specified /// resource group. Cognitive Services account names must be between /// 3 and 24 characters in length and use numbers and lower-case /// letters only. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<CognitiveServicesAccountEnumerateSkusResult>> ListSkusWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsHttp { using System; using System.Linq; 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> /// HttpRetry operations. /// </summary> public partial class HttpRetry : IServiceOperations<AutoRestHttpInfrastructureTestService>, IHttpRetry { /// <summary> /// Initializes a new instance of the HttpRetry class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> public HttpRetry(AutoRestHttpInfrastructureTestService client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestHttpInfrastructureTestService /// </summary> public AutoRestHttpInfrastructureTestService Client { get; private set; } /// <summary> /// Return 408 status code, then 200 after retry /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> Head408WithHttpMessagesAsync(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, "Head408", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/408").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("HEAD"); _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 ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } 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; } /// <summary> /// Return 500 status code, then 200 after retry /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> Put500WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Put500", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/500").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 = SafeJsonConvert.SerializeObject(booleanValue, 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 ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } 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; } /// <summary> /// Return 500 status code, then 200 after retry /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> Patch500WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Patch500", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/500").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("PATCH"); _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 = SafeJsonConvert.SerializeObject(booleanValue, 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 ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } 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; } /// <summary> /// Return 502 status code, then 200 after retry /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> Get502WithHttpMessagesAsync(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, "Get502", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/502").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 ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } 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; } /// <summary> /// Return 503 status code, then 200 after retry /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> Post503WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Post503", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/503").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("POST"); _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 = SafeJsonConvert.SerializeObject(booleanValue, 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 ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } 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; } /// <summary> /// Return 503 status code, then 200 after retry /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> Delete503WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete503", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/503").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("DELETE"); _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 = SafeJsonConvert.SerializeObject(booleanValue, 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 ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } 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; } /// <summary> /// Return 504 status code, then 200 after retry /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> Put504WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Put504", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/504").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 = SafeJsonConvert.SerializeObject(booleanValue, 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 ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } 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; } /// <summary> /// Return 504 status code, then 200 after retry /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> Patch504WithHttpMessagesAsync(bool? booleanValue = default(bool?), 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("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Patch504", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/retry/504").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("PATCH"); _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 = SafeJsonConvert.SerializeObject(booleanValue, 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 ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } 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; } } }
using System.Windows.Forms; using System.Drawing; using System.Drawing.Drawing2D; using System.ComponentModel; namespace WeifenLuo.WinFormsUI.Docking { partial class DockPanel { private sealed class DockDragHandler : DragHandler { private class DockIndicator : DragForm { #region IHitTest private interface IHitTest { DockStyle HitTest(Point pt); DockStyle Status { get; set; } } #endregion #region PanelIndicator private class PanelIndicator : PictureBox, IHitTest { private static Image _imagePanelLeft = Resources.DockIndicator_PanelLeft; private static Image _imagePanelRight = Resources.DockIndicator_PanelRight; private static Image _imagePanelTop = Resources.DockIndicator_PanelTop; private static Image _imagePanelBottom = Resources.DockIndicator_PanelBottom; private static Image _imagePanelFill = Resources.DockIndicator_PanelFill; private static Image _imagePanelLeftActive = Resources.DockIndicator_PanelLeft_Active; private static Image _imagePanelRightActive = Resources.DockIndicator_PanelRight_Active; private static Image _imagePanelTopActive = Resources.DockIndicator_PanelTop_Active; private static Image _imagePanelBottomActive = Resources.DockIndicator_PanelBottom_Active; private static Image _imagePanelFillActive = Resources.DockIndicator_PanelFill_Active; public PanelIndicator(DockStyle dockStyle) { m_dockStyle = dockStyle; SizeMode = PictureBoxSizeMode.AutoSize; Image = ImageInactive; } private DockStyle m_dockStyle; private DockStyle DockStyle { get { return m_dockStyle; } } private DockStyle m_status; public DockStyle Status { get { return m_status; } set { if (value != DockStyle && value != DockStyle.None) throw new InvalidEnumArgumentException(); if (m_status == value) return; m_status = value; IsActivated = (m_status != DockStyle.None); } } private Image ImageInactive { get { if (DockStyle == DockStyle.Left) return _imagePanelLeft; else if (DockStyle == DockStyle.Right) return _imagePanelRight; else if (DockStyle == DockStyle.Top) return _imagePanelTop; else if (DockStyle == DockStyle.Bottom) return _imagePanelBottom; else if (DockStyle == DockStyle.Fill) return _imagePanelFill; else return null; } } private Image ImageActive { get { if (DockStyle == DockStyle.Left) return _imagePanelLeftActive; else if (DockStyle == DockStyle.Right) return _imagePanelRightActive; else if (DockStyle == DockStyle.Top) return _imagePanelTopActive; else if (DockStyle == DockStyle.Bottom) return _imagePanelBottomActive; else if (DockStyle == DockStyle.Fill) return _imagePanelFillActive; else return null; } } private bool m_isActivated = false; private bool IsActivated { get { return m_isActivated; } set { m_isActivated = value; Image = IsActivated ? ImageActive : ImageInactive; } } public DockStyle HitTest(Point pt) { return this.Visible && ClientRectangle.Contains(PointToClient(pt)) ? DockStyle : DockStyle.None; } } #endregion PanelIndicator #region PaneIndicator private class PaneIndicator : PictureBox, IHitTest { private struct HotSpotIndex { public HotSpotIndex(int x, int y, DockStyle dockStyle) { m_x = x; m_y = y; m_dockStyle = dockStyle; } private int m_x; public int X { get { return m_x; } } private int m_y; public int Y { get { return m_y; } } private DockStyle m_dockStyle; public DockStyle DockStyle { get { return m_dockStyle; } } } private static Bitmap _bitmapPaneDiamond = Resources.DockIndicator_PaneDiamond; private static Bitmap _bitmapPaneDiamondLeft = Resources.DockIndicator_PaneDiamond_Left; private static Bitmap _bitmapPaneDiamondRight = Resources.DockIndicator_PaneDiamond_Right; private static Bitmap _bitmapPaneDiamondTop = Resources.DockIndicator_PaneDiamond_Top; private static Bitmap _bitmapPaneDiamondBottom = Resources.DockIndicator_PaneDiamond_Bottom; private static Bitmap _bitmapPaneDiamondFill = Resources.DockIndicator_PaneDiamond_Fill; private static Bitmap _bitmapPaneDiamondHotSpot = Resources.DockIndicator_PaneDiamond_HotSpot; private static Bitmap _bitmapPaneDiamondHotSpotIndex = Resources.DockIndicator_PaneDiamond_HotSpotIndex; private static HotSpotIndex[] _hotSpots = new HotSpotIndex[] { new HotSpotIndex(1, 0, DockStyle.Top), new HotSpotIndex(0, 1, DockStyle.Left), new HotSpotIndex(1, 1, DockStyle.Fill), new HotSpotIndex(2, 1, DockStyle.Right), new HotSpotIndex(1, 2, DockStyle.Bottom) }; private static GraphicsPath _displayingGraphicsPath = DrawHelper.CalculateGraphicsPathFromBitmap(_bitmapPaneDiamond); public PaneIndicator() { SizeMode = PictureBoxSizeMode.AutoSize; Image = _bitmapPaneDiamond; Region = new Region(DisplayingGraphicsPath); } public static GraphicsPath DisplayingGraphicsPath { get { return _displayingGraphicsPath; } } public DockStyle HitTest(Point pt) { if (!Visible) return DockStyle.None; pt = PointToClient(pt); if (!ClientRectangle.Contains(pt)) return DockStyle.None; for (int i = _hotSpots.GetLowerBound(0); i <= _hotSpots.GetUpperBound(0); i++) { if (_bitmapPaneDiamondHotSpot.GetPixel(pt.X, pt.Y) == _bitmapPaneDiamondHotSpotIndex.GetPixel(_hotSpots[i].X, _hotSpots[i].Y)) return _hotSpots[i].DockStyle; } return DockStyle.None; } private DockStyle m_status = DockStyle.None; public DockStyle Status { get { return m_status; } set { m_status = value; if (m_status == DockStyle.None) Image = _bitmapPaneDiamond; else if (m_status == DockStyle.Left) Image = _bitmapPaneDiamondLeft; else if (m_status == DockStyle.Right) Image = _bitmapPaneDiamondRight; else if (m_status == DockStyle.Top) Image = _bitmapPaneDiamondTop; else if (m_status == DockStyle.Bottom) Image = _bitmapPaneDiamondBottom; else if (m_status == DockStyle.Fill) Image = _bitmapPaneDiamondFill; } } } #endregion PaneIndicator #region consts private int _PanelIndicatorMargin = 10; #endregion private DockDragHandler m_dragHandler; public DockIndicator(DockDragHandler dragHandler) { m_dragHandler = dragHandler; Controls.AddRange(new Control[] { PaneDiamond, PanelLeft, PanelRight, PanelTop, PanelBottom, PanelFill }); Region = new Region(Rectangle.Empty); } private PaneIndicator m_paneDiamond = null; private PaneIndicator PaneDiamond { get { if (m_paneDiamond == null) m_paneDiamond = new PaneIndicator(); return m_paneDiamond; } } private PanelIndicator m_panelLeft = null; private PanelIndicator PanelLeft { get { if (m_panelLeft == null) m_panelLeft = new PanelIndicator(DockStyle.Left); return m_panelLeft; } } private PanelIndicator m_panelRight = null; private PanelIndicator PanelRight { get { if (m_panelRight == null) m_panelRight = new PanelIndicator(DockStyle.Right); return m_panelRight; } } private PanelIndicator m_panelTop = null; private PanelIndicator PanelTop { get { if (m_panelTop == null) m_panelTop = new PanelIndicator(DockStyle.Top); return m_panelTop; } } private PanelIndicator m_panelBottom = null; private PanelIndicator PanelBottom { get { if (m_panelBottom == null) m_panelBottom = new PanelIndicator(DockStyle.Bottom); return m_panelBottom; } } private PanelIndicator m_panelFill = null; private PanelIndicator PanelFill { get { if (m_panelFill == null) m_panelFill = new PanelIndicator(DockStyle.Fill); return m_panelFill; } } private bool m_fullPanelEdge = false; public bool FullPanelEdge { get { return m_fullPanelEdge; } set { if (m_fullPanelEdge == value) return; m_fullPanelEdge = value; RefreshChanges(); } } public DockDragHandler DragHandler { get { return m_dragHandler; } } public DockPanel DockPanel { get { return DragHandler.DockPanel; } } private DockPane m_dockPane = null; public DockPane DockPane { get { return m_dockPane; } internal set { if (m_dockPane == value) return; DockPane oldDisplayingPane = DisplayingPane; m_dockPane = value; if (oldDisplayingPane != DisplayingPane) RefreshChanges(); } } private IHitTest m_hitTest = null; private IHitTest HitTestResult { get { return m_hitTest; } set { if (m_hitTest == value) return; if (m_hitTest != null) m_hitTest.Status = DockStyle.None; m_hitTest = value; } } private DockPane DisplayingPane { get { return ShouldPaneDiamondVisible() ? DockPane : null; } } private void RefreshChanges() { Region region = new Region(Rectangle.Empty); Rectangle rectDockArea = FullPanelEdge ? DockPanel.DockArea : DockPanel.DocumentWindowBounds; rectDockArea = RectangleToClient(DockPanel.RectangleToScreen(rectDockArea)); if (ShouldPanelIndicatorVisible(DockState.DockLeft)) { PanelLeft.Location = new Point(rectDockArea.X + _PanelIndicatorMargin, rectDockArea.Y + (rectDockArea.Height - PanelRight.Height) / 2); PanelLeft.Visible = true; region.Union(PanelLeft.Bounds); } else PanelLeft.Visible = false; if (ShouldPanelIndicatorVisible(DockState.DockRight)) { PanelRight.Location = new Point(rectDockArea.X + rectDockArea.Width - PanelRight.Width - _PanelIndicatorMargin, rectDockArea.Y + (rectDockArea.Height - PanelRight.Height) / 2); PanelRight.Visible = true; region.Union(PanelRight.Bounds); } else PanelRight.Visible = false; if (ShouldPanelIndicatorVisible(DockState.DockTop)) { PanelTop.Location = new Point(rectDockArea.X + (rectDockArea.Width - PanelTop.Width) / 2, rectDockArea.Y + _PanelIndicatorMargin); PanelTop.Visible = true; region.Union(PanelTop.Bounds); } else PanelTop.Visible = false; if (ShouldPanelIndicatorVisible(DockState.DockBottom)) { PanelBottom.Location = new Point(rectDockArea.X + (rectDockArea.Width - PanelBottom.Width) / 2, rectDockArea.Y + rectDockArea.Height - PanelBottom.Height - _PanelIndicatorMargin); PanelBottom.Visible = true; region.Union(PanelBottom.Bounds); } else PanelBottom.Visible = false; if (ShouldPanelIndicatorVisible(DockState.Document)) { Rectangle rectDocumentWindow = RectangleToClient(DockPanel.RectangleToScreen(DockPanel.DocumentWindowBounds)); PanelFill.Location = new Point(rectDocumentWindow.X + (rectDocumentWindow.Width - PanelFill.Width) / 2, rectDocumentWindow.Y + (rectDocumentWindow.Height - PanelFill.Height) / 2); PanelFill.Visible = true; region.Union(PanelFill.Bounds); } else PanelFill.Visible = false; if (ShouldPaneDiamondVisible()) { Rectangle rect = RectangleToClient(DockPane.RectangleToScreen(DockPane.ClientRectangle)); PaneDiamond.Location = new Point(rect.Left + (rect.Width - PaneDiamond.Width) / 2, rect.Top + (rect.Height - PaneDiamond.Height) / 2); PaneDiamond.Visible = true; using (GraphicsPath graphicsPath = PaneIndicator.DisplayingGraphicsPath.Clone() as GraphicsPath) { Point[] pts = new Point[] { new Point(PaneDiamond.Left, PaneDiamond.Top), new Point(PaneDiamond.Right, PaneDiamond.Top), new Point(PaneDiamond.Left, PaneDiamond.Bottom) }; using (Matrix matrix = new Matrix(PaneDiamond.ClientRectangle, pts)) { graphicsPath.Transform(matrix); } region.Union(graphicsPath); } } else PaneDiamond.Visible = false; Region = region; } private bool ShouldPanelIndicatorVisible(DockState dockState) { if (!Visible) return false; if (DockPanel.DockWindows[dockState].Visible) return false; return DragHandler.DragSource.IsDockStateValid(dockState); } private bool ShouldPaneDiamondVisible() { if (DockPane == null) return false; if (!DockPanel.AllowEndUserNestedDocking) return false; return DragHandler.DragSource.CanDockTo(DockPane); } public override void Show(bool bActivate) { base.Show(bActivate); Bounds = SystemInformation.VirtualScreen; RefreshChanges(); } public void TestDrop() { Point pt = Control.MousePosition; DockPane = DockHelper.PaneAtPoint(pt, DockPanel); if (TestDrop(PanelLeft, pt) != DockStyle.None) HitTestResult = PanelLeft; else if (TestDrop(PanelRight, pt) != DockStyle.None) HitTestResult = PanelRight; else if (TestDrop(PanelTop, pt) != DockStyle.None) HitTestResult = PanelTop; else if (TestDrop(PanelBottom, pt) != DockStyle.None) HitTestResult = PanelBottom; else if (TestDrop(PanelFill, pt) != DockStyle.None) HitTestResult = PanelFill; else if (TestDrop(PaneDiamond, pt) != DockStyle.None) HitTestResult = PaneDiamond; else HitTestResult = null; if (HitTestResult != null) { if (HitTestResult is PaneIndicator) DragHandler.Outline.Show(DockPane, HitTestResult.Status); else DragHandler.Outline.Show(DockPanel, HitTestResult.Status, FullPanelEdge); } } private static DockStyle TestDrop(IHitTest hitTest, Point pt) { return hitTest.Status = hitTest.HitTest(pt); } } private class DockOutline : DockOutlineBase { public DockOutline() { m_dragForm = new DragForm(); SetDragForm(Rectangle.Empty); DragForm.BackColor = SystemColors.ActiveCaption; DragForm.Opacity = 0.5; DragForm.Show(false); } DragForm m_dragForm; private DragForm DragForm { get { return m_dragForm; } } protected override void OnShow() { CalculateRegion(); } protected override void OnClose() { DragForm.Close(); } private void CalculateRegion() { if (SameAsOldValue) return; if (!FloatWindowBounds.IsEmpty) SetOutline(FloatWindowBounds); else if (DockTo is DockPanel) SetOutline(DockTo as DockPanel, Dock, (ContentIndex != 0)); else if (DockTo is DockPane) SetOutline(DockTo as DockPane, Dock, ContentIndex); else SetOutline(); } private void SetOutline() { SetDragForm(Rectangle.Empty); } private void SetOutline(Rectangle floatWindowBounds) { SetDragForm(floatWindowBounds); } private void SetOutline(DockPanel dockPanel, DockStyle dock, bool fullPanelEdge) { Rectangle rect = fullPanelEdge ? dockPanel.DockArea : dockPanel.DocumentWindowBounds; rect.Location = dockPanel.PointToScreen(rect.Location); if (dock == DockStyle.Top) { int height = dockPanel.GetDockWindowSize(DockState.DockTop); rect = new Rectangle(rect.X, rect.Y, rect.Width, height); } else if (dock == DockStyle.Bottom) { int height = dockPanel.GetDockWindowSize(DockState.DockBottom); rect = new Rectangle(rect.X, rect.Bottom - height, rect.Width, height); } else if (dock == DockStyle.Left) { int width = dockPanel.GetDockWindowSize(DockState.DockLeft); rect = new Rectangle(rect.X, rect.Y, width, rect.Height); } else if (dock == DockStyle.Right) { int width = dockPanel.GetDockWindowSize(DockState.DockRight); rect = new Rectangle(rect.Right - width, rect.Y, width, rect.Height); } else if (dock == DockStyle.Fill) { rect = dockPanel.DocumentWindowBounds; rect.Location = dockPanel.PointToScreen(rect.Location); } SetDragForm(rect); } private void SetOutline(DockPane pane, DockStyle dock, int contentIndex) { if (dock != DockStyle.Fill) { Rectangle rect = pane.DisplayingRectangle; if (dock == DockStyle.Right) rect.X += rect.Width / 2; if (dock == DockStyle.Bottom) rect.Y += rect.Height / 2; if (dock == DockStyle.Left || dock == DockStyle.Right) rect.Width -= rect.Width / 2; if (dock == DockStyle.Top || dock == DockStyle.Bottom) rect.Height -= rect.Height / 2; rect.Location = pane.PointToScreen(rect.Location); SetDragForm(rect); } else if (contentIndex == -1) { Rectangle rect = pane.DisplayingRectangle; rect.Location = pane.PointToScreen(rect.Location); SetDragForm(rect); } else { using (GraphicsPath path = pane.TabStripControl.GetOutline(contentIndex)) { RectangleF rectF = path.GetBounds(); Rectangle rect = new Rectangle((int)rectF.X, (int)rectF.Y, (int)rectF.Width, (int)rectF.Height); using (Matrix matrix = new Matrix(rect, new Point[] { new Point(0, 0), new Point(rect.Width, 0), new Point(0, rect.Height) })) { path.Transform(matrix); } Region region = new Region(path); SetDragForm(rect, region); } } } private void SetDragForm(Rectangle rect) { DragForm.Bounds = rect; if (rect == Rectangle.Empty) DragForm.Region = new Region(Rectangle.Empty); else if (DragForm.Region != null) DragForm.Region = null; } private void SetDragForm(Rectangle rect, Region region) { DragForm.Bounds = rect; DragForm.Region = region; } } public DockDragHandler(DockPanel panel) : base(panel) { } public new IDockDragSource DragSource { get { return base.DragSource as IDockDragSource; } set { base.DragSource = value; } } private DockOutlineBase m_outline; public DockOutlineBase Outline { get { return m_outline; } private set { m_outline = value; } } private DockIndicator m_indicator; private DockIndicator Indicator { get { return m_indicator; } set { m_indicator = value; } } private Rectangle m_floatOutlineBounds; private Rectangle FloatOutlineBounds { get { return m_floatOutlineBounds; } set { m_floatOutlineBounds = value; } } public void BeginDrag(IDockDragSource dragSource) { DragSource = dragSource; if (!BeginDrag()) { DragSource = null; return; } Outline = new DockOutline(); Indicator = new DockIndicator(this); Indicator.Show(false); FloatOutlineBounds = DragSource.BeginDrag(StartMousePosition); } protected override void OnDragging() { TestDrop(); } protected override void OnEndDrag(bool abort) { DockPanel.SuspendLayout(true); Outline.Close(); Indicator.Close(); EndDrag(abort); // Queue a request to layout all children controls DockPanel.PerformMdiClientLayout(); DockPanel.ResumeLayout(true, true); DragSource.EndDrag(); DragSource = null; } private void TestDrop() { Outline.FlagTestDrop = false; Indicator.FullPanelEdge = ((Control.ModifierKeys & Keys.Shift) != 0); if ((Control.ModifierKeys & Keys.Control) == 0) { Indicator.TestDrop(); if (!Outline.FlagTestDrop) { DockPane pane = DockHelper.PaneAtPoint(Control.MousePosition, DockPanel); if (pane != null && DragSource.IsDockStateValid(pane.DockState)) pane.TestDrop(DragSource, Outline); } if (!Outline.FlagTestDrop && DragSource.IsDockStateValid(DockState.Float)) { FloatWindow floatWindow = DockHelper.FloatWindowAtPoint(Control.MousePosition, DockPanel); if (floatWindow != null) floatWindow.TestDrop(DragSource, Outline); } } else Indicator.DockPane = DockHelper.PaneAtPoint(Control.MousePosition, DockPanel); if (!Outline.FlagTestDrop) { if (DragSource.IsDockStateValid(DockState.Float)) { Rectangle rect = FloatOutlineBounds; rect.Offset(Control.MousePosition.X - StartMousePosition.X, Control.MousePosition.Y - StartMousePosition.Y); Outline.Show(rect); } } if (!Outline.FlagTestDrop) { Cursor.Current = Cursors.No; Outline.Show(); } else Cursor.Current = DragControl.Cursor; } private void EndDrag(bool abort) { if (abort) return; if (!Outline.FloatWindowBounds.IsEmpty) DragSource.FloatAt(Outline.FloatWindowBounds); else if (Outline.DockTo is DockPane) { DockPane pane = Outline.DockTo as DockPane; DragSource.DockTo(pane, Outline.Dock, Outline.ContentIndex); } else if (Outline.DockTo is DockPanel) { DockPanel panel = Outline.DockTo as DockPanel; panel.UpdateDockWindowZOrder(Outline.Dock, Outline.FlagFullEdge); DragSource.DockTo(panel, Outline.Dock); } } } private DockDragHandler m_dockDragHandler = null; private DockDragHandler GetDockDragHandler() { if (m_dockDragHandler == null) m_dockDragHandler = new DockDragHandler(this); return m_dockDragHandler; } internal void BeginDrag(IDockDragSource dragSource) { GetDockDragHandler().BeginDrag(dragSource); } } }
// Copyright (C) 2014 dot42 // // Original filename: Javax.Microedition.Khronos.Egl.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Javax.Microedition.Khronos.Egl { /// <java-name> /// javax/microedition/khronos/egl/EGLConfig /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGLConfig", AccessFlags = 1057)] public abstract partial class EGLConfig /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public EGLConfig() /* MethodBuilder.Create */ { } } /// <java-name> /// javax/microedition/khronos/egl/EGL10 /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL10", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IEGL10Constants /* scope: __dot42__ */ { /// <java-name> /// EGL_SUCCESS /// </java-name> [Dot42.DexImport("EGL_SUCCESS", "I", AccessFlags = 25)] public const int EGL_SUCCESS = 12288; /// <java-name> /// EGL_NOT_INITIALIZED /// </java-name> [Dot42.DexImport("EGL_NOT_INITIALIZED", "I", AccessFlags = 25)] public const int EGL_NOT_INITIALIZED = 12289; /// <java-name> /// EGL_BAD_ACCESS /// </java-name> [Dot42.DexImport("EGL_BAD_ACCESS", "I", AccessFlags = 25)] public const int EGL_BAD_ACCESS = 12290; /// <java-name> /// EGL_BAD_ALLOC /// </java-name> [Dot42.DexImport("EGL_BAD_ALLOC", "I", AccessFlags = 25)] public const int EGL_BAD_ALLOC = 12291; /// <java-name> /// EGL_BAD_ATTRIBUTE /// </java-name> [Dot42.DexImport("EGL_BAD_ATTRIBUTE", "I", AccessFlags = 25)] public const int EGL_BAD_ATTRIBUTE = 12292; /// <java-name> /// EGL_BAD_CONFIG /// </java-name> [Dot42.DexImport("EGL_BAD_CONFIG", "I", AccessFlags = 25)] public const int EGL_BAD_CONFIG = 12293; /// <java-name> /// EGL_BAD_CONTEXT /// </java-name> [Dot42.DexImport("EGL_BAD_CONTEXT", "I", AccessFlags = 25)] public const int EGL_BAD_CONTEXT = 12294; /// <java-name> /// EGL_BAD_CURRENT_SURFACE /// </java-name> [Dot42.DexImport("EGL_BAD_CURRENT_SURFACE", "I", AccessFlags = 25)] public const int EGL_BAD_CURRENT_SURFACE = 12295; /// <java-name> /// EGL_BAD_DISPLAY /// </java-name> [Dot42.DexImport("EGL_BAD_DISPLAY", "I", AccessFlags = 25)] public const int EGL_BAD_DISPLAY = 12296; /// <java-name> /// EGL_BAD_MATCH /// </java-name> [Dot42.DexImport("EGL_BAD_MATCH", "I", AccessFlags = 25)] public const int EGL_BAD_MATCH = 12297; /// <java-name> /// EGL_BAD_NATIVE_PIXMAP /// </java-name> [Dot42.DexImport("EGL_BAD_NATIVE_PIXMAP", "I", AccessFlags = 25)] public const int EGL_BAD_NATIVE_PIXMAP = 12298; /// <java-name> /// EGL_BAD_NATIVE_WINDOW /// </java-name> [Dot42.DexImport("EGL_BAD_NATIVE_WINDOW", "I", AccessFlags = 25)] public const int EGL_BAD_NATIVE_WINDOW = 12299; /// <java-name> /// EGL_BAD_PARAMETER /// </java-name> [Dot42.DexImport("EGL_BAD_PARAMETER", "I", AccessFlags = 25)] public const int EGL_BAD_PARAMETER = 12300; /// <java-name> /// EGL_BAD_SURFACE /// </java-name> [Dot42.DexImport("EGL_BAD_SURFACE", "I", AccessFlags = 25)] public const int EGL_BAD_SURFACE = 12301; /// <java-name> /// EGL_BUFFER_SIZE /// </java-name> [Dot42.DexImport("EGL_BUFFER_SIZE", "I", AccessFlags = 25)] public const int EGL_BUFFER_SIZE = 12320; /// <java-name> /// EGL_ALPHA_SIZE /// </java-name> [Dot42.DexImport("EGL_ALPHA_SIZE", "I", AccessFlags = 25)] public const int EGL_ALPHA_SIZE = 12321; /// <java-name> /// EGL_BLUE_SIZE /// </java-name> [Dot42.DexImport("EGL_BLUE_SIZE", "I", AccessFlags = 25)] public const int EGL_BLUE_SIZE = 12322; /// <java-name> /// EGL_GREEN_SIZE /// </java-name> [Dot42.DexImport("EGL_GREEN_SIZE", "I", AccessFlags = 25)] public const int EGL_GREEN_SIZE = 12323; /// <java-name> /// EGL_RED_SIZE /// </java-name> [Dot42.DexImport("EGL_RED_SIZE", "I", AccessFlags = 25)] public const int EGL_RED_SIZE = 12324; /// <java-name> /// EGL_DEPTH_SIZE /// </java-name> [Dot42.DexImport("EGL_DEPTH_SIZE", "I", AccessFlags = 25)] public const int EGL_DEPTH_SIZE = 12325; /// <java-name> /// EGL_STENCIL_SIZE /// </java-name> [Dot42.DexImport("EGL_STENCIL_SIZE", "I", AccessFlags = 25)] public const int EGL_STENCIL_SIZE = 12326; /// <java-name> /// EGL_CONFIG_CAVEAT /// </java-name> [Dot42.DexImport("EGL_CONFIG_CAVEAT", "I", AccessFlags = 25)] public const int EGL_CONFIG_CAVEAT = 12327; /// <java-name> /// EGL_CONFIG_ID /// </java-name> [Dot42.DexImport("EGL_CONFIG_ID", "I", AccessFlags = 25)] public const int EGL_CONFIG_ID = 12328; /// <java-name> /// EGL_LEVEL /// </java-name> [Dot42.DexImport("EGL_LEVEL", "I", AccessFlags = 25)] public const int EGL_LEVEL = 12329; /// <java-name> /// EGL_MAX_PBUFFER_HEIGHT /// </java-name> [Dot42.DexImport("EGL_MAX_PBUFFER_HEIGHT", "I", AccessFlags = 25)] public const int EGL_MAX_PBUFFER_HEIGHT = 12330; /// <java-name> /// EGL_MAX_PBUFFER_PIXELS /// </java-name> [Dot42.DexImport("EGL_MAX_PBUFFER_PIXELS", "I", AccessFlags = 25)] public const int EGL_MAX_PBUFFER_PIXELS = 12331; /// <java-name> /// EGL_MAX_PBUFFER_WIDTH /// </java-name> [Dot42.DexImport("EGL_MAX_PBUFFER_WIDTH", "I", AccessFlags = 25)] public const int EGL_MAX_PBUFFER_WIDTH = 12332; /// <java-name> /// EGL_NATIVE_RENDERABLE /// </java-name> [Dot42.DexImport("EGL_NATIVE_RENDERABLE", "I", AccessFlags = 25)] public const int EGL_NATIVE_RENDERABLE = 12333; /// <java-name> /// EGL_NATIVE_VISUAL_ID /// </java-name> [Dot42.DexImport("EGL_NATIVE_VISUAL_ID", "I", AccessFlags = 25)] public const int EGL_NATIVE_VISUAL_ID = 12334; /// <java-name> /// EGL_NATIVE_VISUAL_TYPE /// </java-name> [Dot42.DexImport("EGL_NATIVE_VISUAL_TYPE", "I", AccessFlags = 25)] public const int EGL_NATIVE_VISUAL_TYPE = 12335; /// <java-name> /// EGL_SAMPLES /// </java-name> [Dot42.DexImport("EGL_SAMPLES", "I", AccessFlags = 25)] public const int EGL_SAMPLES = 12337; /// <java-name> /// EGL_SAMPLE_BUFFERS /// </java-name> [Dot42.DexImport("EGL_SAMPLE_BUFFERS", "I", AccessFlags = 25)] public const int EGL_SAMPLE_BUFFERS = 12338; /// <java-name> /// EGL_SURFACE_TYPE /// </java-name> [Dot42.DexImport("EGL_SURFACE_TYPE", "I", AccessFlags = 25)] public const int EGL_SURFACE_TYPE = 12339; /// <java-name> /// EGL_TRANSPARENT_TYPE /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_TYPE", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_TYPE = 12340; /// <java-name> /// EGL_TRANSPARENT_BLUE_VALUE /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_BLUE_VALUE", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_BLUE_VALUE = 12341; /// <java-name> /// EGL_TRANSPARENT_GREEN_VALUE /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_GREEN_VALUE", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_GREEN_VALUE = 12342; /// <java-name> /// EGL_TRANSPARENT_RED_VALUE /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_RED_VALUE", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_RED_VALUE = 12343; /// <java-name> /// EGL_NONE /// </java-name> [Dot42.DexImport("EGL_NONE", "I", AccessFlags = 25)] public const int EGL_NONE = 12344; /// <java-name> /// EGL_LUMINANCE_SIZE /// </java-name> [Dot42.DexImport("EGL_LUMINANCE_SIZE", "I", AccessFlags = 25)] public const int EGL_LUMINANCE_SIZE = 12349; /// <java-name> /// EGL_ALPHA_MASK_SIZE /// </java-name> [Dot42.DexImport("EGL_ALPHA_MASK_SIZE", "I", AccessFlags = 25)] public const int EGL_ALPHA_MASK_SIZE = 12350; /// <java-name> /// EGL_COLOR_BUFFER_TYPE /// </java-name> [Dot42.DexImport("EGL_COLOR_BUFFER_TYPE", "I", AccessFlags = 25)] public const int EGL_COLOR_BUFFER_TYPE = 12351; /// <java-name> /// EGL_RENDERABLE_TYPE /// </java-name> [Dot42.DexImport("EGL_RENDERABLE_TYPE", "I", AccessFlags = 25)] public const int EGL_RENDERABLE_TYPE = 12352; /// <java-name> /// EGL_SLOW_CONFIG /// </java-name> [Dot42.DexImport("EGL_SLOW_CONFIG", "I", AccessFlags = 25)] public const int EGL_SLOW_CONFIG = 12368; /// <java-name> /// EGL_NON_CONFORMANT_CONFIG /// </java-name> [Dot42.DexImport("EGL_NON_CONFORMANT_CONFIG", "I", AccessFlags = 25)] public const int EGL_NON_CONFORMANT_CONFIG = 12369; /// <java-name> /// EGL_TRANSPARENT_RGB /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_RGB", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_RGB = 12370; /// <java-name> /// EGL_RGB_BUFFER /// </java-name> [Dot42.DexImport("EGL_RGB_BUFFER", "I", AccessFlags = 25)] public const int EGL_RGB_BUFFER = 12430; /// <java-name> /// EGL_LUMINANCE_BUFFER /// </java-name> [Dot42.DexImport("EGL_LUMINANCE_BUFFER", "I", AccessFlags = 25)] public const int EGL_LUMINANCE_BUFFER = 12431; /// <java-name> /// EGL_VENDOR /// </java-name> [Dot42.DexImport("EGL_VENDOR", "I", AccessFlags = 25)] public const int EGL_VENDOR = 12371; /// <java-name> /// EGL_VERSION /// </java-name> [Dot42.DexImport("EGL_VERSION", "I", AccessFlags = 25)] public const int EGL_VERSION = 12372; /// <java-name> /// EGL_EXTENSIONS /// </java-name> [Dot42.DexImport("EGL_EXTENSIONS", "I", AccessFlags = 25)] public const int EGL_EXTENSIONS = 12373; /// <java-name> /// EGL_HEIGHT /// </java-name> [Dot42.DexImport("EGL_HEIGHT", "I", AccessFlags = 25)] public const int EGL_HEIGHT = 12374; /// <java-name> /// EGL_WIDTH /// </java-name> [Dot42.DexImport("EGL_WIDTH", "I", AccessFlags = 25)] public const int EGL_WIDTH = 12375; /// <java-name> /// EGL_LARGEST_PBUFFER /// </java-name> [Dot42.DexImport("EGL_LARGEST_PBUFFER", "I", AccessFlags = 25)] public const int EGL_LARGEST_PBUFFER = 12376; /// <java-name> /// EGL_RENDER_BUFFER /// </java-name> [Dot42.DexImport("EGL_RENDER_BUFFER", "I", AccessFlags = 25)] public const int EGL_RENDER_BUFFER = 12422; /// <java-name> /// EGL_COLORSPACE /// </java-name> [Dot42.DexImport("EGL_COLORSPACE", "I", AccessFlags = 25)] public const int EGL_COLORSPACE = 12423; /// <java-name> /// EGL_ALPHA_FORMAT /// </java-name> [Dot42.DexImport("EGL_ALPHA_FORMAT", "I", AccessFlags = 25)] public const int EGL_ALPHA_FORMAT = 12424; /// <java-name> /// EGL_HORIZONTAL_RESOLUTION /// </java-name> [Dot42.DexImport("EGL_HORIZONTAL_RESOLUTION", "I", AccessFlags = 25)] public const int EGL_HORIZONTAL_RESOLUTION = 12432; /// <java-name> /// EGL_VERTICAL_RESOLUTION /// </java-name> [Dot42.DexImport("EGL_VERTICAL_RESOLUTION", "I", AccessFlags = 25)] public const int EGL_VERTICAL_RESOLUTION = 12433; /// <java-name> /// EGL_PIXEL_ASPECT_RATIO /// </java-name> [Dot42.DexImport("EGL_PIXEL_ASPECT_RATIO", "I", AccessFlags = 25)] public const int EGL_PIXEL_ASPECT_RATIO = 12434; /// <java-name> /// EGL_SINGLE_BUFFER /// </java-name> [Dot42.DexImport("EGL_SINGLE_BUFFER", "I", AccessFlags = 25)] public const int EGL_SINGLE_BUFFER = 12421; /// <java-name> /// EGL_CORE_NATIVE_ENGINE /// </java-name> [Dot42.DexImport("EGL_CORE_NATIVE_ENGINE", "I", AccessFlags = 25)] public const int EGL_CORE_NATIVE_ENGINE = 12379; /// <java-name> /// EGL_DRAW /// </java-name> [Dot42.DexImport("EGL_DRAW", "I", AccessFlags = 25)] public const int EGL_DRAW = 12377; /// <java-name> /// EGL_READ /// </java-name> [Dot42.DexImport("EGL_READ", "I", AccessFlags = 25)] public const int EGL_READ = 12378; /// <java-name> /// EGL_DONT_CARE /// </java-name> [Dot42.DexImport("EGL_DONT_CARE", "I", AccessFlags = 25)] public const int EGL_DONT_CARE = -1; /// <java-name> /// EGL_PBUFFER_BIT /// </java-name> [Dot42.DexImport("EGL_PBUFFER_BIT", "I", AccessFlags = 25)] public const int EGL_PBUFFER_BIT = 1; /// <java-name> /// EGL_PIXMAP_BIT /// </java-name> [Dot42.DexImport("EGL_PIXMAP_BIT", "I", AccessFlags = 25)] public const int EGL_PIXMAP_BIT = 2; /// <java-name> /// EGL_WINDOW_BIT /// </java-name> [Dot42.DexImport("EGL_WINDOW_BIT", "I", AccessFlags = 25)] public const int EGL_WINDOW_BIT = 4; /// <java-name> /// EGL_DEFAULT_DISPLAY /// </java-name> [Dot42.DexImport("EGL_DEFAULT_DISPLAY", "Ljava/lang/Object;", AccessFlags = 25)] public static readonly object EGL_DEFAULT_DISPLAY; /// <java-name> /// EGL_NO_DISPLAY /// </java-name> [Dot42.DexImport("EGL_NO_DISPLAY", "Ljavax/microedition/khronos/egl/EGLDisplay;", AccessFlags = 25)] public static readonly global::Javax.Microedition.Khronos.Egl.EGLDisplay EGL_NO_DISPLAY; /// <java-name> /// EGL_NO_CONTEXT /// </java-name> [Dot42.DexImport("EGL_NO_CONTEXT", "Ljavax/microedition/khronos/egl/EGLContext;", AccessFlags = 25)] public static readonly global::Javax.Microedition.Khronos.Egl.EGLContext EGL_NO_CONTEXT; /// <java-name> /// EGL_NO_SURFACE /// </java-name> [Dot42.DexImport("EGL_NO_SURFACE", "Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 25)] public static readonly global::Javax.Microedition.Khronos.Egl.EGLSurface EGL_NO_SURFACE; } /// <java-name> /// javax/microedition/khronos/egl/EGL10 /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL10", AccessFlags = 1537)] public partial interface IEGL10 : global::Javax.Microedition.Khronos.Egl.IEGL /* scope: __dot42__ */ { /// <java-name> /// eglChooseConfig /// </java-name> [Dot42.DexImport("eglChooseConfig", "(Ljavax/microedition/khronos/egl/EGLDisplay;[I[Ljavax/microedition/khronos/egl/EG" + "LConfig;I[I)Z", AccessFlags = 1025)] bool EglChooseConfig(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, int[] attrib_list, global::Javax.Microedition.Khronos.Egl.EGLConfig[] configs, int config_size, int[] num_config) /* MethodBuilder.Create */ ; /// <java-name> /// eglCopyBuffers /// </java-name> [Dot42.DexImport("eglCopyBuffers", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;Ljava/lang/Object;)Z", AccessFlags = 1025)] bool EglCopyBuffers(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface, object native_pixmap) /* MethodBuilder.Create */ ; /// <java-name> /// eglCreateContext /// </java-name> [Dot42.DexImport("eglCreateContext", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;Ljavax/microedition/khronos/egl/EGLContext;[I)Ljavax/microedition/khronos/e" + "gl/EGLContext;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLContext EglCreateContext(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, global::Javax.Microedition.Khronos.Egl.EGLContext share_context, int[] attrib_list) /* MethodBuilder.Create */ ; /// <java-name> /// eglCreatePbufferSurface /// </java-name> [Dot42.DexImport("eglCreatePbufferSurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;[I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLSurface EglCreatePbufferSurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, int[] attrib_list) /* MethodBuilder.Create */ ; /// <java-name> /// eglCreatePixmapSurface /// </java-name> [Dot42.DexImport("eglCreatePixmapSurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;Ljava/lang/Object;[I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLSurface EglCreatePixmapSurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, object native_pixmap, int[] attrib_list) /* MethodBuilder.Create */ ; /// <java-name> /// eglCreateWindowSurface /// </java-name> [Dot42.DexImport("eglCreateWindowSurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;Ljava/lang/Object;[I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLSurface EglCreateWindowSurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, object native_window, int[] attrib_list) /* MethodBuilder.Create */ ; /// <java-name> /// eglDestroyContext /// </java-name> [Dot42.DexImport("eglDestroyContext", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "ntext;)Z", AccessFlags = 1025)] bool EglDestroyContext(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLContext context) /* MethodBuilder.Create */ ; /// <java-name> /// eglDestroySurface /// </java-name> [Dot42.DexImport("eglDestroySurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;)Z", AccessFlags = 1025)] bool EglDestroySurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetConfigAttrib /// </java-name> [Dot42.DexImport("eglGetConfigAttrib", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;I[I)Z", AccessFlags = 1025)] bool EglGetConfigAttrib(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, int attribute, int[] value) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetConfigs /// </java-name> [Dot42.DexImport("eglGetConfigs", "(Ljavax/microedition/khronos/egl/EGLDisplay;[Ljavax/microedition/khronos/egl/EGLC" + "onfig;I[I)Z", AccessFlags = 1025)] bool EglGetConfigs(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig[] configs, int config_size, int[] num_config) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetCurrentContext /// </java-name> [Dot42.DexImport("eglGetCurrentContext", "()Ljavax/microedition/khronos/egl/EGLContext;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLContext EglGetCurrentContext() /* MethodBuilder.Create */ ; /// <java-name> /// eglGetCurrentDisplay /// </java-name> [Dot42.DexImport("eglGetCurrentDisplay", "()Ljavax/microedition/khronos/egl/EGLDisplay;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLDisplay EglGetCurrentDisplay() /* MethodBuilder.Create */ ; /// <java-name> /// eglGetCurrentSurface /// </java-name> [Dot42.DexImport("eglGetCurrentSurface", "(I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLSurface EglGetCurrentSurface(int readdraw) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetDisplay /// </java-name> [Dot42.DexImport("eglGetDisplay", "(Ljava/lang/Object;)Ljavax/microedition/khronos/egl/EGLDisplay;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLDisplay EglGetDisplay(object native_display) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetError /// </java-name> [Dot42.DexImport("eglGetError", "()I", AccessFlags = 1025)] int EglGetError() /* MethodBuilder.Create */ ; /// <java-name> /// eglInitialize /// </java-name> [Dot42.DexImport("eglInitialize", "(Ljavax/microedition/khronos/egl/EGLDisplay;[I)Z", AccessFlags = 1025)] bool EglInitialize(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, int[] major_minor) /* MethodBuilder.Create */ ; /// <java-name> /// eglMakeCurrent /// </java-name> [Dot42.DexImport("eglMakeCurrent", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;Ljavax/microedition/khronos/egl/EGLSurface;Ljavax/microedition/khronos/egl" + "/EGLContext;)Z", AccessFlags = 1025)] bool EglMakeCurrent(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface draw, global::Javax.Microedition.Khronos.Egl.EGLSurface read, global::Javax.Microedition.Khronos.Egl.EGLContext context) /* MethodBuilder.Create */ ; /// <java-name> /// eglQueryContext /// </java-name> [Dot42.DexImport("eglQueryContext", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "ntext;I[I)Z", AccessFlags = 1025)] bool EglQueryContext(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLContext context, int attribute, int[] value) /* MethodBuilder.Create */ ; /// <java-name> /// eglQueryString /// </java-name> [Dot42.DexImport("eglQueryString", "(Ljavax/microedition/khronos/egl/EGLDisplay;I)Ljava/lang/String;", AccessFlags = 1025)] string EglQueryString(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, int name) /* MethodBuilder.Create */ ; /// <java-name> /// eglQuerySurface /// </java-name> [Dot42.DexImport("eglQuerySurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;I[I)Z", AccessFlags = 1025)] bool EglQuerySurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface, int attribute, int[] value) /* MethodBuilder.Create */ ; /// <java-name> /// eglSwapBuffers /// </java-name> [Dot42.DexImport("eglSwapBuffers", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;)Z", AccessFlags = 1025)] bool EglSwapBuffers(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface) /* MethodBuilder.Create */ ; /// <java-name> /// eglTerminate /// </java-name> [Dot42.DexImport("eglTerminate", "(Ljavax/microedition/khronos/egl/EGLDisplay;)Z", AccessFlags = 1025)] bool EglTerminate(global::Javax.Microedition.Khronos.Egl.EGLDisplay display) /* MethodBuilder.Create */ ; /// <java-name> /// eglWaitGL /// </java-name> [Dot42.DexImport("eglWaitGL", "()Z", AccessFlags = 1025)] bool EglWaitGL() /* MethodBuilder.Create */ ; /// <java-name> /// eglWaitNative /// </java-name> [Dot42.DexImport("eglWaitNative", "(ILjava/lang/Object;)Z", AccessFlags = 1025)] bool EglWaitNative(int engine, object bindTarget) /* MethodBuilder.Create */ ; } /// <java-name> /// javax/microedition/khronos/egl/EGL11 /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL11", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IEGL11Constants /* scope: __dot42__ */ { /// <java-name> /// EGL_CONTEXT_LOST /// </java-name> [Dot42.DexImport("EGL_CONTEXT_LOST", "I", AccessFlags = 25)] public const int EGL_CONTEXT_LOST = 12302; } /// <java-name> /// javax/microedition/khronos/egl/EGL11 /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL11", AccessFlags = 1537)] public partial interface IEGL11 : global::Javax.Microedition.Khronos.Egl.IEGL10 /* scope: __dot42__ */ { } /// <java-name> /// javax/microedition/khronos/egl/EGLContext /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGLContext", AccessFlags = 1057)] public abstract partial class EGLContext /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public EGLContext() /* MethodBuilder.Create */ { } /// <java-name> /// getEGL /// </java-name> [Dot42.DexImport("getEGL", "()Ljavax/microedition/khronos/egl/EGL;", AccessFlags = 9)] public static global::Javax.Microedition.Khronos.Egl.IEGL GetEGL() /* MethodBuilder.Create */ { return default(global::Javax.Microedition.Khronos.Egl.IEGL); } /// <java-name> /// getGL /// </java-name> [Dot42.DexImport("getGL", "()Ljavax/microedition/khronos/opengles/GL;", AccessFlags = 1025)] public abstract global::Javax.Microedition.Khronos.Opengles.IGL GetGL() /* MethodBuilder.Create */ ; /// <java-name> /// getEGL /// </java-name> public static global::Javax.Microedition.Khronos.Egl.IEGL EGL { [Dot42.DexImport("getEGL", "()Ljavax/microedition/khronos/egl/EGL;", AccessFlags = 9)] get{ return GetEGL(); } } /// <java-name> /// getGL /// </java-name> public global::Javax.Microedition.Khronos.Opengles.IGL GL { [Dot42.DexImport("getGL", "()Ljavax/microedition/khronos/opengles/GL;", AccessFlags = 1025)] get{ return GetGL(); } } } /// <java-name> /// javax/microedition/khronos/egl/EGLSurface /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGLSurface", AccessFlags = 1057)] public abstract partial class EGLSurface /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public EGLSurface() /* MethodBuilder.Create */ { } } /// <java-name> /// javax/microedition/khronos/egl/EGLDisplay /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGLDisplay", AccessFlags = 1057)] public abstract partial class EGLDisplay /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public EGLDisplay() /* MethodBuilder.Create */ { } } /// <java-name> /// javax/microedition/khronos/egl/EGL /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL", AccessFlags = 1537)] public partial interface IEGL /* scope: __dot42__ */ { } }
using System; using System.Linq; using System.Collections.Generic; using ColossalFramework; using ColossalFramework.Plugins; using Random = UnityEngine.Random; namespace AutoLineColor.Naming { internal class LondonNamingStrategy : INamingStrategy { private static string[] _trains = { "{0}", "{0} Service", "{0} Rail", "{0} Railway", "{0} Flyer", "{0} Zephyr", "{0} Rocket", "{0} Arrow", "{0} Special", "Spirit of {0}", "Pride of {0}", }; public string GetName(TransportLine transportLine) { switch (transportLine.Info.m_transportType) { case TransportInfo.TransportType.Bus: return GetBusLineName (transportLine); case TransportInfo.TransportType.Metro: return GetMetroLineName (transportLine); default: return GetTrainLineName (transportLine); } } private void AnalyzeLine(TransportLine transportLine, List<string> districtNames, out int districtCount, out int stopCount, out bool nonDistrict) { var theNetManager = Singleton<NetManager>.instance; var theDistrictManager = Singleton<DistrictManager>.instance; var stop = transportLine.m_stops; var firstStop = stop; stopCount = 0; districtCount = 0; nonDistrict = false; do { var stopInfo = theNetManager.m_nodes.m_buffer[stop]; var district = theDistrictManager.GetDistrict(stopInfo.m_position); if (district == 0) { nonDistrict = true; } else { var districtName = theDistrictManager.GetDistrictName(district).Trim(); if (!districtNames.Contains(districtName)) { districtNames.Add(districtName); districtCount++; } } stop = TransportLine.GetNextStop (stop); stopCount++; } while (stopCount < 25 && stop != firstStop); } private static string GetInitials(string words) { string initials = words[0].ToString(); for (int i = 0; i < words.Length - 1; i++) { if (words [i] == ' ') { initials += words[i + 1]; } } return initials; } private static List<string> GetExistingNames() { var names = new List<string>(); var theTransportManager = Singleton<TransportManager>.instance; var theInstanceManager = Singleton<InstanceManager>.instance; var lines = theTransportManager.m_lines.m_buffer; for (ushort lineIndex = 0; lineIndex < lines.Length - 1; lineIndex++) { if (lines[lineIndex].HasCustomName()) { string name = theInstanceManager.GetName(new InstanceID { TransportLine = lineIndex }); if (!String.IsNullOrEmpty(name)) { names.Add(name); } } } return names; } private static List<string> GetNumbers(List<string> names) { var numbers = new List<string>(); foreach (var name in names) { numbers.Add(FirstWord(name)); } return numbers; } private static string FirstWord(string words) { return words.Contains(" ") ? (words.Substring(0, words.IndexOf(" "))) : words; } private static string TryBakerlooify(string word1, string word2) { int offset1 = Math.Min(word1.Length - 1, Math.Max(word1.Length / 2, 4)); int offset2 = word2.Length / 4; int length2 = Math.Max(word2.Length / 2, 3); string substring2 = word2.Substring(offset2, length2); for (int offset = offset1; offset < word1.Length; offset++) { if (substring2.IndexOf(word1[offset]) >= 0) { return word1.Substring(0, offset) + word2.Substring(offset2 + substring2.IndexOf(word1[offset])); } } return null; } /* * Bus line numbers are based on district: * * Given districts "Hamilton Park", "Ivy Square", "King District" in a city called "Springwood", bus line names look like: * * HP43 Local * 22 Hamilton Park * 345 Ivy to King Express * 9 Hamilton, Ivy and King * 6 Springwood Express */ private string GetBusLineName(TransportLine transportLine) { var districtNames = new List<string>(); bool nonDistrict; int districtCount; int stopCount; AnalyzeLine(transportLine, districtNames, out districtCount, out stopCount, out nonDistrict); string prefix = null; int number; string name = null; string suffix = null; var existingNames = GetExistingNames(); var existingNumbers = GetNumbers(existingNames); // Work out the bus number (and prefix) if (!nonDistrict && districtCount == 1) { /* District Initials */ prefix = GetInitials(districtNames[0]); number = 0; string prefixed_number; do { number++; prefixed_number = String.Format("{0}{1}", prefix, number); } while (existingNumbers.Contains(prefixed_number)); } else { int step; if (stopCount < 15) { number = Random.Range(100, 900); step = Random.Range(7, 20); } else if (stopCount < 30) { number = Random.Range(20, 100); step = Random.Range(2, 10); } else { number = Random.Range(1, 20); step = Random.Range(1, 4); } while (existingNumbers.Contains(number.ToString())) { number += step; } } // Work out the bus name if (districtCount == 1) { name = nonDistrict ? districtNames[0] : "Local"; } if (districtCount == 2) { name = String.Format("{0} to {1}", FirstWord(districtNames[0]), FirstWord(districtNames[1])); } if (districtCount == 3) { name = String.Format("{0}, {1} and {2}", FirstWord(districtNames[0]), FirstWord(districtNames[1]), FirstWord(districtNames[2])); } if (districtCount == 0 || districtCount > 3) { var theSimulationManager = Singleton<SimulationManager>.instance; name = theSimulationManager.m_metaData.m_CityName; } if (stopCount <= 4) { suffix = "Express"; } string lineName = String.Format("{0}{1}", prefix ?? "", number); if (!String.IsNullOrEmpty(name)) { lineName += " " + name; } if (!String.IsNullOrEmpty(suffix)) { lineName += " " + suffix; } return lineName; } /* * Metro line names are based on district, with generic names from a list thrown in. * * Given districts "Manor Park", "Ivy Square", "Hickory District", metro line names look like: * * Manor Line * Ivy Loop Line * Hickory & Ivy Line * Hickory, Manor & Ivy Line * Foxtrot Line * * There's also some attempt to "Bakerlooify" line names. No idea how well that will work. */ private string GetMetroLineName(TransportLine transportLine) { var districtNames = new List<string>(); bool nonDistrict; int districtCount; int stopCount; AnalyzeLine(transportLine, districtNames, out districtCount, out stopCount, out nonDistrict); string name = null; var districtFirstNames = districtNames.Select(FirstWord).ToList(); var existingNames = GetExistingNames(); int count = 0; if (districtCount == 1) { name = districtNames[0]; } else if (districtCount == 2) { if (districtFirstNames[0].Equals(districtFirstNames[1])) { name = districtFirstNames[0]; } else { name = TryBakerlooify(districtFirstNames[0], districtFirstNames[1]) ?? TryBakerlooify(districtFirstNames[1], districtFirstNames[0]) ?? String.Format("{0} & {1}", districtFirstNames[0], districtFirstNames[1]); } } else if (districtCount >= 3) { int totalLength = districtFirstNames.Sum(d => d.Length); if (totalLength < 20) { var districtFirstNamesArray = districtFirstNames.ToArray(); name = String.Format("{0} & {1}", String.Join(", ", districtFirstNamesArray, 0, districtFirstNamesArray.Length - 1), districtFirstNamesArray[districtFirstNamesArray.Length - 1]); } } var lineName = name == null ? "Metro Line" : String.Format("{0} Line", name); while (name == null || existingNames.Contains(lineName)) { name = GenericNames.GetGenericName(count / 2); lineName = String.Format("{0} Line", name); count++; } return lineName; } /* * Train line names are based on the British designations, with some liberties taken. * * The format is AXNN Name: * * A is the number of districts the train stops at. * X is the first letter of the last district, or X if the train stops outside of a district. * NN are random digits. * * The name is based on the district names. */ private string GetTrainLineName(TransportLine transportLine) { var districtNames = new List<string>(); bool nonDistrict; int districtCount; int stopCount; AnalyzeLine(transportLine, districtNames, out districtCount, out stopCount, out nonDistrict); string ident = null; int number = Random.Range(1, 90); string name = null; var districtFirstNames = districtNames.Select(FirstWord).ToList(); var existingNames = GetExistingNames(); var existingNumbers = GetNumbers(existingNames); var lastDistrictName = districtNames.LastOrDefault(); if (String.IsNullOrEmpty(lastDistrictName)) { lastDistrictName = "Z"; } ident = String.Format("{0}{1}", districtCount, nonDistrict ? "X" : lastDistrictName.Substring(0, 1)); if (districtCount == 0) { var theSimulationManager = Singleton<SimulationManager>.instance; name = String.Format(_trains[Random.Range(0, _trains.Length)], theSimulationManager.m_metaData.m_CityName); } else if (districtCount == 1) { name = String.Format(_trains[Random.Range(0, _trains.Length)], districtNames[0]); } else if (districtCount == 2) { if (districtFirstNames[0].Equals(districtFirstNames[1])) { name = districtFirstNames[0]; } else if (stopCount == 2) { name = String.Format("{0} {1} Shuttle", districtFirstNames[0], districtFirstNames[1]); } else if (!nonDistrict) { name = String.Format("{0} {1} Express", districtFirstNames[0], districtFirstNames[1]); } else { name = String.Format("{0} via {1}", districtFirstNames[0], districtFirstNames[1]); } } else { int totalLength = districtFirstNames.Sum(d => d.Length); if (totalLength < 15) { var districtFirstNamesArray = districtFirstNames.ToArray(); name = String.Format("{0} and {1} via {2}", String.Join(", ", districtFirstNamesArray, 0, districtFirstNamesArray.Length - 2), districtFirstNamesArray[districtFirstNamesArray.Length - 1], districtFirstNamesArray[districtFirstNamesArray.Length - 2]); } else { name = String.Format(_trains[Random.Range(0, _trains.Length)], districtNames.First()); } } var lineNumber = String.Format("{0}{1:00}", ident, number); while (existingNumbers.Contains(lineNumber)) { number++; lineNumber = String.Format("{0}{1:00}", ident, number); } return String.Format("{0} {1}", lineNumber, name); } } }
// 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. //Zip Spec here: http://www.pkware.com/documents/casestudies/APPNOTE.TXT using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Text; namespace System.IO.Compression { public class ZipArchive : IDisposable { #region Fields private Stream _archiveStream; private ZipArchiveEntry _archiveStreamOwner; private BinaryReader _archiveReader; private ZipArchiveMode _mode; private List<ZipArchiveEntry> _entries; private ReadOnlyCollection<ZipArchiveEntry> _entriesCollection; private Dictionary<String, ZipArchiveEntry> _entriesDictionary; private Boolean _readEntries; private Boolean _leaveOpen; private Int64 _centralDirectoryStart; //only valid after ReadCentralDirectory private Boolean _isDisposed; private UInt32 _numberOfThisDisk; //only valid after ReadCentralDirectory private Int64 _expectedNumberOfEntries; private Stream _backingStream; private Byte[] _archiveComment; private Encoding _entryNameEncoding; #if DEBUG_FORCE_ZIP64 public Boolean _forceZip64; #endif #endregion Fields #region Public/Protected APIs /// <summary> /// Initializes a new instance of ZipArchive on the given stream for reading. /// </summary> /// <exception cref="ArgumentException">The stream is already closed or does not support reading.</exception> /// <exception cref="ArgumentNullException">The stream is null.</exception> /// <exception cref="InvalidDataException">The contents of the stream could not be interpreted as a Zip archive.</exception> /// <param name="stream">The stream containing the archive to be read.</param> public ZipArchive(Stream stream) : this(stream, ZipArchiveMode.Read, leaveOpen: false, entryNameEncoding: null) { } /// <summary> /// Initializes a new instance of ZipArchive on the given stream in the specified mode. /// </summary> /// <exception cref="ArgumentException">The stream is already closed. -or- mode is incompatible with the capabilities of the stream.</exception> /// <exception cref="ArgumentNullException">The stream is null.</exception> /// <exception cref="ArgumentOutOfRangeException">mode specified an invalid value.</exception> /// <exception cref="InvalidDataException">The contents of the stream could not be interpreted as a Zip file. -or- mode is Update and an entry is missing from the archive or is corrupt and cannot be read. -or- mode is Update and an entry is too large to fit into memory.</exception> /// <param name="stream">The input or output stream.</param> /// <param name="mode">See the description of the ZipArchiveMode enum. Read requires the stream to support reading, Create requires the stream to support writing, and Update requires the stream to support reading, writing, and seeking.</param> public ZipArchive(Stream stream, ZipArchiveMode mode) : this(stream, mode, leaveOpen: false, entryNameEncoding: null) { } /// <summary> /// Initializes a new instance of ZipArchive on the given stream in the specified mode, specifying whether to leave the stream open. /// </summary> /// <exception cref="ArgumentException">The stream is already closed. -or- mode is incompatible with the capabilities of the stream.</exception> /// <exception cref="ArgumentNullException">The stream is null.</exception> /// <exception cref="ArgumentOutOfRangeException">mode specified an invalid value.</exception> /// <exception cref="InvalidDataException">The contents of the stream could not be interpreted as a Zip file. -or- mode is Update and an entry is missing from the archive or is corrupt and cannot be read. -or- mode is Update and an entry is too large to fit into memory.</exception> /// <param name="stream">The input or output stream.</param> /// <param name="mode">See the description of the ZipArchiveMode enum. Read requires the stream to support reading, Create requires the stream to support writing, and Update requires the stream to support reading, writing, and seeking.</param> /// <param name="leaveOpen">true to leave the stream open upon disposing the ZipArchive, otherwise false.</param> public ZipArchive(Stream stream, ZipArchiveMode mode, Boolean leaveOpen) : this(stream, mode, leaveOpen, entryNameEncoding: null) { } /// <summary> /// Initializes a new instance of ZipArchive on the given stream in the specified mode, specifying whether to leave the stream open. /// </summary> /// <exception cref="ArgumentException">The stream is already closed. -or- mode is incompatible with the capabilities of the stream.</exception> /// <exception cref="ArgumentNullException">The stream is null.</exception> /// <exception cref="ArgumentOutOfRangeException">mode specified an invalid value.</exception> /// <exception cref="InvalidDataException">The contents of the stream could not be interpreted as a Zip file. -or- mode is Update and an entry is missing from the archive or is corrupt and cannot be read. -or- mode is Update and an entry is too large to fit into memory.</exception> /// <param name="stream">The input or output stream.</param> /// <param name="mode">See the description of the ZipArchiveMode enum. Read requires the stream to support reading, Create requires the stream to support writing, and Update requires the stream to support reading, writing, and seeking.</param> /// <param name="leaveOpen">true to leave the stream open upon disposing the ZipArchive, otherwise false.</param> /// <param name="entryNameEncoding">The encoding to use when reading or writing entry names in this ZipArchive. /// /// <para>NOTE: Specifying this parameter to values other than <c>null</c> is discouraged. /// However, this may be necessary for interoperability with ZIP archive tools and libraries that do not correctly support /// UTF-8 encoding for entry names.<br /> /// This value is used as follows:</para> /// <para><strong>Reading (opening) ZIP archive files:</strong></para> /// <para>If <c>entryNameEncoding</c> is not specified (<c>== null</c>):</para> /// <list> /// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header is <em>not</em> set, /// use the current system default code page (<c>Encoding.Default</c>) in order to decode the entry name.</item> /// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header <em>is</em> set, /// use UTF-8 (<c>Encoding.UTF8</c>) in order to decode the entry name.</item> /// </list> /// <para>If <c>entryNameEncoding</c> is specified (<c>!= null</c>):</para> /// <list> /// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header is <em>not</em> set, /// use the specified <c>entryNameEncoding</c> in order to decode the entry name.</item> /// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header <em>is</em> set, /// use UTF-8 (<c>Encoding.UTF8</c>) in order to decode the entry name.</item> /// </list> /// <para><strong>Writing (saving) ZIP archive files:</strong></para> /// <para>If <c>entryNameEncoding</c> is not specified (<c>== null</c>):</para> /// <list> /// <item>For entry names that contain characters outside the ASCII range, /// the language encoding flag (EFS) will be set in the general purpose bit flag of the local file header, /// and UTF-8 (<c>Encoding.UTF8</c>) will be used in order to encode the entry name into bytes.</item> /// <item>For entry names that do not contain characters outside the ASCII range, /// the language encoding flag (EFS) will not be set in the general purpose bit flag of the local file header, /// and the current system default code page (<c>Encoding.Default</c>) will be used to encode the entry names into bytes.</item> /// </list> /// <para>If <c>entryNameEncoding</c> is specified (<c>!= null</c>):</para> /// <list> /// <item>The specified <c>entryNameEncoding</c> will always be used to encode the entry names into bytes. /// The language encoding flag (EFS) in the general purpose bit flag of the local file header will be set if and only /// if the specified <c>entryNameEncoding</c> is a UTF-8 encoding.</item> /// </list> /// <para>Note that Unicode encodings other than UTF-8 may not be currently used for the <c>entryNameEncoding</c>, /// otherwise an <see cref="ArgumentException"/> is thrown.</para> /// </param> /// <exception cref="ArgumentException">If a Unicode encoding other than UTF-8 is specified for the <code>entryNameEncoding</code>.</exception> public ZipArchive(Stream stream, ZipArchiveMode mode, Boolean leaveOpen, Encoding entryNameEncoding) { if (stream == null) throw new ArgumentNullException(nameof(stream)); Contract.EndContractBlock(); this.EntryNameEncoding = entryNameEncoding; this.Init(stream, mode, leaveOpen); } /// <summary> /// The collection of entries that are currently in the ZipArchive. This may not accurately represent the actual entries that are present in the underlying file or stream. /// </summary> /// <exception cref="NotSupportedException">The ZipArchive does not support reading.</exception> /// <exception cref="ObjectDisposedException">The ZipArchive has already been closed.</exception> /// <exception cref="InvalidDataException">The Zip archive is corrupt and the entries cannot be retrieved.</exception> public ReadOnlyCollection<ZipArchiveEntry> Entries { get { Contract.Ensures(Contract.Result<ReadOnlyCollection<ZipArchiveEntry>>() != null); if (_mode == ZipArchiveMode.Create) throw new NotSupportedException(SR.EntriesInCreateMode); ThrowIfDisposed(); EnsureCentralDirectoryRead(); return _entriesCollection; } } /// <summary> /// The ZipArchiveMode that the ZipArchive was initialized with. /// </summary> public ZipArchiveMode Mode { get { Contract.Ensures( Contract.Result<ZipArchiveMode>() == ZipArchiveMode.Create || Contract.Result<ZipArchiveMode>() == ZipArchiveMode.Read || Contract.Result<ZipArchiveMode>() == ZipArchiveMode.Update); return _mode; } } /// <summary> /// Creates an empty entry in the Zip archive with the specified entry name. /// There are no restrictions on the names of entries. /// The last write time of the entry is set to the current time. /// If an entry with the specified name already exists in the archive, a second entry will be created that has an identical name. /// Since no <code>CompressionLevel</code> is specified, the default provided by the implementation of the underlying compression /// algorithm will be used; the <code>ZipArchive</code> will not impose its own default. /// (Currently, the underlying compression algorithm is provided by the <code>System.IO.Compression.DeflateStream</code> class.) /// </summary> /// <exception cref="ArgumentException">entryName is a zero-length string.</exception> /// <exception cref="ArgumentNullException">entryName is null.</exception> /// <exception cref="NotSupportedException">The ZipArchive does not support writing.</exception> /// <exception cref="ObjectDisposedException">The ZipArchive has already been closed.</exception> /// <param name="entryName">A path relative to the root of the archive, indicating the name of the entry to be created.</param> /// <returns>A wrapper for the newly created file entry in the archive.</returns> public ZipArchiveEntry CreateEntry(String entryName) { Contract.Ensures(Contract.Result<ZipArchiveEntry>() != null); Contract.EndContractBlock(); return DoCreateEntry(entryName, null); } /// <summary> /// Creates an empty entry in the Zip archive with the specified entry name. There are no restrictions on the names of entries. The last write time of the entry is set to the current time. If an entry with the specified name already exists in the archive, a second entry will be created that has an identical name. /// </summary> /// <exception cref="ArgumentException">entryName is a zero-length string.</exception> /// <exception cref="ArgumentNullException">entryName is null.</exception> /// <exception cref="NotSupportedException">The ZipArchive does not support writing.</exception> /// <exception cref="ObjectDisposedException">The ZipArchive has already been closed.</exception> /// <param name="entryName">A path relative to the root of the archive, indicating the name of the entry to be created.</param> /// <param name="compressionLevel">The level of the compression (speed/memory vs. compressed size trade-off).</param> /// <returns>A wrapper for the newly created file entry in the archive.</returns> public ZipArchiveEntry CreateEntry(String entryName, CompressionLevel compressionLevel) { Contract.Ensures(Contract.Result<ZipArchiveEntry>() != null); Contract.EndContractBlock(); return DoCreateEntry(entryName, compressionLevel); } /// <summary> /// Releases the unmanaged resources used by ZipArchive and optionally finishes writing the archive and releases the managed resources. /// </summary> /// <param name="disposing">true to finish writing the archive and release unmanaged and managed resources, false to release only unmanaged resources.</param> protected virtual void Dispose(Boolean disposing) { if (disposing && !_isDisposed) { try { switch (_mode) { case ZipArchiveMode.Read: break; case ZipArchiveMode.Create: case ZipArchiveMode.Update: default: Debug.Assert(_mode == ZipArchiveMode.Update || _mode == ZipArchiveMode.Create); WriteFile(); break; } } finally { CloseStreams(); _isDisposed = true; } } } /// <summary> /// Finishes writing the archive and releases all resources used by the ZipArchive object, unless the object was constructed with leaveOpen as true. Any streams from opened entries in the ZipArchive still open will throw exceptions on subsequent writes, as the underlying streams will have been closed. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Retrieves a wrapper for the file entry in the archive with the specified name. Names are compared using ordinal comparison. If there are multiple entries in the archive with the specified name, the first one found will be returned. /// </summary> /// <exception cref="ArgumentException">entryName is a zero-length string.</exception> /// <exception cref="ArgumentNullException">entryName is null.</exception> /// <exception cref="NotSupportedException">The ZipArchive does not support reading.</exception> /// <exception cref="ObjectDisposedException">The ZipArchive has already been closed.</exception> /// <exception cref="InvalidDataException">The Zip archive is corrupt and the entries cannot be retrieved.</exception> /// <param name="entryName">A path relative to the root of the archive, identifying the desired entry.</param> /// <returns>A wrapper for the file entry in the archive. If no entry in the archive exists with the specified name, null will be returned.</returns> public ZipArchiveEntry GetEntry(String entryName) { if (entryName == null) throw new ArgumentNullException(nameof(entryName)); Contract.EndContractBlock(); if (_mode == ZipArchiveMode.Create) throw new NotSupportedException(SR.EntriesInCreateMode); EnsureCentralDirectoryRead(); ZipArchiveEntry result; _entriesDictionary.TryGetValue(entryName, out result); return result; } #endregion Public/Protected APIs #region Privates internal BinaryReader ArchiveReader { get { return _archiveReader; } } internal Stream ArchiveStream { get { return _archiveStream; } } internal UInt32 NumberOfThisDisk { get { return _numberOfThisDisk; } } internal Encoding EntryNameEncoding { get { return _entryNameEncoding; } private set { // value == null is fine. This means the user does not want to overwrite default encoding picking logic. // The Zip file spec [http://www.pkware.com/documents/casestudies/APPNOTE.TXT] specifies a bit in the entry header // (specifically: the language encoding flag (EFS) in the general purpose bit flag of the local file header) that // basically says: UTF8 (1) or CP437 (0). But in reality, tools replace CP437 with "something else that is not UTF8". // For instance, the Windows Shell Zip tool takes "something else" to mean "the local system codepage". // We default to the same behaviour, but we let the user explicitly specify the encoding to use for cases where they // understand their use case well enough. // Since the definition of acceptable encodings for the "something else" case is in reality by convention, it is not // immediately clear, whether non-UTF8 Unicode encodings are acceptable. To determine that we would need to survey // what is currently being done in the field, but we do not have the time for it right now. // So, we artificially disallow non-UTF8 Unicode encodings for now to make sure we are not creating a compat burden // for something other tools do not support. If we realise in future that "something else" should include non-UTF8 // Unicode encodings, we can remove this restriction. if (value != null && (value.Equals(Encoding.BigEndianUnicode) || value.Equals(Encoding.Unicode) #if FEATURE_UTF32 || value.Equals(Encoding.UTF32) #endif // FEATURE_UTF32 #if FEATURE_UTF7 || value.Equals(Encoding.UTF7) #endif // FEATURE_UTF7 )) { throw new ArgumentException(SR.EntryNameEncodingNotSupported, nameof(EntryNameEncoding)); } _entryNameEncoding = value; } } private ZipArchiveEntry DoCreateEntry(String entryName, CompressionLevel? compressionLevel) { Contract.Ensures(Contract.Result<ZipArchiveEntry>() != null); if (entryName == null) throw new ArgumentNullException(nameof(entryName)); if (String.IsNullOrEmpty(entryName)) throw new ArgumentException(SR.CannotBeEmpty, nameof(entryName)); if (_mode == ZipArchiveMode.Read) throw new NotSupportedException(SR.CreateInReadMode); ThrowIfDisposed(); ZipArchiveEntry entry = compressionLevel.HasValue ? new ZipArchiveEntry(this, entryName, compressionLevel.Value) : new ZipArchiveEntry(this, entryName); AddEntry(entry); return entry; } internal void AcquireArchiveStream(ZipArchiveEntry entry) { //if a previous entry had held the stream but never wrote anything, we write their local header for them if (_archiveStreamOwner != null) { if (!_archiveStreamOwner.EverOpenedForWrite) { _archiveStreamOwner.WriteAndFinishLocalEntry(); } else { throw new IOException(SR.CreateModeCreateEntryWhileOpen); } } _archiveStreamOwner = entry; } private void AddEntry(ZipArchiveEntry entry) { _entries.Add(entry); String entryName = entry.FullName; if (!_entriesDictionary.ContainsKey(entryName)) { _entriesDictionary.Add(entryName, entry); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This code is used in a contract check.")] internal Boolean IsStillArchiveStreamOwner(ZipArchiveEntry entry) { return _archiveStreamOwner == entry; } internal void ReleaseArchiveStream(ZipArchiveEntry entry) { Debug.Assert(_archiveStreamOwner == entry); _archiveStreamOwner = null; } internal void RemoveEntry(ZipArchiveEntry entry) { _entries.Remove(entry); _entriesDictionary.Remove(entry.FullName); } internal void ThrowIfDisposed() { if (_isDisposed) throw new ObjectDisposedException(this.GetType().ToString()); } private void CloseStreams() { if (!_leaveOpen) { _archiveStream.Dispose(); if (_backingStream != null) _backingStream.Dispose(); if (_archiveReader != null) _archiveReader.Dispose(); } else { /* if _backingStream isn't null, that means we assigned the original stream they passed * us to _backingStream (which they requested we leave open), and _archiveStream was * the temporary copy that we needed */ if (_backingStream != null) _archiveStream.Dispose(); } } private void EnsureCentralDirectoryRead() { if (!_readEntries) { ReadCentralDirectory(); _readEntries = true; } } private void Init(Stream stream, ZipArchiveMode mode, Boolean leaveOpen) { Stream extraTempStream = null; try { _backingStream = null; //check stream against mode switch (mode) { case ZipArchiveMode.Create: if (!stream.CanWrite) throw new ArgumentException(SR.CreateModeCapabilities); break; case ZipArchiveMode.Read: if (!stream.CanRead) throw new ArgumentException(SR.ReadModeCapabilities); if (!stream.CanSeek) { _backingStream = stream; extraTempStream = stream = new MemoryStream(); _backingStream.CopyTo(stream); stream.Seek(0, SeekOrigin.Begin); } break; case ZipArchiveMode.Update: if (!stream.CanRead || !stream.CanWrite || !stream.CanSeek) throw new ArgumentException(SR.UpdateModeCapabilities); break; default: //still have to throw this, because stream constructor doesn't do mode argument checks throw new ArgumentOutOfRangeException(nameof(mode)); } _mode = mode; _archiveStream = stream; _archiveStreamOwner = null; if (mode == ZipArchiveMode.Create) _archiveReader = null; else _archiveReader = new BinaryReader(stream); _entries = new List<ZipArchiveEntry>(); _entriesCollection = new ReadOnlyCollection<ZipArchiveEntry>(_entries); _entriesDictionary = new Dictionary<String, ZipArchiveEntry>(); _readEntries = false; _leaveOpen = leaveOpen; _centralDirectoryStart = 0; //invalid until ReadCentralDirectory _isDisposed = false; _numberOfThisDisk = 0; //invalid until ReadCentralDirectory _archiveComment = null; switch (mode) { case ZipArchiveMode.Create: _readEntries = true; break; case ZipArchiveMode.Read: ReadEndOfCentralDirectory(); break; case ZipArchiveMode.Update: default: Debug.Assert(mode == ZipArchiveMode.Update); if (_archiveStream.Length == 0) { _readEntries = true; } else { ReadEndOfCentralDirectory(); EnsureCentralDirectoryRead(); foreach (ZipArchiveEntry entry in _entries) { entry.ThrowIfNotOpenable(false, true); } } break; } } catch { if (extraTempStream != null) extraTempStream.Dispose(); throw; } } private void ReadCentralDirectory() { try { //assume ReadEndOfCentralDirectory has been called and has populated _centralDirectoryStart _archiveStream.Seek(_centralDirectoryStart, SeekOrigin.Begin); Int64 numberOfEntries = 0; //read the central directory ZipCentralDirectoryFileHeader currentHeader; Boolean saveExtraFieldsAndComments = Mode == ZipArchiveMode.Update; while (ZipCentralDirectoryFileHeader.TryReadBlock(_archiveReader, saveExtraFieldsAndComments, out currentHeader)) { AddEntry(new ZipArchiveEntry(this, currentHeader)); numberOfEntries++; } if (numberOfEntries != _expectedNumberOfEntries) throw new InvalidDataException(SR.NumEntriesWrong); } catch (EndOfStreamException ex) { throw new InvalidDataException(SR.Format(SR.CentralDirectoryInvalid, ex)); } } //This function reads all the EOCD stuff it needs to find the offset to the start of the central directory //This offset gets put in _centralDirectoryStart and the number of this disk gets put in _numberOfThisDisk //Also does some verification that this isn't a split/spanned archive //Also checks that offset to CD isn't out of bounds private void ReadEndOfCentralDirectory() { try { //this seeks to the start of the end of central directory record _archiveStream.Seek(-ZipEndOfCentralDirectoryBlock.SizeOfBlockWithoutSignature, SeekOrigin.End); if (!ZipHelper.SeekBackwardsToSignature(_archiveStream, ZipEndOfCentralDirectoryBlock.SignatureConstant)) throw new InvalidDataException(SR.EOCDNotFound); Int64 eocdStart = _archiveStream.Position; //read the EOCD ZipEndOfCentralDirectoryBlock eocd; Boolean eocdProper = ZipEndOfCentralDirectoryBlock.TryReadBlock(_archiveReader, out eocd); Debug.Assert(eocdProper); //we just found this using the signature finder, so it should be okay if (eocd.NumberOfThisDisk != eocd.NumberOfTheDiskWithTheStartOfTheCentralDirectory) throw new InvalidDataException(SR.SplitSpanned); _numberOfThisDisk = eocd.NumberOfThisDisk; _centralDirectoryStart = eocd.OffsetOfStartOfCentralDirectoryWithRespectToTheStartingDiskNumber; if (eocd.NumberOfEntriesInTheCentralDirectory != eocd.NumberOfEntriesInTheCentralDirectoryOnThisDisk) throw new InvalidDataException(SR.SplitSpanned); _expectedNumberOfEntries = eocd.NumberOfEntriesInTheCentralDirectory; //only bother saving the comment if we are in update mode if (_mode == ZipArchiveMode.Update) _archiveComment = eocd.ArchiveComment; //only bother looking for zip64 EOCD stuff if we suspect it is needed because some value is FFFFFFFFF //because these are the only two values we need, we only worry about these //if we don't find the zip64 EOCD, we just give up and try to use the original values if (eocd.NumberOfThisDisk == ZipHelper.Mask16Bit || eocd.OffsetOfStartOfCentralDirectoryWithRespectToTheStartingDiskNumber == ZipHelper.Mask32Bit || eocd.NumberOfEntriesInTheCentralDirectory == ZipHelper.Mask16Bit) { //we need to look for zip 64 EOCD stuff //seek to the zip 64 EOCD locator _archiveStream.Seek(eocdStart - Zip64EndOfCentralDirectoryLocator.SizeOfBlockWithoutSignature, SeekOrigin.Begin); //if we don't find it, assume it doesn't exist and use data from normal eocd if (ZipHelper.SeekBackwardsToSignature(_archiveStream, Zip64EndOfCentralDirectoryLocator.SignatureConstant)) { //use locator to get to Zip64EOCD Zip64EndOfCentralDirectoryLocator locator; Boolean zip64eocdLocatorProper = Zip64EndOfCentralDirectoryLocator.TryReadBlock(_archiveReader, out locator); Debug.Assert(zip64eocdLocatorProper); //we just found this using the signature finder, so it should be okay if (locator.OffsetOfZip64EOCD > (UInt64)Int64.MaxValue) throw new InvalidDataException(SR.FieldTooBigOffsetToZip64EOCD); Int64 zip64EOCDOffset = (Int64)locator.OffsetOfZip64EOCD; _archiveStream.Seek(zip64EOCDOffset, SeekOrigin.Begin); //read Zip64EOCD Zip64EndOfCentralDirectoryRecord record; if (!Zip64EndOfCentralDirectoryRecord.TryReadBlock(_archiveReader, out record)) throw new InvalidDataException(SR.Zip64EOCDNotWhereExpected); _numberOfThisDisk = record.NumberOfThisDisk; if (record.NumberOfEntriesTotal > (UInt64)Int64.MaxValue) throw new InvalidDataException(SR.FieldTooBigNumEntries); if (record.OffsetOfCentralDirectory > (UInt64)Int64.MaxValue) throw new InvalidDataException(SR.FieldTooBigOffsetToCD); if (record.NumberOfEntriesTotal != record.NumberOfEntriesOnThisDisk) throw new InvalidDataException(SR.SplitSpanned); _expectedNumberOfEntries = (Int64)record.NumberOfEntriesTotal; _centralDirectoryStart = (Int64)record.OffsetOfCentralDirectory; } } if (_centralDirectoryStart > _archiveStream.Length) { throw new InvalidDataException(SR.FieldTooBigOffsetToCD); } } catch (EndOfStreamException ex) { throw new InvalidDataException(SR.CDCorrupt, ex); } catch (IOException ex) { throw new InvalidDataException(SR.CDCorrupt, ex); } } private void WriteFile() { //if we are in create mode, we always set readEntries to true in Init //if we are in update mode, we call EnsureCentralDirectoryRead, which sets readEntries to true Debug.Assert(_readEntries); if (_mode == ZipArchiveMode.Update) { List<ZipArchiveEntry> markedForDelete = new List<ZipArchiveEntry>(); foreach (ZipArchiveEntry entry in _entries) { if (!entry.LoadLocalHeaderExtraFieldAndCompressedBytesIfNeeded()) markedForDelete.Add(entry); } foreach (ZipArchiveEntry entry in markedForDelete) entry.Delete(); _archiveStream.Seek(0, SeekOrigin.Begin); _archiveStream.SetLength(0); } foreach (ZipArchiveEntry entry in _entries) { entry.WriteAndFinishLocalEntry(); } Int64 startOfCentralDirectory = _archiveStream.Position; foreach (ZipArchiveEntry entry in _entries) { entry.WriteCentralDirectoryFileHeader(); } Int64 sizeOfCentralDirectory = _archiveStream.Position - startOfCentralDirectory; WriteArchiveEpilogue(startOfCentralDirectory, sizeOfCentralDirectory); } //writes eocd, and if needed, zip 64 eocd, zip64 eocd locator //should only throw an exception in extremely exceptional cases because it is called from dispose private void WriteArchiveEpilogue(Int64 startOfCentralDirectory, Int64 sizeOfCentralDirectory) { //determine if we need Zip 64 Boolean needZip64 = false; if (startOfCentralDirectory >= UInt32.MaxValue || sizeOfCentralDirectory >= UInt32.MaxValue || _entries.Count >= ZipHelper.Mask16Bit #if DEBUG_FORCE_ZIP64 || _forceZip64 #endif ) needZip64 = true; //if we need zip 64, write zip 64 eocd and locator if (needZip64) { Int64 zip64EOCDRecordStart = _archiveStream.Position; Zip64EndOfCentralDirectoryRecord.WriteBlock(_archiveStream, _entries.Count, startOfCentralDirectory, sizeOfCentralDirectory); Zip64EndOfCentralDirectoryLocator.WriteBlock(_archiveStream, zip64EOCDRecordStart); } //write normal eocd ZipEndOfCentralDirectoryBlock.WriteBlock(_archiveStream, _entries.Count, startOfCentralDirectory, sizeOfCentralDirectory, _archiveComment); } #endregion Privates } }
/* * * 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. * */ /* Copyright (c) 2001, Dr Martin Porter Copyright (c) 2002, Richard Boulton All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * Neither the name of the copyright holders nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using Among = SF.Snowball.Among; using SnowballProgram = SF.Snowball.SnowballProgram; namespace SF.Snowball.Ext { /* * Generated class implementing code defined by a snowball script. */ public class HungarianStemmer : SnowballProgram { public HungarianStemmer() { a_0 = new Among[] { new Among("cs", -1, -1, "", null), new Among("dzs", -1, -1, "", null), new Among("gy", -1, -1, "", null), new Among("ly", -1, -1, "", null), new Among("ny", -1, -1, "", null), new Among("sz", -1, -1, "", null), new Among("ty", -1, -1, "", null), new Among("zs", -1, -1, "", null) }; a_1 = new Among[] { new Among("\u00E1", -1, 1, "", null), new Among("\u00E9", -1, 2, "", null) }; a_2 = new Among[] { new Among("bb", -1, -1, "", null), new Among("cc", -1, -1, "", null), new Among("dd", -1, -1, "", null), new Among("ff", -1, -1, "", null), new Among("gg", -1, -1, "", null), new Among("jj", -1, -1, "", null), new Among("kk", -1, -1, "", null), new Among("ll", -1, -1, "", null), new Among("mm", -1, -1, "", null), new Among("nn", -1, -1, "", null), new Among("pp", -1, -1, "", null), new Among("rr", -1, -1, "", null), new Among("ccs", -1, -1, "", null), new Among("ss", -1, -1, "", null), new Among("zzs", -1, -1, "", null), new Among("tt", -1, -1, "", null), new Among("vv", -1, -1, "", null), new Among("ggy", -1, -1, "", null), new Among("lly", -1, -1, "", null), new Among("nny", -1, -1, "", null), new Among("tty", -1, -1, "", null), new Among("ssz", -1, -1, "", null), new Among("zz", -1, -1, "", null) }; a_3 = new Among[] { new Among("al", -1, 1, "", null), new Among("el", -1, 2, "", null) }; a_4 = new Among[] { new Among("ba", -1, -1, "", null), new Among("ra", -1, -1, "", null), new Among("be", -1, -1, "", null), new Among("re", -1, -1, "", null), new Among("ig", -1, -1, "", null), new Among("nak", -1, -1, "", null), new Among("nek", -1, -1, "", null), new Among("val", -1, -1, "", null), new Among("vel", -1, -1, "", null), new Among("ul", -1, -1, "", null), new Among("n\u00E1l", -1, -1, "", null), new Among("n\u00E9l", -1, -1, "", null), new Among("b\u00F3l", -1, -1, "", null), new Among("r\u00F3l", -1, -1, "", null), new Among("t\u00F3l", -1, -1, "", null), new Among("b\u00F5l", -1, -1, "", null), new Among("r\u00F5l", -1, -1, "", null), new Among("t\u00F5l", -1, -1, "", null), new Among("\u00FCl", -1, -1, "", null), new Among("n", -1, -1, "", null), new Among("an", 19, -1, "", null), new Among("ban", 20, -1, "", null), new Among("en", 19, -1, "", null), new Among("ben", 22, -1, "", null), new Among("k\u00E9ppen", 22, -1, "", null), new Among("on", 19, -1, "", null), new Among("\u00F6n", 19, -1, "", null), new Among("k\u00E9pp", -1, -1, "", null), new Among("kor", -1, -1, "", null), new Among("t", -1, -1, "", null), new Among("at", 29, -1, "", null), new Among("et", 29, -1, "", null), new Among("k\u00E9nt", 29, -1, "", null), new Among("ank\u00E9nt", 32, -1, "", null), new Among("enk\u00E9nt", 32, -1, "", null), new Among("onk\u00E9nt", 32, -1, "", null), new Among("ot", 29, -1, "", null), new Among("\u00E9rt", 29, -1, "", null), new Among("\u00F6t", 29, -1, "", null), new Among("hez", -1, -1, "", null), new Among("hoz", -1, -1, "", null), new Among("h\u00F6z", -1, -1, "", null), new Among("v\u00E1", -1, -1, "", null), new Among("v\u00E9", -1, -1, "", null) }; a_5 = new Among[] { new Among("\u00E1n", -1, 2, "", null), new Among("\u00E9n", -1, 1, "", null), new Among("\u00E1nk\u00E9nt", -1, 3, "", null) }; a_6 = new Among[] { new Among("stul", -1, 2, "", null), new Among("astul", 0, 1, "", null), new Among("\u00E1stul", 0, 3, "", null), new Among("st\u00FCl", -1, 2, "", null), new Among("est\u00FCl", 3, 1, "", null), new Among("\u00E9st\u00FCl", 3, 4, "", null) }; a_7 = new Among[] { new Among("\u00E1", -1, 1, "", null), new Among("\u00E9", -1, 2, "", null) }; a_8 = new Among[] { new Among("k", -1, 7, "", null), new Among("ak", 0, 4, "", null), new Among("ek", 0, 6, "", null), new Among("ok", 0, 5, "", null), new Among("\u00E1k", 0, 1, "", null), new Among("\u00E9k", 0, 2, "", null), new Among("\u00F6k", 0, 3, "", null) }; a_9 = new Among[] { new Among("\u00E9i", -1, 7, "", null), new Among("\u00E1\u00E9i", 0, 6, "", null), new Among("\u00E9\u00E9i", 0, 5, "", null), new Among("\u00E9", -1, 9, "", null), new Among("k\u00E9", 3, 4, "", null), new Among("ak\u00E9", 4, 1, "", null), new Among("ek\u00E9", 4, 1, "", null), new Among("ok\u00E9", 4, 1, "", null), new Among("\u00E1k\u00E9", 4, 3, "", null), new Among("\u00E9k\u00E9", 4, 2, "", null), new Among("\u00F6k\u00E9", 4, 1, "", null), new Among("\u00E9\u00E9", 3, 8, "", null) }; a_10 = new Among[] { new Among("a", -1, 18, "", null), new Among("ja", 0, 17, "", null), new Among("d", -1, 16, "", null), new Among("ad", 2, 13, "", null), new Among("ed", 2, 13, "", null), new Among("od", 2, 13, "", null), new Among("\u00E1d", 2, 14, "", null), new Among("\u00E9d", 2, 15, "", null), new Among("\u00F6d", 2, 13, "", null), new Among("e", -1, 18, "", null), new Among("je", 9, 17, "", null), new Among("nk", -1, 4, "", null), new Among("unk", 11, 1, "", null), new Among("\u00E1nk", 11, 2, "", null), new Among("\u00E9nk", 11, 3, "", null), new Among("\u00FCnk", 11, 1, "", null), new Among("uk", -1, 8, "", null), new Among("juk", 16, 7, "", null), new Among("\u00E1juk", 17, 5, "", null), new Among("\u00FCk", -1, 8, "", null), new Among("j\u00FCk", 19, 7, "", null), new Among("\u00E9j\u00FCk", 20, 6, "", null), new Among("m", -1, 12, "", null), new Among("am", 22, 9, "", null), new Among("em", 22, 9, "", null), new Among("om", 22, 9, "", null), new Among("\u00E1m", 22, 10, "", null), new Among("\u00E9m", 22, 11, "", null), new Among("o", -1, 18, "", null), new Among("\u00E1", -1, 19, "", null), new Among("\u00E9", -1, 20, "", null) }; a_11 = new Among[] { new Among("id", -1, 10, "", null), new Among("aid", 0, 9, "", null), new Among("jaid", 1, 6, "", null), new Among("eid", 0, 9, "", null), new Among("jeid", 3, 6, "", null), new Among("\u00E1id", 0, 7, "", null), new Among("\u00E9id", 0, 8, "", null), new Among("i", -1, 15, "", null), new Among("ai", 7, 14, "", null), new Among("jai", 8, 11, "", null), new Among("ei", 7, 14, "", null), new Among("jei", 10, 11, "", null), new Among("\u00E1i", 7, 12, "", null), new Among("\u00E9i", 7, 13, "", null), new Among("itek", -1, 24, "", null), new Among("eitek", 14, 21, "", null), new Among("jeitek", 15, 20, "", null), new Among("\u00E9itek", 14, 23, "", null), new Among("ik", -1, 29, "", null), new Among("aik", 18, 26, "", null), new Among("jaik", 19, 25, "", null), new Among("eik", 18, 26, "", null), new Among("jeik", 21, 25, "", null), new Among("\u00E1ik", 18, 27, "", null), new Among("\u00E9ik", 18, 28, "", null), new Among("ink", -1, 20, "", null), new Among("aink", 25, 17, "", null), new Among("jaink", 26, 16, "", null), new Among("eink", 25, 17, "", null), new Among("jeink", 28, 16, "", null), new Among("\u00E1ink", 25, 18, "", null), new Among("\u00E9ink", 25, 19, "", null), new Among("aitok", -1, 21, "", null), new Among("jaitok", 32, 20, "", null), new Among("\u00E1itok", -1, 22, "", null), new Among("im", -1, 5, "", null), new Among("aim", 35, 4, "", null), new Among("jaim", 36, 1, "", null), new Among("eim", 35, 4, "", null), new Among("jeim", 38, 1, "", null), new Among("\u00E1im", 35, 2, "", null), new Among("\u00E9im", 35, 3, "", null) }; } private Among[] a_0; private Among[] a_1; private Among[] a_2; private Among[] a_3; private Among[] a_4; private Among[] a_5; private Among[] a_6; private Among[] a_7; private Among[] a_8; private Among[] a_9; private Among[] a_10; private Among[] a_11; private static readonly char[] g_v = new char[] { (char)17, (char)65, (char)16, (char)0, (char)0, (char)0, (char)0, (char)0, (char)0, (char)0, (char)0, (char)0, (char)0, (char)0, (char)0, (char)0, (char)1, (char)17, (char)52, (char)14 }; private int I_p1; private void copy_from(HungarianStemmer other) { I_p1 = other.I_p1; base.copy_from(other); } private bool r_mark_regions() { int v_1; int v_2; int v_3; // (, line 44 I_p1 = limit; // or, line 51 v_1 = cursor; // (, line 48 if (!(in_grouping(g_v, 97, 252))) { goto lab1; } // goto, line 48 while (true) { v_2 = cursor; if (!(out_grouping(g_v, 97, 252))) { goto lab3; } cursor = v_2; goto golab2; lab3: cursor = v_2; if (cursor >= limit) { goto lab1; } cursor++; } golab2: // or, line 49 v_3 = cursor; // among, line 49 if (find_among(a_0, 8) == 0) { goto lab5; } goto lab4; lab5: cursor = v_3; // next, line 49 if (cursor >= limit) { goto lab1; } cursor++; lab4: // setmark p1, line 50 I_p1 = cursor; goto lab0; lab1: cursor = v_1; // (, line 53 if (!(out_grouping(g_v, 97, 252))) { return false; } // gopast, line 53 while (true) { if (!(in_grouping(g_v, 97, 252))) { goto lab7; } goto golab6; lab7: if (cursor >= limit) { return false; } cursor++; } golab6: // setmark p1, line 53 I_p1 = cursor; lab0: return true; } private bool r_R1() { if (!(I_p1 <= cursor)) { return false; } return true; } private bool r_v_ending() { int among_var; // (, line 60 // [, line 61 ket = cursor; // substring, line 61 among_var = find_among_b(a_1, 2); if (among_var == 0) { return false; } // ], line 61 bra = cursor; // call R1, line 61 if (!r_R1()) { return false; } switch (among_var) { case 0: return false; case 1: // (, line 62 // <-, line 62 slice_from("a"); break; case 2: // (, line 63 // <-, line 63 slice_from("e"); break; } return true; } private bool r_double() { int v_1; // (, line 67 // test, line 68 v_1 = limit - cursor; // among, line 68 if (find_among_b(a_2, 23) == 0) { return false; } cursor = limit - v_1; return true; } private bool r_undouble() { // (, line 72 // next, line 73 if (cursor <= limit_backward) { return false; } cursor--; // [, line 73 ket = cursor; // hop, line 73 { int c = cursor - 1; if (limit_backward > c || c > limit) { return false; } cursor = c; } // ], line 73 bra = cursor; // delete, line 73 slice_del(); return true; } private bool r_instrum() { int among_var; // (, line 76 // [, line 77 ket = cursor; // substring, line 77 among_var = find_among_b(a_3, 2); if (among_var == 0) { return false; } // ], line 77 bra = cursor; // call R1, line 77 if (!r_R1()) { return false; } switch (among_var) { case 0: return false; case 1: // (, line 78 // call double, line 78 if (!r_double()) { return false; } break; case 2: // (, line 79 // call double, line 79 if (!r_double()) { return false; } break; } // delete, line 81 slice_del(); // call undouble, line 82 if (!r_undouble()) { return false; } return true; } private bool r_case() { // (, line 86 // [, line 87 ket = cursor; // substring, line 87 if (find_among_b(a_4, 44) == 0) { return false; } // ], line 87 bra = cursor; // call R1, line 87 if (!r_R1()) { return false; } // delete, line 111 slice_del(); // call v_ending, line 112 if (!r_v_ending()) { return false; } return true; } private bool r_case_special() { int among_var; // (, line 115 // [, line 116 ket = cursor; // substring, line 116 among_var = find_among_b(a_5, 3); if (among_var == 0) { return false; } // ], line 116 bra = cursor; // call R1, line 116 if (!r_R1()) { return false; } switch (among_var) { case 0: return false; case 1: // (, line 117 // <-, line 117 slice_from("e"); break; case 2: // (, line 118 // <-, line 118 slice_from("a"); break; case 3: // (, line 119 // <-, line 119 slice_from("a"); break; } return true; } private bool r_case_other() { int among_var; // (, line 123 // [, line 124 ket = cursor; // substring, line 124 among_var = find_among_b(a_6, 6); if (among_var == 0) { return false; } // ], line 124 bra = cursor; // call R1, line 124 if (!r_R1()) { return false; } switch (among_var) { case 0: return false; case 1: // (, line 125 // delete, line 125 slice_del(); break; case 2: // (, line 126 // delete, line 126 slice_del(); break; case 3: // (, line 127 // <-, line 127 slice_from("a"); break; case 4: // (, line 128 // <-, line 128 slice_from("e"); break; } return true; } private bool r_factive() { int among_var; // (, line 132 // [, line 133 ket = cursor; // substring, line 133 among_var = find_among_b(a_7, 2); if (among_var == 0) { return false; } // ], line 133 bra = cursor; // call R1, line 133 if (!r_R1()) { return false; } switch (among_var) { case 0: return false; case 1: // (, line 134 // call double, line 134 if (!r_double()) { return false; } break; case 2: // (, line 135 // call double, line 135 if (!r_double()) { return false; } break; } // delete, line 137 slice_del(); // call undouble, line 138 if (!r_undouble()) { return false; } return true; } private bool r_plural() { int among_var; // (, line 141 // [, line 142 ket = cursor; // substring, line 142 among_var = find_among_b(a_8, 7); if (among_var == 0) { return false; } // ], line 142 bra = cursor; // call R1, line 142 if (!r_R1()) { return false; } switch (among_var) { case 0: return false; case 1: // (, line 143 // <-, line 143 slice_from("a"); break; case 2: // (, line 144 // <-, line 144 slice_from("e"); break; case 3: // (, line 145 // delete, line 145 slice_del(); break; case 4: // (, line 146 // delete, line 146 slice_del(); break; case 5: // (, line 147 // delete, line 147 slice_del(); break; case 6: // (, line 148 // delete, line 148 slice_del(); break; case 7: // (, line 149 // delete, line 149 slice_del(); break; } return true; } private bool r_owned() { int among_var; // (, line 153 // [, line 154 ket = cursor; // substring, line 154 among_var = find_among_b(a_9, 12); if (among_var == 0) { return false; } // ], line 154 bra = cursor; // call R1, line 154 if (!r_R1()) { return false; } switch (among_var) { case 0: return false; case 1: // (, line 155 // delete, line 155 slice_del(); break; case 2: // (, line 156 // <-, line 156 slice_from("e"); break; case 3: // (, line 157 // <-, line 157 slice_from("a"); break; case 4: // (, line 158 // delete, line 158 slice_del(); break; case 5: // (, line 159 // <-, line 159 slice_from("e"); break; case 6: // (, line 160 // <-, line 160 slice_from("a"); break; case 7: // (, line 161 // delete, line 161 slice_del(); break; case 8: // (, line 162 // <-, line 162 slice_from("e"); break; case 9: // (, line 163 // delete, line 163 slice_del(); break; } return true; } private bool r_sing_owner() { int among_var; // (, line 167 // [, line 168 ket = cursor; // substring, line 168 among_var = find_among_b(a_10, 31); if (among_var == 0) { return false; } // ], line 168 bra = cursor; // call R1, line 168 if (!r_R1()) { return false; } switch (among_var) { case 0: return false; case 1: // (, line 169 // delete, line 169 slice_del(); break; case 2: // (, line 170 // <-, line 170 slice_from("a"); break; case 3: // (, line 171 // <-, line 171 slice_from("e"); break; case 4: // (, line 172 // delete, line 172 slice_del(); break; case 5: // (, line 173 // <-, line 173 slice_from("a"); break; case 6: // (, line 174 // <-, line 174 slice_from("e"); break; case 7: // (, line 175 // delete, line 175 slice_del(); break; case 8: // (, line 176 // delete, line 176 slice_del(); break; case 9: // (, line 177 // delete, line 177 slice_del(); break; case 10: // (, line 178 // <-, line 178 slice_from("a"); break; case 11: // (, line 179 // <-, line 179 slice_from("e"); break; case 12: // (, line 180 // delete, line 180 slice_del(); break; case 13: // (, line 181 // delete, line 181 slice_del(); break; case 14: // (, line 182 // <-, line 182 slice_from("a"); break; case 15: // (, line 183 // <-, line 183 slice_from("e"); break; case 16: // (, line 184 // delete, line 184 slice_del(); break; case 17: // (, line 185 // delete, line 185 slice_del(); break; case 18: // (, line 186 // delete, line 186 slice_del(); break; case 19: // (, line 187 // <-, line 187 slice_from("a"); break; case 20: // (, line 188 // <-, line 188 slice_from("e"); break; } return true; } private bool r_plur_owner() { int among_var; // (, line 192 // [, line 193 ket = cursor; // substring, line 193 among_var = find_among_b(a_11, 42); if (among_var == 0) { return false; } // ], line 193 bra = cursor; // call R1, line 193 if (!r_R1()) { return false; } switch (among_var) { case 0: return false; case 1: // (, line 194 // delete, line 194 slice_del(); break; case 2: // (, line 195 // <-, line 195 slice_from("a"); break; case 3: // (, line 196 // <-, line 196 slice_from("e"); break; case 4: // (, line 197 // delete, line 197 slice_del(); break; case 5: // (, line 198 // delete, line 198 slice_del(); break; case 6: // (, line 199 // delete, line 199 slice_del(); break; case 7: // (, line 200 // <-, line 200 slice_from("a"); break; case 8: // (, line 201 // <-, line 201 slice_from("e"); break; case 9: // (, line 202 // delete, line 202 slice_del(); break; case 10: // (, line 203 // delete, line 203 slice_del(); break; case 11: // (, line 204 // delete, line 204 slice_del(); break; case 12: // (, line 205 // <-, line 205 slice_from("a"); break; case 13: // (, line 206 // <-, line 206 slice_from("e"); break; case 14: // (, line 207 // delete, line 207 slice_del(); break; case 15: // (, line 208 // delete, line 208 slice_del(); break; case 16: // (, line 209 // delete, line 209 slice_del(); break; case 17: // (, line 210 // delete, line 210 slice_del(); break; case 18: // (, line 211 // <-, line 211 slice_from("a"); break; case 19: // (, line 212 // <-, line 212 slice_from("e"); break; case 20: // (, line 214 // delete, line 214 slice_del(); break; case 21: // (, line 215 // delete, line 215 slice_del(); break; case 22: // (, line 216 // <-, line 216 slice_from("a"); break; case 23: // (, line 217 // <-, line 217 slice_from("e"); break; case 24: // (, line 218 // delete, line 218 slice_del(); break; case 25: // (, line 219 // delete, line 219 slice_del(); break; case 26: // (, line 220 // delete, line 220 slice_del(); break; case 27: // (, line 221 // <-, line 221 slice_from("a"); break; case 28: // (, line 222 // <-, line 222 slice_from("e"); break; case 29: // (, line 223 // delete, line 223 slice_del(); break; } return true; } public override bool Stem() { int v_1; int v_2; int v_3; int v_4; int v_5; int v_6; int v_7; int v_8; int v_9; int v_10; // (, line 228 // do, line 229 v_1 = cursor; // call mark_regions, line 229 if (!r_mark_regions()) { goto lab0; } lab0: cursor = v_1; // backwards, line 230 limit_backward = cursor; cursor = limit; // (, line 230 // do, line 231 v_2 = limit - cursor; // call instrum, line 231 if (!r_instrum()) { goto lab1; } lab1: cursor = limit - v_2; // do, line 232 v_3 = limit - cursor; // call case, line 232 if (!r_case()) { goto lab2; } lab2: cursor = limit - v_3; // do, line 233 v_4 = limit - cursor; // call case_special, line 233 if (!r_case_special()) { goto lab3; } lab3: cursor = limit - v_4; // do, line 234 v_5 = limit - cursor; // call case_other, line 234 if (!r_case_other()) { goto lab4; } lab4: cursor = limit - v_5; // do, line 235 v_6 = limit - cursor; // call factive, line 235 if (!r_factive()) { goto lab5; } lab5: cursor = limit - v_6; // do, line 236 v_7 = limit - cursor; // call owned, line 236 if (!r_owned()) { goto lab6; } lab6: cursor = limit - v_7; // do, line 237 v_8 = limit - cursor; // call sing_owner, line 237 if (!r_sing_owner()) { goto lab7; } lab7: cursor = limit - v_8; // do, line 238 v_9 = limit - cursor; // call plur_owner, line 238 if (!r_plur_owner()) { goto lab8; } lab8: cursor = limit - v_9; // do, line 239 v_10 = limit - cursor; // call plural, line 239 if (!r_plural()) { goto lab9; } lab9: cursor = limit - v_10; cursor = limit_backward; return true; } } }
/* * Copyright (C) 2013 Google 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. */ #if UNITY_IPHONE using System; using System.Collections; using System.Collections.Generic; using GooglePlayGames.BasicApi; using GooglePlayGames.OurUtils; using System.Runtime.InteropServices; using System.Text; using System.IO; using UnityEngine; namespace GooglePlayGames.IOS { public class IOSClient : IPlayGamesClient { // Callback types: private delegate void GPGSSuccessCallback(bool success, int userdata); private delegate void GPGSUpdateStateCallback(bool success, int slot); private delegate int GPGSStateConflictCallback(int slot, IntPtr localBufPtr, int localDataSize, IntPtr serverBufPtr, int serverDataSize, IntPtr resolvBufPtr, int resolvBufCap); private delegate void GPGSLoadStateCallback(bool success, int slot, IntPtr dataBuf, int dataSize); // Entry points exposed by the iOS native code (.m files in Assets/Plugins/iOS): [DllImport("__Internal")] private static extern void GPGSAuthenticateWithCallback(GPGSSuccessCallback cb); [DllImport("__Internal")] private static extern void GPGSEnableDebugLog(bool enable); [DllImport("__Internal")] private static extern void GPGSGetPlayerId(StringBuilder outbuf, int bufSize); [DllImport("__Internal")] private static extern void GPGSGetPlayerName(StringBuilder outbuf, int bufSize); [DllImport("__Internal")] private static extern void GPGSSignOut(); [DllImport("__Internal")] private static extern bool GPGSQueryAchievement(string achId, ref bool outIsIncremental, ref bool outIsRevealed, ref bool outIsUnlocked, ref int outCurSteps, ref int outTotalSteps); [DllImport("__Internal")] private static extern void GPGSUnlockAchievement(string achId, GPGSSuccessCallback cb, int userdata); [DllImport("__Internal")] private static extern void GPGSRevealAchievement(string achId, GPGSSuccessCallback cb, int userdata); [DllImport("__Internal")] private static extern void GPGSIncrementAchievement(string achId, int steps, GPGSSuccessCallback cb, int userdata); [DllImport("__Internal")] private static extern void GPGSShowAchievementsUI(); [DllImport("__Internal")] private static extern void GPGSShowLeaderboardsUI(string lbId); [DllImport("__Internal")] private static extern void GPGSSubmitScore(string lbId, long score, GPGSSuccessCallback cb, int userdata); [DllImport("__Internal")] private static extern void GPGSUpdateState(int slot, byte[] data, int dataSize, GPGSUpdateStateCallback updateCb, GPGSStateConflictCallback conflictCb); [DllImport("__Internal")] private static extern void GPGSLoadState(int slot, GPGSLoadStateCallback loadCb, GPGSStateConflictCallback conflictCb); // Default capacity for stringbuilder buffers private const int DefaultStringBufferCapacity = 256; // Pending callbacks from such calls as UnlockAchievement, etc. These are keyed // by an identifier that we send to the low-level C API, which is then reported // back on the callback (the userdata parameter of most calls) static Dictionary<int, System.Action<bool>> mCallbackDict = new Dictionary<int, System.Action<bool>>(); static int mNextCallbackId = 0; bool mAuthenticated = false; System.Action<bool> mAuthCallback = null; static IOSClient sInstance = null; // maps slot# to OnStateLoadedListener (each slot can have a different listener, // because the caller may want to load several slots concurrently). Dictionary<int,OnStateLoadedListener> mStateLoadedListener = new Dictionary<int, OnStateLoadedListener>(); // local files where we store the cloud cache (we implement this on the plugin side // because in iOS the library does not support offline loading of cloud data. So we // fake that using files. const string CloudCacheDir = "/gpgscc"; string CloudCacheFileFmt = CloudCacheDir + "/{0}.dat"; // cloud cache encrypter BufferEncrypter mCloudEncrypter = null; public IOSClient() { mCloudEncrypter = DummyEncrypter; if (Logger.DebugLogEnabled) { Logger.d("Note: debug logs enabled on IOSClient."); GPGSEnableDebugLog(true); } if (sInstance != null) { Logger.e("Second instance of IOSClient created. This is not supposed to happen " + "and will likely break things."); } sInstance = this; } public void Authenticate(System.Action<bool> callback, bool silent) { Logger.d("IOSClient.Authenticate"); mAuthCallback = callback; GPGSAuthenticateWithCallback(AuthCallback); } public void SignOut() { Logger.d("IOSClient.SignOut"); GPGSSignOut(); mAuthenticated = false; } // Due to limitations of Mono on iOS, callbacks invoked from C have to be static, // and have to have this MonoPInvokeCallback annotation. [MonoPInvokeCallback(typeof(GPGSSuccessCallback))] private static void AuthCallback(bool success, int userdata) { Logger.d("IOSClient.AuthCallback, success=" + success); sInstance.mAuthenticated = success; if (sInstance.mAuthCallback != null) { sInstance.mAuthCallback.Invoke(success); } } public bool IsAuthenticated () { return mAuthenticated; } public string GetUserId () { Logger.d("IOSClient.GetUserId"); StringBuilder sb = new StringBuilder(512); GPGSGetPlayerId(sb, sb.Capacity); Logger.d("Returned user id: " + sb.ToString()); return sb.ToString(); } public string GetUserDisplayName () { Logger.d("IOSClient.GetUserDisplayName"); StringBuilder sb = new StringBuilder(512); GPGSGetPlayerName(sb, sb.Capacity); Logger.d("Returned user display name: " + sb.ToString()); return sb.ToString(); } public Achievement GetAchievement (string achId) { Logger.d("IOSClient.GetAchievement " + achId); Achievement a = new Achievement(); a.Id = achId; a.Name = a.Description = ""; bool isRevealed = false, isUnlocked = false, isIncremental = false; int curSteps = 0, totalSteps = 0; GPGSQueryAchievement(achId, ref isIncremental, ref isRevealed, ref isUnlocked, ref curSteps, ref totalSteps); a.IsIncremental = isIncremental; a.IsRevealed = isRevealed; a.IsUnlocked = isUnlocked; a.CurrentSteps = curSteps; a.TotalSteps = totalSteps; return a; } public void UnlockAchievement(string achId, System.Action<bool> callback) { Logger.d("IOSClient.UnlockAchievement, achId=" + achId); int key = 0; GPGSSuccessCallback cb = null; if (callback != null) { key = RegisterSuccessCallback("UnlockAchievement", callback); cb = ApiCallSuccessCallback; } GPGSUnlockAchievement(achId, cb, key); } public void RevealAchievement (string achId, System.Action<bool> callback) { Logger.d("IOSClient.RevealAchievement, achId=" + achId); int key = 0; GPGSSuccessCallback cb = null; if (callback != null) { key = RegisterSuccessCallback("RevealAchievement", callback); cb = ApiCallSuccessCallback; } GPGSRevealAchievement(achId, cb, key); } public void IncrementAchievement (string achId, int steps, System.Action<bool> callback) { Logger.d("IOSClient.IncrementAchievement, achId=" + achId + ", steps=" + steps); int key = 0; GPGSSuccessCallback cb = null; if (callback != null) { key = RegisterSuccessCallback("IncrementAchievement", callback); cb = ApiCallSuccessCallback; } GPGSIncrementAchievement(achId, steps, cb, key); } public void ShowAchievementsUI () { Logger.d("IOSClient.ShowAchievementsUI"); GPGSShowAchievementsUI(); } public void ShowLeaderboardUI (string lbId) { Logger.d("IOSClient.ShowLeaderboardsUI"); GPGSShowLeaderboardsUI(lbId); } public void SubmitScore (string lbId, long score, System.Action<bool> callback) { Logger.d(string.Format("IOSClient.SubmitScore lbId={0}, score={1}, cb={2}", lbId, score, (callback != null ? "non-null" : "null"))); int key = 0; GPGSSuccessCallback cb = null; if (callback != null) { key = RegisterSuccessCallback("SubmitScore", callback); cb = ApiCallSuccessCallback; } GPGSSubmitScore(lbId, score, cb, key); } private static OnStateLoadedListener GetListener(int slot) { if (sInstance.mStateLoadedListener.ContainsKey(slot)) { return sInstance.mStateLoadedListener[slot]; } else { return null; } } // Due to limitations of Mono on iOS, callbacks invoked from C have to be static, // and have to have this MonoPInvokeCallback annotation. [MonoPInvokeCallback(typeof(GPGSUpdateStateCallback))] private static void UpdateStateCallback(bool success, int slot) { OnStateLoadedListener listener = GetListener(slot); Logger.d("IOSClient.UpdateStateCallback, slot=" + slot + ", success=" + success); if (null != listener) { Logger.d("IOSClient.UpdateStateCallback calling OnSLL.OnStateSaved"); listener.OnStateSaved(success, slot); } else { Logger.d("IOSClient.UpdateStateCallback: no OnSLL to call!"); } } // Due to limitations of Mono on iOS, callbacks invoked from C have to be static, // and have to have this MonoPInvokeCallback annotation. [MonoPInvokeCallback(typeof(GPGSSuccessCallback))] private static void ApiCallSuccessCallback(bool success, int key) { Logger.d("IOSClient.ApiCallSuccessCallback success=" + success + ", key=" + key); CallRegisteredSuccessCallback(key, success); } // Due to limitations of Mono on iOS, callbacks invoked from C have to be static, // and have to have this MonoPInvokeCallback annotation. [MonoPInvokeCallback(typeof(GPGSStateConflictCallback))] private static int StateConflictCallback(int slot, IntPtr localBufPtr, int localDataSize, IntPtr serverBufPtr, int serverDataSize, IntPtr resolvBufPtr, int resolvBufCap) { string prefix = "IOSClient.StateConflictCallback "; Logger.d(prefix + "slot " + slot + " " + "localbuf " + localBufPtr + " (" + localDataSize + " bytes); " + "serverbuf " + serverBufPtr + " (" + serverDataSize + " bytes); " + "resolvbuf " + resolvBufPtr + " (capacity " + resolvBufCap + ")"); byte[] localData = null; byte[] serverData = null; if (localBufPtr.ToInt32() != 0) { localData = new byte[localDataSize]; Marshal.Copy(localBufPtr, localData, 0, localDataSize); } if (serverBufPtr.ToInt32() != 0) { serverData = new byte[serverDataSize]; Marshal.Copy(serverBufPtr, serverData, 0, serverDataSize); } OnStateLoadedListener listener = GetListener(slot); byte[] resolvData = null; if (OurUtils.Utils.BuffersAreIdentical(localData, serverData)) { Logger.d(prefix + "Bypassing fake conflict " + "(local data is IDENTICAL to server data)."); resolvData = localData != null ? localData : serverData; } else if (listener != null) { Logger.d(prefix + "calling OnSLL.OnStateConflict."); resolvData = listener.OnStateConflict(slot, localData, serverData); Logger.d(prefix +" resolvData has " + resolvData.Length + " bytes"); if (resolvData.Length > resolvBufCap) { Logger.e("Resolved data length is " + resolvData.Length + " which exceeds " + "resolved buffer capacity " + resolvBufCap); resolvData = null; } } else { Logger.d(prefix + "no listener, so choosing local data."); } if (resolvData == null) { // fallback Logger.w("Using fallback strategy due to unexpected resolution."); resolvData = localData != null ? localData : serverData; if (resolvData == null) { Logger.w("ERROR: unexpected cloud conflict where all data sets are null. " + "Fixing by storing byte[1] { 0 }."); resolvData = new byte[1] { 0 }; } } int len = resolvBufCap < resolvData.Length ? resolvBufCap : resolvData.Length; Logger.d(prefix + "outputting " + len + " bytes to resolved buffer."); Marshal.Copy(resolvData, 0, resolvBufPtr, len); Logger.d(prefix + "finishing up."); return len; } // Due to limitations of Mono on iOS, callbacks invoked from C have to be static, // and have to have this MonoPInvokeCallback annotation. [MonoPInvokeCallback(typeof(GPGSLoadStateCallback))] private static void LoadStateCallback(bool success, int slot, IntPtr dataBuf, int dataSize) { string prefix = "IOSClient.LoadStateCallback "; Logger.d(prefix + " success="+ success + ", slot=" + slot + " dataBuf=" + dataBuf + " dataSize=" + dataSize); byte[] data = null; if (success) { if (dataBuf.ToInt32() != 0) { data = new byte[dataSize]; Marshal.Copy(dataBuf, data, 0, dataSize); sInstance.SaveCloudCacheFile(slot, data); } } else { // Cloud load failed... but don't despair! Do we have the data in local cache? Logger.d(prefix + "Cloud load failed. Trying to load local cache."); byte[] localCache = sInstance.LoadCloudCacheFile(slot); if (localCache != null) { // no local cache, so we have to report a failure. Logger.d(prefix + "Local cache not present. Reporting failure."); } else { // we have data in local cache, so report success instead of failure, // and return that data. Logger.d(prefix + "Loaded from local cache, so reporting success."); data = localCache; success = true; } } OnStateLoadedListener callback = GetListener(slot); if (callback != null) { Logger.d(prefix + "calling OnStateLoadedListener with " + (success ? "success" : "failure")); callback.OnStateLoaded(success, slot, data); } } public void SetCloudCacheEncrypter(BufferEncrypter encrypter) { Logger.d("IOSClient: cloud cache encrypter is now set."); mCloudEncrypter = encrypter; } public void LoadState(int slot, OnStateLoadedListener listener) { Logger.d("IOSClient.LoadState slot=" + slot); mStateLoadedListener[slot] = listener; GPGSLoadState(slot, LoadStateCallback, StateConflictCallback); } public void UpdateState(int slot, byte[] data, OnStateLoadedListener listener) { Logger.d("IOSClient.UpdateState slot " + slot + ", " + data.Length + " bytes"); mStateLoadedListener[slot] = listener; SaveCloudCacheFile(slot, data); GPGSUpdateState(slot, data, data.Length, UpdateStateCallback, StateConflictCallback); } private void CreateCloudCacheDirIfNeeded() { string root = Application.persistentDataPath; if (!System.IO.Directory.Exists(root + CloudCacheDir)) { Logger.d("IOSClient: creating cloud cache dir: " + root + CloudCacheDir); System.IO.Directory.CreateDirectory(root + CloudCacheDir); } } private byte[] LoadCloudCacheFile(int slot) { string root = Application.persistentDataPath; string file = root + string.Format(CloudCacheFileFmt, slot); string pref = "IOSClient.LoadCloudCacheFile: "; Logger.d(pref + "Looking for local cloud cache for slot " + slot + " in " + file); if (System.IO.File.Exists(file)) { Logger.d(pref + "Loading " + file); byte[] encrypted = File.ReadAllBytes(file); Logger.d(pref + "Slot " + slot + " loaded successfully, " + encrypted.Length + " bytes"); byte[] decrypted = mCloudEncrypter(false, encrypted); Logger.d(pref + "Decrypted data: " + decrypted.Length + " bytes"); return decrypted; } else { Logger.d("IOSClient: Local cloud cache for slot " + slot + " not found."); return null; } } private void SaveCloudCacheFile(int slot, byte[] data) { string root = Application.persistentDataPath; string file = root + string.Format(CloudCacheFileFmt, slot); string pref = "IOSClient.SaveCloudCacheFile: "; Logger.d(pref + "Saving local cloud cache for slot " + slot + " to " + file); CreateCloudCacheDirIfNeeded(); Logger.d(pref + "Original data: " + data.Length + " bytes"); byte[] encrypted = mCloudEncrypter(true, data); Logger.d(pref + "Encrypted data: " + encrypted.Length + " bytes"); File.WriteAllBytes(file, encrypted); Logger.d(pref + "Slot " + slot + " successfully written."); } private byte[] DummyEncrypter(bool encrypt, byte[] data) { return data; } private static int RegisterSuccessCallback(string methodName, System.Action<bool> callback) { int key = mNextCallbackId++; mCallbackDict[key] = callback; Logger.d("Success callback registered for method " + methodName + ", key " + key); return key; } private static void CallRegisteredSuccessCallback(int key, bool success) { if (mCallbackDict.ContainsKey(key)) { System.Action<bool> cb = mCallbackDict[key]; if (cb != null) { mCallbackDict.Remove(key); cb.Invoke(success); } } } } } #endif
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Linq; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Runtime.Serialization; using System.Text; namespace Microsoft.PowerShell.ScheduledJob { /// <summary> /// This class provides functionality for retrieving scheduled job run results /// from the scheduled job store. An instance of this object will be registered /// with the PowerShell JobManager so that GetJobs commands will retrieve schedule /// job runs from the file based scheduled job store. This allows scheduled job /// runs to be managed from PowerShell in the same way workflow jobs are managed. /// </summary> public sealed class ScheduledJobSourceAdapter : JobSourceAdapter { #region Private Members private static FileSystemWatcher StoreWatcher; private static object SyncObject = new object(); private static ScheduledJobRepository JobRepository = new ScheduledJobRepository(); internal const string AdapterTypeName = "PSScheduledJob"; #endregion #region Public Strings /// <summary> /// BeforeFilter. /// </summary> public const string BeforeFilter = "Before"; /// <summary> /// AfterFilter. /// </summary> public const string AfterFilter = "After"; /// <summary> /// NewestFilter. /// </summary> public const string NewestFilter = "Newest"; #endregion #region Constructor /// <summary> /// Constructor. /// </summary> public ScheduledJobSourceAdapter() { Name = AdapterTypeName; } #endregion #region JobSourceAdapter Implementation /// <summary> /// Create a new Job2 results instance. /// </summary> /// <param name="specification">Job specification.</param> /// <returns>Job2.</returns> public override Job2 NewJob(JobInvocationInfo specification) { if (specification == null) { throw new PSArgumentNullException("specification"); } ScheduledJobDefinition scheduledJobDef = new ScheduledJobDefinition( specification, null, null, null); return new ScheduledJob( specification.Command, specification.Name, scheduledJobDef); } /// <summary> /// Creates a new Job2 object based on a definition name /// that can be run manually. If the path parameter is /// null then a default location will be used to find the /// job definition by name. /// </summary> /// <param name="definitionName">ScheduledJob definition name.</param> /// <param name="definitionPath">ScheduledJob definition file path.</param> /// <returns>Job2 object.</returns> public override Job2 NewJob(string definitionName, string definitionPath) { if (string.IsNullOrEmpty(definitionName)) { throw new PSArgumentException("definitionName"); } Job2 rtnJob = null; try { ScheduledJobDefinition scheduledJobDef = ScheduledJobDefinition.LoadFromStore(definitionName, definitionPath); rtnJob = new ScheduledJob( scheduledJobDef.Command, scheduledJobDef.Name, scheduledJobDef); } catch (FileNotFoundException) { // Return null if no job definition exists. } return rtnJob; } /// <summary> /// Get the list of jobs that are currently available in this /// store. /// </summary> /// <returns>Collection of job objects.</returns> public override IList<Job2> GetJobs() { RefreshRepository(); List<Job2> rtnJobs = new List<Job2>(); foreach (var job in JobRepository.Jobs) { rtnJobs.Add(job); } return rtnJobs; } /// <summary> /// Get list of jobs that matches the specified names. /// </summary> /// <param name="name">names to match, can support /// wildcard if the store supports</param> /// <param name="recurse"></param> /// <returns>Collection of jobs that match the specified /// criteria.</returns> public override IList<Job2> GetJobsByName(string name, bool recurse) { if (string.IsNullOrEmpty(name)) { throw new PSArgumentException("name"); } RefreshRepository(); WildcardPattern namePattern = new WildcardPattern(name, WildcardOptions.IgnoreCase); List<Job2> rtnJobs = new List<Job2>(); foreach (var job in JobRepository.Jobs) { if (namePattern.IsMatch(job.Name)) { rtnJobs.Add(job); } } return rtnJobs; } /// <summary> /// Get list of jobs that run the specified command. /// </summary> /// <param name="command">Command to match.</param> /// <param name="recurse"></param> /// <returns>Collection of jobs that match the specified /// criteria.</returns> public override IList<Job2> GetJobsByCommand(string command, bool recurse) { if (string.IsNullOrEmpty(command)) { throw new PSArgumentException("command"); } RefreshRepository(); WildcardPattern commandPattern = new WildcardPattern(command, WildcardOptions.IgnoreCase); List<Job2> rtnJobs = new List<Job2>(); foreach (var job in JobRepository.Jobs) { if (commandPattern.IsMatch(job.Command)) { rtnJobs.Add(job); } } return rtnJobs; } /// <summary> /// Get job that has the specified id. /// </summary> /// <param name="instanceId">Guid to match.</param> /// <param name="recurse"></param> /// <returns>Job with the specified guid.</returns> public override Job2 GetJobByInstanceId(Guid instanceId, bool recurse) { RefreshRepository(); foreach (var job in JobRepository.Jobs) { if (Guid.Equals(job.InstanceId, instanceId)) { return job; } } return null; } /// <summary> /// Get job that has specific session id. /// </summary> /// <param name="id">Id to match.</param> /// <param name="recurse"></param> /// <returns>Job with the specified id.</returns> public override Job2 GetJobBySessionId(int id, bool recurse) { RefreshRepository(); foreach (var job in JobRepository.Jobs) { if (id == job.Id) { return job; } } return null; } /// <summary> /// Get list of jobs that are in the specified state. /// </summary> /// <param name="state">State to match.</param> /// <param name="recurse"></param> /// <returns>Collection of jobs with the specified /// state.</returns> public override IList<Job2> GetJobsByState(JobState state, bool recurse) { RefreshRepository(); List<Job2> rtnJobs = new List<Job2>(); foreach (var job in JobRepository.Jobs) { if (state == job.JobStateInfo.State) { rtnJobs.Add(job); } } return rtnJobs; } /// <summary> /// Get list of jobs based on the adapter specific /// filter parameters. /// </summary> /// <param name="filter">dictionary containing name value /// pairs for adapter specific filters</param> /// <param name="recurse"></param> /// <returns>Collection of jobs that match the /// specified criteria.</returns> public override IList<Job2> GetJobsByFilter(Dictionary<string, object> filter, bool recurse) { if (filter == null) { throw new PSArgumentNullException("filter"); } List<Job2> rtnJobs = new List<Job2>(); foreach (var filterItem in filter) { switch (filterItem.Key) { case BeforeFilter: GetJobsBefore((DateTime)filterItem.Value, ref rtnJobs); break; case AfterFilter: GetJobsAfter((DateTime)filterItem.Value, ref rtnJobs); break; case NewestFilter: GetNewestJobs((int)filterItem.Value, ref rtnJobs); break; } } return rtnJobs; } /// <summary> /// Remove a job from the store. /// </summary> /// <param name="job">Job object to remove.</param> public override void RemoveJob(Job2 job) { if (job == null) { throw new PSArgumentNullException("job"); } RefreshRepository(); try { JobRepository.Remove(job); ScheduledJobStore.RemoveJobRun( job.Name, job.PSBeginTime ?? DateTime.MinValue); } catch (DirectoryNotFoundException) { } catch (FileNotFoundException) { } } /// <summary> /// Saves job to scheduled job run store. /// </summary> /// <param name="job">ScheduledJob.</param> public override void PersistJob(Job2 job) { if (job == null) { throw new PSArgumentNullException("job"); } SaveJobToStore(job as ScheduledJob); } #endregion #region Save Job /// <summary> /// Serializes a ScheduledJob and saves it to store. /// </summary> /// <param name="job">ScheduledJob.</param> internal static void SaveJobToStore(ScheduledJob job) { string outputPath = job.Definition.OutputPath; if (string.IsNullOrEmpty(outputPath)) { string msg = StringUtil.Format(ScheduledJobErrorStrings.CantSaveJobNoFilePathSpecified, job.Name); throw new ScheduledJobException(msg); } FileStream fsStatus = null; FileStream fsResults = null; try { // Check the job store results and if maximum number of results exist // remove the oldest results folder to make room for these new results. CheckJobStoreResults(outputPath, job.Definition.ExecutionHistoryLength); fsStatus = ScheduledJobStore.CreateFileForJobRunItem( outputPath, job.PSBeginTime ?? DateTime.MinValue, ScheduledJobStore.JobRunItem.Status); // Save status only in status file stream. SaveStatusToFile(job, fsStatus); fsResults = ScheduledJobStore.CreateFileForJobRunItem( outputPath, job.PSBeginTime ?? DateTime.MinValue, ScheduledJobStore.JobRunItem.Results); // Save entire job in results file stream. SaveResultsToFile(job, fsResults); } finally { if (fsStatus != null) { fsStatus.Close(); } if (fsResults != null) { fsResults.Close(); } } } /// <summary> /// Writes the job status information to the provided /// file stream. /// </summary> /// <param name="job">ScheduledJob job to save.</param> /// <param name="fs">FileStream.</param> private static void SaveStatusToFile(ScheduledJob job, FileStream fs) { StatusInfo statusInfo = new StatusInfo( job.InstanceId, job.Name, job.Location, job.Command, job.StatusMessage, job.JobStateInfo.State, job.HasMoreData, job.PSBeginTime, job.PSEndTime, job.Definition); XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer(); serializer.WriteObject(fs, statusInfo); fs.Flush(); } /// <summary> /// Writes the job (which implements ISerializable) to the provided /// file stream. /// </summary> /// <param name="job">ScheduledJob job to save.</param> /// <param name="fs">FileStream.</param> private static void SaveResultsToFile(ScheduledJob job, FileStream fs) { XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer(); serializer.WriteObject(fs, job); fs.Flush(); } /// <summary> /// Check the job store results and if maximum number of results exist /// remove the oldest results folder to make room for these new results. /// </summary> /// <param name="outputPath">Output path.</param> /// <param name="executionHistoryLength">Maximum size of stored job results.</param> private static void CheckJobStoreResults(string outputPath, int executionHistoryLength) { // Get current results for this job definition. Collection<DateTime> jobRuns = ScheduledJobStore.GetJobRunsForDefinitionPath(outputPath); if (jobRuns.Count <= executionHistoryLength) { // There is room for another job run in the store. return; } // Remove the oldest job run from the store. DateTime jobRunToRemove = DateTime.MaxValue; foreach (DateTime jobRun in jobRuns) { jobRunToRemove = (jobRun < jobRunToRemove) ? jobRun : jobRunToRemove; } try { ScheduledJobStore.RemoveJobRunFromOutputPath(outputPath, jobRunToRemove); } catch (UnauthorizedAccessException) { } } #endregion #region Retrieve Job /// <summary> /// Finds and load the Job associated with this ScheduledJobDefinition object /// having the job run date time provided. /// </summary> /// <param name="jobRun">DateTime of job run to load.</param> /// <param name="definitionName">ScheduledJobDefinition name.</param> /// <returns>Job2 job loaded from store.</returns> internal static Job2 LoadJobFromStore(string definitionName, DateTime jobRun) { FileStream fsResults = null; Exception ex = null; bool corruptedFile = false; Job2 job = null; try { // Results fsResults = ScheduledJobStore.GetFileForJobRunItem( definitionName, jobRun, ScheduledJobStore.JobRunItem.Results, FileMode.Open, FileAccess.Read, FileShare.Read); job = LoadResultsFromFile(fsResults); } catch (ArgumentException e) { ex = e; } catch (DirectoryNotFoundException e) { ex = e; } catch (FileNotFoundException e) { ex = e; corruptedFile = true; } catch (UnauthorizedAccessException e) { ex = e; } catch (IOException e) { ex = e; } catch (System.Runtime.Serialization.SerializationException) { corruptedFile = true; } catch (System.Runtime.Serialization.InvalidDataContractException) { corruptedFile = true; } catch (System.Xml.XmlException) { corruptedFile = true; } catch (System.TypeInitializationException) { corruptedFile = true; } finally { if (fsResults != null) { fsResults.Close(); } } if (corruptedFile) { // Remove the corrupted job results file. ScheduledJobStore.RemoveJobRun(definitionName, jobRun); } if (ex != null) { string msg = StringUtil.Format(ScheduledJobErrorStrings.CantLoadJobRunFromStore, definitionName, jobRun); throw new ScheduledJobException(msg, ex); } return job; } /// <summary> /// Loads the Job2 object from provided files stream. /// </summary> /// <param name="fs">FileStream from which to read job object.</param> /// <returns>Created Job2 from file stream.</returns> private static Job2 LoadResultsFromFile(FileStream fs) { XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer(); return (Job2)serializer.ReadObject(fs); } #endregion #region Static Methods /// <summary> /// Adds a Job2 object to the repository. /// </summary> /// <param name="job">Job2.</param> internal static void AddToRepository(Job2 job) { if (job == null) { throw new PSArgumentNullException("job"); } JobRepository.AddOrReplace(job); } /// <summary> /// Clears all items in the repository. /// </summary> internal static void ClearRepository() { JobRepository.Clear(); } /// <summary> /// Clears all items for given job definition name in the /// repository. /// </summary> /// <param name="definitionName">Scheduled job definition name.</param> internal static void ClearRepositoryForDefinition(string definitionName) { if (string.IsNullOrEmpty(definitionName)) { throw new PSArgumentException("definitionName"); } // This returns a new list object of repository jobs. List<Job2> jobList = JobRepository.Jobs; foreach (var job in jobList) { if (string.Compare(definitionName, job.Name, StringComparison.OrdinalIgnoreCase) == 0) { JobRepository.Remove(job); } } } #endregion #region Private Methods private void RefreshRepository() { ScheduledJobStore.CreateDirectoryIfNotExists(); CreateFileSystemWatcher(); IEnumerable<string> jobDefinitions = ScheduledJobStore.GetJobDefinitions(); foreach (string definitionName in jobDefinitions) { // Create Job2 objects for each job run in store. Collection<DateTime> jobRuns = GetJobRuns(definitionName); if (jobRuns == null) { continue; } ScheduledJobDefinition definition = null; foreach (DateTime jobRun in jobRuns) { if (jobRun > JobRepository.GetLatestJobRun(definitionName)) { Job2 job; try { if (definition == null) { definition = ScheduledJobDefinition.LoadFromStore(definitionName, null); } job = LoadJobFromStore(definition.Name, jobRun); } catch (ScheduledJobException) { continue; } catch (DirectoryNotFoundException) { continue; } catch (FileNotFoundException) { continue; } catch (UnauthorizedAccessException) { continue; } catch (IOException) { continue; } JobRepository.AddOrReplace(job); JobRepository.SetLatestJobRun(definitionName, jobRun); } } } } private void CreateFileSystemWatcher() { // Lazily create the static file system watcher // on first use. if (StoreWatcher == null) { lock (SyncObject) { if (StoreWatcher == null) { StoreWatcher = new FileSystemWatcher(ScheduledJobStore.GetJobDefinitionLocation()); StoreWatcher.IncludeSubdirectories = true; StoreWatcher.NotifyFilter = NotifyFilters.LastWrite; StoreWatcher.Filter = "Results.xml"; StoreWatcher.EnableRaisingEvents = true; StoreWatcher.Changed += (object sender, FileSystemEventArgs e) => { UpdateRepositoryObjects(e); }; } } } } private static void UpdateRepositoryObjects(FileSystemEventArgs e) { // Extract job run information from change file path. string updateDefinitionName; DateTime updateJobRun; if (!GetJobRunInfo(e.Name, out updateDefinitionName, out updateJobRun)) { System.Diagnostics.Debug.Assert(false, "All job run updates should have valid directory names."); return; } // Find corresponding job in repository. ScheduledJob updateJob = JobRepository.GetJob(updateDefinitionName, updateJobRun); if (updateJob == null) { return; } // Load updated job information from store. Job2 job = null; try { job = LoadJobFromStore(updateDefinitionName, updateJobRun); } catch (ScheduledJobException) { } catch (DirectoryNotFoundException) { } catch (FileNotFoundException) { } catch (UnauthorizedAccessException) { } catch (IOException) { } // Update job in repository based on new job store data. if (job != null) { updateJob.Update(job as ScheduledJob); } } /// <summary> /// Parses job definition name and job run DateTime from provided path string. /// Example: /// path = "ScheduledJob1\\Output\\20111219-200921-369\\Results.xml" /// 'ScheduledJob1' is the definition name. /// '20111219-200921-369' is the jobRun DateTime. /// </summary> /// <param name="path"></param> /// <param name="definitionName"></param> /// <param name="jobRunReturn"></param> /// <returns></returns> private static bool GetJobRunInfo( string path, out string definitionName, out DateTime jobRunReturn) { // Parse definition name from path. string[] pathItems = path.Split(System.IO.Path.DirectorySeparatorChar); if (pathItems.Length == 4) { definitionName = pathItems[0]; return ScheduledJobStore.ConvertJobRunNameToDateTime(pathItems[2], out jobRunReturn); } definitionName = null; jobRunReturn = DateTime.MinValue; return false; } internal static Collection<DateTime> GetJobRuns(string definitionName) { Collection<DateTime> jobRuns = null; try { jobRuns = ScheduledJobStore.GetJobRunsForDefinition(definitionName); } catch (DirectoryNotFoundException) { } catch (FileNotFoundException) { } catch (UnauthorizedAccessException) { } catch (IOException) { } return jobRuns; } private void GetJobsBefore( DateTime dateTime, ref List<Job2> jobList) { foreach (var job in JobRepository.Jobs) { if (job.PSEndTime < dateTime && !jobList.Contains(job)) { jobList.Add(job); } } } private void GetJobsAfter( DateTime dateTime, ref List<Job2> jobList) { foreach (var job in JobRepository.Jobs) { if (job.PSEndTime > dateTime && !jobList.Contains(job)) { jobList.Add(job); } } } private void GetNewestJobs( int maxNumber, ref List<Job2> jobList) { List<Job2> allJobs = JobRepository.Jobs; // Sort descending. allJobs.Sort((firstJob, secondJob) => { if (firstJob.PSEndTime > secondJob.PSEndTime) { return -1; } else if (firstJob.PSEndTime < secondJob.PSEndTime) { return 1; } else { return 0; } }); int count = 0; foreach (var job in allJobs) { if (++count > maxNumber) { break; } if (!jobList.Contains(job)) { jobList.Add(job); } } } #endregion #region Private Repository Class /// <summary> /// Collection of Job2 objects. /// </summary> internal class ScheduledJobRepository { #region Private Members private object _syncObject = new object(); private Dictionary<Guid, Job2> _jobs = new Dictionary<Guid, Job2>(); private Dictionary<string, DateTime> _latestJobRuns = new Dictionary<string, DateTime>(); #endregion #region Public Properties /// <summary> /// Returns all job objects in the repository as a List. /// </summary> public List<Job2> Jobs { get { lock (_syncObject) { return new List<Job2>(_jobs.Values); } } } /// <summary> /// Returns count of jobs in repository. /// </summary> public int Count { get { lock (_syncObject) { return _jobs.Count; } } } #endregion #region Public Methods /// <summary> /// Add Job2 to repository. /// </summary> /// <param name="job">Job2 to add.</param> public void Add(Job2 job) { if (job == null) { throw new PSArgumentNullException("job"); } lock (_syncObject) { if (_jobs.ContainsKey(job.InstanceId)) { string msg = StringUtil.Format(ScheduledJobErrorStrings.ScheduledJobAlreadyExistsInLocal, job.Name, job.InstanceId); throw new ScheduledJobException(msg); } _jobs.Add(job.InstanceId, job); } } /// <summary> /// Add or replace passed in Job2 object to repository. /// </summary> /// <param name="job">Job2 to add.</param> public void AddOrReplace(Job2 job) { if (job == null) { throw new PSArgumentNullException("job"); } lock (_syncObject) { if (_jobs.ContainsKey(job.InstanceId)) { _jobs.Remove(job.InstanceId); } _jobs.Add(job.InstanceId, job); } } /// <summary> /// Remove Job2 from repository. /// </summary> /// <param name="job"></param> public void Remove(Job2 job) { if (job == null) { throw new PSArgumentNullException("job"); } lock (_syncObject) { if (_jobs.ContainsKey(job.InstanceId) == false) { string msg = StringUtil.Format(ScheduledJobErrorStrings.ScheduledJobNotInRepository, job.Name); throw new ScheduledJobException(msg); } _jobs.Remove(job.InstanceId); } } /// <summary> /// Clears all Job2 items from the repository. /// </summary> public void Clear() { lock (_syncObject) { _jobs.Clear(); } } /// <summary> /// Gets the latest job run Date/Time for the given definition name. /// </summary> /// <param name="definitionName">ScheduledJobDefinition name.</param> /// <returns>Job Run DateTime.</returns> public DateTime GetLatestJobRun(string definitionName) { if (string.IsNullOrEmpty(definitionName)) { throw new PSArgumentException("definitionName"); } lock (_syncObject) { if (_latestJobRuns.ContainsKey(definitionName)) { return _latestJobRuns[definitionName]; } else { DateTime startJobRun = DateTime.MinValue; _latestJobRuns.Add(definitionName, startJobRun); return startJobRun; } } } /// <summary> /// Sets the latest job run Date/Time for the given definition name. /// </summary> /// <param name="definitionName"></param> /// <param name="jobRun"></param> public void SetLatestJobRun(string definitionName, DateTime jobRun) { if (string.IsNullOrEmpty(definitionName)) { throw new PSArgumentException("definitionName"); } lock (_syncObject) { if (_latestJobRuns.ContainsKey(definitionName)) { _latestJobRuns.Remove(definitionName); _latestJobRuns.Add(definitionName, jobRun); } else { _latestJobRuns.Add(definitionName, jobRun); } } } /// <summary> /// Search repository for specific job run. /// </summary> /// <param name="definitionName">Definition name.</param> /// <param name="jobRun">Job run DateTime.</param> /// <returns>Scheduled job if found.</returns> public ScheduledJob GetJob(string definitionName, DateTime jobRun) { lock (_syncObject) { foreach (ScheduledJob job in _jobs.Values) { if (job.PSBeginTime == null) { continue; } DateTime PSBeginTime = job.PSBeginTime ?? DateTime.MinValue; if (definitionName.Equals(job.Definition.Name, StringComparison.OrdinalIgnoreCase) && jobRun.Year == PSBeginTime.Year && jobRun.Month == PSBeginTime.Month && jobRun.Day == PSBeginTime.Day && jobRun.Hour == PSBeginTime.Hour && jobRun.Minute == PSBeginTime.Minute && jobRun.Second == PSBeginTime.Second && jobRun.Millisecond == PSBeginTime.Millisecond) { return job; } } } return null; } #endregion } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////// // // // Purpose: This class implements a set of methods for retrieving // character type information. Character type information is // independent of culture and region. // // //////////////////////////////////////////////////////////////////////////// namespace System.Globalization { //This class has only static members and therefore doesn't need to be serialized. using System; using System.Threading; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Reflection; using System.Security; using System.Diagnostics.Contracts; public static class CharUnicodeInfo { //--------------------------------------------------------------------// // Internal Information // //--------------------------------------------------------------------// // // Native methods to access the Unicode category data tables in charinfo.nlp. // internal const char HIGH_SURROGATE_START = '\ud800'; internal const char HIGH_SURROGATE_END = '\udbff'; internal const char LOW_SURROGATE_START = '\udc00'; internal const char LOW_SURROGATE_END = '\udfff'; internal const int UNICODE_CATEGORY_OFFSET = 0; internal const int BIDI_CATEGORY_OFFSET = 1; static bool s_initialized = InitTable(); // The native pointer to the 12:4:4 index table of the Unicode cateogry data. [SecurityCritical] unsafe static ushort* s_pCategoryLevel1Index; [SecurityCritical] unsafe static byte* s_pCategoriesValue; // The native pointer to the 12:4:4 index table of the Unicode numeric data. // The value of this index table is an index into the real value table stored in s_pNumericValues. [SecurityCritical] unsafe static ushort* s_pNumericLevel1Index; // The numeric value table, which is indexed by s_pNumericLevel1Index. // Every item contains the value for numeric value. // unsafe static double* s_pNumericValues; // To get around the IA64 alignment issue. Our double data is aligned in 8-byte boundary, but loader loads the embeded table starting // at 4-byte boundary. This cause a alignment issue since double is 8-byte. [SecurityCritical] unsafe static byte* s_pNumericValues; // The digit value table, which is indexed by s_pNumericLevel1Index. It shares the same indice as s_pNumericValues. // Every item contains the value for decimal digit/digit value. [SecurityCritical] unsafe static DigitValues* s_pDigitValues; internal const String UNICODE_INFO_FILE_NAME = "charinfo.nlp"; // The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff. internal const int UNICODE_PLANE01_START = 0x10000; // // This is the header for the native data table that we load from UNICODE_INFO_FILE_NAME. // // Excplicit layout is used here since a syntax like char[16] can not be used in sequential layout. [StructLayout(LayoutKind.Explicit)] internal unsafe struct UnicodeDataHeader { [FieldOffset(0)] internal char TableName; // WCHAR[16] [FieldOffset(0x20)] internal ushort version; // WORD[4] [FieldOffset(0x28)] internal uint OffsetToCategoriesIndex; // DWORD [FieldOffset(0x2c)] internal uint OffsetToCategoriesValue; // DWORD [FieldOffset(0x30)] internal uint OffsetToNumbericIndex; // DWORD [FieldOffset(0x34)] internal uint OffsetToDigitValue; // DWORD [FieldOffset(0x38)] internal uint OffsetToNumbericValue; // DWORD } // NOTE: It's important to specify pack size here, since the size of the structure is 2 bytes. Otherwise, // the default pack size will be 4. [StructLayout(LayoutKind.Sequential, Pack=2)] internal struct DigitValues { internal sbyte decimalDigit; internal sbyte digit; } //We need to allocate the underlying table that provides us with the information that we //use. We allocate this once in the class initializer and then we don't need to worry //about it again. // [System.Security.SecuritySafeCritical] // auto-generated unsafe static bool InitTable() { // Go to native side and get pointer to the native table byte * pDataTable = GlobalizationAssembly.GetGlobalizationResourceBytePtr(typeof(CharUnicodeInfo).Assembly, UNICODE_INFO_FILE_NAME); UnicodeDataHeader* mainHeader = (UnicodeDataHeader*)pDataTable; // Set up the native pointer to different part of the tables. s_pCategoryLevel1Index = (ushort*) (pDataTable + mainHeader->OffsetToCategoriesIndex); s_pCategoriesValue = (byte*) (pDataTable + mainHeader->OffsetToCategoriesValue); s_pNumericLevel1Index = (ushort*) (pDataTable + mainHeader->OffsetToNumbericIndex); s_pNumericValues = (byte*) (pDataTable + mainHeader->OffsetToNumbericValue); s_pDigitValues = (DigitValues*) (pDataTable + mainHeader->OffsetToDigitValue); return true; } //////////////////////////////////////////////////////////////////////// // // Actions: // Convert the BMP character or surrogate pointed by index to a UTF32 value. // This is similar to Char.ConvertToUTF32, but the difference is that // it does not throw exceptions when invalid surrogate characters are passed in. // // WARNING: since it doesn't throw an exception it CAN return a value // in the surrogate range D800-DFFF, which are not legal unicode values. // //////////////////////////////////////////////////////////////////////// internal static int InternalConvertToUtf32(String s, int index) { Contract.Assert(s != null, "s != null"); Contract.Assert(index >= 0 && index < s.Length, "index < s.Length"); if (index < s.Length - 1) { int temp1 = (int)s[index] - HIGH_SURROGATE_START; if (temp1 >= 0 && temp1 <= 0x3ff) { int temp2 = (int)s[index+1] - LOW_SURROGATE_START; if (temp2 >= 0 && temp2 <= 0x3ff) { // Convert the surrogate to UTF32 and get the result. return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START); } } } return ((int)s[index]); } //////////////////////////////////////////////////////////////////////// // // Convert a character or a surrogate pair starting at index of string s // to UTF32 value. // // Parameters: // s The string // index The starting index. It can point to a BMP character or // a surrogate pair. // len The length of the string. // charLength [out] If the index points to a BMP char, charLength // will be 1. If the index points to a surrogate pair, // charLength will be 2. // // WARNING: since it doesn't throw an exception it CAN return a value // in the surrogate range D800-DFFF, which are not legal unicode values. // // Returns: // The UTF32 value // //////////////////////////////////////////////////////////////////////// internal static int InternalConvertToUtf32(String s, int index, out int charLength) { Contract.Assert(s != null, "s != null"); Contract.Assert(s.Length > 0, "s.Length > 0"); Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); charLength = 1; if (index < s.Length - 1) { int temp1 = (int)s[index] - HIGH_SURROGATE_START; if (temp1 >= 0 && temp1 <= 0x3ff) { int temp2 = (int)s[index+1] - LOW_SURROGATE_START; if (temp2 >= 0 && temp2 <= 0x3ff) { // Convert the surrogate to UTF32 and get the result. charLength++; return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START); } } } return ((int)s[index]); } //////////////////////////////////////////////////////////////////////// // // IsWhiteSpace // // Determines if the given character is a white space character. // //////////////////////////////////////////////////////////////////////// internal static bool IsWhiteSpace(String s, int index) { Contract.Assert(s != null, "s!=null"); Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); UnicodeCategory uc = GetUnicodeCategory(s, index); // In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator". // And U+2029 is th eonly character which is under the category "ParagraphSeparator". switch (uc) { case (UnicodeCategory.SpaceSeparator): case (UnicodeCategory.LineSeparator): case (UnicodeCategory.ParagraphSeparator): return (true); } return (false); } internal static bool IsWhiteSpace(char c) { UnicodeCategory uc = GetUnicodeCategory(c); // In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator". // And U+2029 is th eonly character which is under the category "ParagraphSeparator". switch (uc) { case (UnicodeCategory.SpaceSeparator): case (UnicodeCategory.LineSeparator): case (UnicodeCategory.ParagraphSeparator): return (true); } return (false); } // // This is called by the public char and string, index versions // // Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character // [System.Security.SecuritySafeCritical] // auto-generated internal unsafe static double InternalGetNumericValue(int ch) { Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 12 bit (8 - 19) of ch. ushort index = s_pNumericLevel1Index[ch >> 8]; // Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. // The offset is referred to an float item in m_pNumericFloatData. // Note that & has the lower precedence than addition, so don't forget the parathesis. index = s_pNumericLevel1Index[index + ((ch >> 4) & 0x000f)]; byte* pBytePtr = (byte*)&(s_pNumericLevel1Index[index]); // Get the result from the 0 -3 bit of ch. #if BIT64 // To get around the IA64 alignment issue. Our double data is aligned in 8-byte boundary, but loader loads the embeded table starting // at 4-byte boundary. This cause a alignment issue since double is 8-byte. byte* pSourcePtr = &(s_pNumericValues[pBytePtr[(ch & 0x000f)] * sizeof(double)]); if (((long)pSourcePtr % 8) != 0) { // We are not aligned in 8-byte boundary. Do a copy. double ret; byte* retPtr = (byte*)&ret; Buffer.Memcpy(retPtr, pSourcePtr, sizeof(double)); return (ret); } return (((double*)s_pNumericValues)[pBytePtr[(ch & 0x000f)]]); #else return (((double*)s_pNumericValues)[pBytePtr[(ch & 0x000f)]]); #endif } // // This is called by the public char and string, index versions // // Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character // [System.Security.SecuritySafeCritical] // auto-generated internal unsafe static DigitValues* InternalGetDigitValues(int ch) { Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 12 bit (8 - 19) of ch. ushort index = s_pNumericLevel1Index[ch >> 8]; // Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. // The offset is referred to an float item in m_pNumericFloatData. // Note that & has the lower precedence than addition, so don't forget the parathesis. index = s_pNumericLevel1Index[index + ((ch >> 4) & 0x000f)]; byte* pBytePtr = (byte*)&(s_pNumericLevel1Index[index]); // Get the result from the 0 -3 bit of ch. return &(s_pDigitValues[pBytePtr[(ch & 0x000f)]]); } [System.Security.SecuritySafeCritical] // auto-generated internal unsafe static sbyte InternalGetDecimalDigitValue(int ch) { return (InternalGetDigitValues(ch)->decimalDigit); } [System.Security.SecuritySafeCritical] // auto-generated internal unsafe static sbyte InternalGetDigitValue(int ch) { return (InternalGetDigitValues(ch)->digit); } //////////////////////////////////////////////////////////////////////// // //Returns the numeric value associated with the character c. If the character is a fraction, // the return value will not be an integer. If the character does not have a numeric value, the return value is -1. // //Returns: // the numeric value for the specified Unicode character. If the character does not have a numeric value, the return value is -1. //Arguments: // ch a Unicode character //Exceptions: // ArgumentNullException // ArgumentOutOfRangeException // //////////////////////////////////////////////////////////////////////// public static double GetNumericValue(char ch) { return (InternalGetNumericValue(ch)); } public static double GetNumericValue(String s, int index) { if (s == null) { throw new ArgumentNullException("s"); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.EndContractBlock(); return (InternalGetNumericValue(InternalConvertToUtf32(s, index))); } //////////////////////////////////////////////////////////////////////// // //Returns the decimal digit value associated with the character c. // // The value should be from 0 ~ 9. // If the character does not have a numeric value, the return value is -1. // From Unicode.org: Decimal Digits. Digits that can be used to form decimal-radix numbers. //Returns: // the decimal digit value for the specified Unicode character. If the character does not have a decimal digit value, the return value is -1. //Arguments: // ch a Unicode character //Exceptions: // ArgumentNullException // ArgumentOutOfRangeException // //////////////////////////////////////////////////////////////////////// public static int GetDecimalDigitValue(char ch) { return (InternalGetDecimalDigitValue(ch)); } public static int GetDecimalDigitValue(String s, int index) { if (s == null) { throw new ArgumentNullException("s"); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.EndContractBlock(); return (InternalGetDecimalDigitValue(InternalConvertToUtf32(s, index))); } //////////////////////////////////////////////////////////////////////// // //Action: Returns the digit value associated with the character c. // If the character does not have a numeric value, the return value is -1. // From Unicode.org: If the character represents a digit, not necessarily a decimal digit, // the value is here. This covers digits which do not form decimal radix forms, such as the compatibility superscript digits. // // An example is: U+2460 IRCLED DIGIT ONE. This character has digit value 1, but does not have associcated decimal digit value. // //Returns: // the digit value for the specified Unicode character. If the character does not have a digit value, the return value is -1. //Arguments: // ch a Unicode character //Exceptions: // ArgumentNullException // ArgumentOutOfRangeException // //////////////////////////////////////////////////////////////////////// public static int GetDigitValue(char ch) { return (InternalGetDigitValue(ch)); } public static int GetDigitValue(String s, int index) { if (s == null) { throw new ArgumentNullException("s"); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.EndContractBlock(); return (InternalGetDigitValue(InternalConvertToUtf32(s, index))); } public static UnicodeCategory GetUnicodeCategory(char ch) { return (InternalGetUnicodeCategory(ch)) ; } public static UnicodeCategory GetUnicodeCategory(String s, int index) { if (s==null) throw new ArgumentNullException("s"); if (((uint)index)>=((uint)s.Length)) { throw new ArgumentOutOfRangeException("index"); } Contract.EndContractBlock(); return InternalGetUnicodeCategory(s, index); } internal unsafe static UnicodeCategory InternalGetUnicodeCategory(int ch) { return ((UnicodeCategory)InternalGetCategoryValue(ch, UNICODE_CATEGORY_OFFSET)); } //////////////////////////////////////////////////////////////////////// // //Action: Returns the Unicode Category property for the character c. //Returns: // an value in UnicodeCategory enum //Arguments: // ch a Unicode character //Exceptions: // None // //Note that this API will return values for D800-DF00 surrogate halves. // //////////////////////////////////////////////////////////////////////// [System.Security.SecuritySafeCritical] // auto-generated internal unsafe static byte InternalGetCategoryValue(int ch, int offset) { Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 12 bit (8 - 19) of ch. ushort index = s_pCategoryLevel1Index[ch >> 8]; // Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. // Note that & has the lower precedence than addition, so don't forget the parathesis. index = s_pCategoryLevel1Index[index + ((ch >> 4) & 0x000f)]; byte* pBytePtr = (byte*)&(s_pCategoryLevel1Index[index]); // Get the result from the 0 -3 bit of ch. byte valueIndex = pBytePtr[(ch & 0x000f)]; byte uc = s_pCategoriesValue[valueIndex * 2 + offset]; // // Make sure that OtherNotAssigned is the last category in UnicodeCategory. // If that changes, change the following assertion as well. // //Contract.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category"); return (uc); } // internal static BidiCategory GetBidiCategory(char ch) { // return ((BidiCategory)InternalGetCategoryValue(c, BIDI_CATEGORY_OFFSET)); // } internal static BidiCategory GetBidiCategory(String s, int index) { if (s==null) throw new ArgumentNullException("s"); if (((uint)index)>=((uint)s.Length)) { throw new ArgumentOutOfRangeException("index"); } Contract.EndContractBlock(); return ((BidiCategory)InternalGetCategoryValue(InternalConvertToUtf32(s, index), BIDI_CATEGORY_OFFSET)); } //////////////////////////////////////////////////////////////////////// // //Action: Returns the Unicode Category property for the character c. //Returns: // an value in UnicodeCategory enum //Arguments: // value a Unicode String // index Index for the specified string. //Exceptions: // None // //////////////////////////////////////////////////////////////////////// internal static UnicodeCategory InternalGetUnicodeCategory(String value, int index) { Contract.Assert(value != null, "value can not be null"); Contract.Assert(index < value.Length, "index < value.Length"); return (InternalGetUnicodeCategory(InternalConvertToUtf32(value, index))); } //////////////////////////////////////////////////////////////////////// // // Get the Unicode category of the character starting at index. If the character is in BMP, charLength will return 1. // If the character is a valid surrogate pair, charLength will return 2. // //////////////////////////////////////////////////////////////////////// internal static UnicodeCategory InternalGetUnicodeCategory(String str, int index, out int charLength) { Contract.Assert(str != null, "str can not be null"); Contract.Assert(str.Length > 0, "str.Length > 0");; Contract.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length"); return (InternalGetUnicodeCategory(InternalConvertToUtf32(str, index, out charLength))); } internal static bool IsCombiningCategory(UnicodeCategory uc) { Contract.Assert(uc >= 0, "uc >= 0"); return ( uc == UnicodeCategory.NonSpacingMark || uc == UnicodeCategory.SpacingCombiningMark || uc == UnicodeCategory.EnclosingMark ); } } }
// C# practical work using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace Lesson2 { // An interface for making an input command // We can only define functions. // They are 'public' be default. interface InputCommand { // All must have a way to return the name of the command. string GetName(); // All commands must have an Execute function which takes a string. // The 'arguments' string can be empty "" or it can have data: "true", "false", "1", "0" etc. void Execute( string arguments ); // Add a function to see test if a command should be removed bool ShouldRemove(); } // A simple class. // It 'inherits' from InputComand // See how it 'implements' the interface // - we dont use the 'public' property on the function // - we specify the interface name when naming the function 'InputCommand.FUNCTION' class Exit : InputCommand { private bool _exit = false; public bool ShouldExit() { return _exit; } // Implement the InputCommand interface below string InputCommand.GetName() { return "ExitProgram"; } void InputCommand.Execute(string arguments) { _exit = true; System.Console.WriteLine("Goodbye!"); System.Threading.Thread.Sleep(1000); // 1 second delay. } bool InputCommand.ShouldRemove() { return false; } } // A input which needs an on/off arguments passed to it // See how we can return a class member in hte 'GetName' funciton. class GodMode : InputCommand { private string _myCommandName = "GodMode"; private bool _inGodMode = false; // Implement the InputCommand interface below string InputCommand.GetName() { return _myCommandName; } void InputCommand.Execute( string arguments ) { // This is an example of complex logic. // There are three options for turning on the flag... if ( arguments == "on" || arguments == "true" || arguments == "1" ) { if ( !_inGodMode ) { _inGodMode = true; System.Console.WriteLine( "{0} is now {1}", _myCommandName, _inGodMode ); } } // ... and three options for turning off the flag! else if ( arguments == "off" || arguments == "false" || arguments == "0" ) { if ( _inGodMode ) { _inGodMode = false; System.Console.WriteLine( "{0} is now {1}", _myCommandName, _inGodMode ); } } // Maybe there should be some feedback when the function fails to do anything? } bool InputCommand.ShouldRemove() { return false; } } // A class made to pass around the result of the user input to the program. class UserInput { private string _command = ""; private string _arguments = ""; public string GetCommand() { return _command; } public void SetCommand( string command ) { _command = command; } public string GetArguments() { return _arguments; } public void SetArguments( string arguments ) { _arguments = arguments; } } class HelloPerson : InputCommand { public string Name { get; set; } // Implement the InputCommand interface below string InputCommand.GetName() { return Name; } void InputCommand.Execute(string arguments) { System.Console.WriteLine("Hello, {0}!", Name ); } bool InputCommand.ShouldRemove() { return false; } } class Counter : InputCommand { private int _count = 0; // Implement the InputCommand interface below string InputCommand.GetName() { return "Counter"; } void InputCommand.Execute(string arguments) { _count += 1; System.Console.WriteLine("Executed {0} times!", _count ); } bool InputCommand.ShouldRemove() { return _count > 2; } } class Shape: InputCommand { virtual public string GetShapeName() { return "Shape"; } virtual public double GetArea() { return 0; } // Implement the InputCommand interface below string InputCommand.GetName() { return GetShapeName(); } void InputCommand.Execute(string arguments) { System.Console.WriteLine("The area of '{0}' is {1} meters squared.", GetShapeName(), GetArea() ); } bool InputCommand.ShouldRemove() { return false; } } class Square : Shape { public int Width { get; set; } override public string GetShapeName() { return "Square"; } override public double GetArea() { return Width * Width; } } class Circle : Shape { public int Radius { get; set; } override public string GetShapeName() { return "Circle"; } override public double GetArea() { return Math.PI * ( Radius * Radius ); } } class Program { // The static entry point of the program. static void Main(string[] args) { // An empty list of commands. List<InputCommand> inputs = new List<InputCommand>(); // Create some instances which implement the InputCommand interface. GodMode godMode = new GodMode(); Exit exit = new Exit(); HelloPerson nathan = new HelloPerson(); nathan.Name = "Nathan"; HelloPerson elliot = new HelloPerson() { Name = "Elliot" }; // ... and more ... // Add them to the list. // The list is of type 'InputCommand', yet these different class types can be added! inputs.Add( godMode ); inputs.Add( exit ); inputs.Add( nathan ); inputs.Add( elliot ); inputs.Add( new Counter() ); inputs.Add( new Square() { Width = 5 } ); inputs.Add( new Circle() { Radius = 2 } ); // Loop until we should exit. while (exit.ShouldExit() == false) { // Get the user input. UserInput userInput = GetUserInput("Enter A Command:"); // Make sure we have something. if (userInput.GetCommand() != "" ) { // Loop all of our commands. foreach (InputCommand i in inputs.ToArray()) // Get the array representation of the list - this makes a copy. { // Check to see if the name matches. if (userInput.GetCommand() == i.GetName()) { i.Execute(userInput.GetArguments()); if ( i.ShouldRemove() ) { System.Console.WriteLine( "Removing {0}...", i.GetName() ); inputs.Remove( i ); // do not remove something from a list if you are looping it. But we are looping a copy of the list. } } } } } } // A helper function for getting user input. // The input text will be split at the first space. // This means the first word will be in _command // and all of the rest will be in _arguments. // - [ "myCommand" ] // - [ "myCommand", "argument" ] // - [ "myCommand", "argument1 argument2 ..." ] static UserInput GetUserInput(string prompt) { // Tell the user what they should input. System.Console.WriteLine(prompt); // Read in the user input. string inputLine = System.Console.ReadLine(); // Split into two strings at the first space ' ' character. // This can result in only one item. string[] splits = inputLine.Split( new char[]{' '}, 2); UserInput userInput = new UserInput(); userInput.SetCommand( splits[0] ); if ( splits.Length > 1 ) { userInput.SetArguments( splits[1] ); } // return the UserInput class. return userInput; } } }
/* ChatObject_subscriber.cs A subscription example This file is derived from code automatically generated by the rtiddsgen command: rtiddsgen -language C# -example <arch> Chat.idl Example subscription of type ChatObject automatically generated by 'rtiddsgen'. To test them, follow these steps: (1) Compile this file and the example publication. (2) Start the subscription with the command objs\<arch>${constructMap.nativeFQNameInModule}_subscriber <domain_id> <sample_count> (3) Start the publication with the command objs\<arch>${constructMap.nativeFQNameInModule}_publisher <domain_id> <sample_count> (4) [Optional] Specify the list of discovery initial peers and multicast receive addresses via an environment variable or a file (in the current working directory) called NDDS_DISCOVERY_PEERS. You can run any number of publishers and subscribers programs, and can add and remove them dynamically from the domain. Example: To run the example application on domain <domain_id>: bin\<Debug|Release>\ChatObject_publisher <domain_id> <sample_count> bin\<Debug|Release>\ChatObject_subscriber <domain_id> <sample_count> */ using System; using System.Collections.Generic; using System.Text; namespace My{ public class ChatObjectSubscriber { public class ChatObjectListener : DDS.DataReaderListener { public override void on_requested_deadline_missed( DDS.DataReader reader, ref DDS.RequestedDeadlineMissedStatus status) {} public override void on_requested_incompatible_qos( DDS.DataReader reader, DDS.RequestedIncompatibleQosStatus status) {} public override void on_sample_rejected( DDS.DataReader reader, ref DDS.SampleRejectedStatus status) {} public override void on_liveliness_changed( DDS.DataReader reader, ref DDS.LivelinessChangedStatus status) {} public override void on_sample_lost( DDS.DataReader reader, ref DDS.SampleLostStatus status) {} public override void on_subscription_matched( DDS.DataReader reader, ref DDS.SubscriptionMatchedStatus status) {} public override void on_data_available(DDS.DataReader reader) { ChatObjectDataReader ChatObject_reader = (ChatObjectDataReader)reader; try { ChatObject_reader.read( /*>>><<<*/ data_seq, info_seq, DDS.ResourceLimitsQosPolicy.LENGTH_UNLIMITED, DDS.SampleStateKind.ANY_SAMPLE_STATE, DDS.ViewStateKind.ANY_VIEW_STATE, DDS.InstanceStateKind.ANY_INSTANCE_STATE); } catch(DDS.Retcode_NoData) { return; } catch(DDS.Exception e) { Console.WriteLine("take/read error {0}", e); /*>>><<<*/ return; } System.Int32 data_length = data_seq.length; for (int i = 0; i < data_length; ++i) { if (info_seq.get_at(i).valid_data) { ChatObjectTypeSupport.print_data(data_seq.get_at(i)); } } try { ChatObject_reader.return_loan(data_seq, info_seq); } catch(DDS.Exception e) { Console.WriteLine("return loan error {0}", e); } } public ChatObjectListener() { data_seq = new ChatObjectSeq(); info_seq = new DDS.SampleInfoSeq(); } private ChatObjectSeq data_seq; private DDS.SampleInfoSeq info_seq; }; public static void Main(string[] args) { // --- Get domain ID --- // int domain_id = 0; if (args.Length >= 1) { domain_id = Int32.Parse(args[0]); } // --- Get max loop count; 0 means infinite loop --- // int sample_count = 0; if (args.Length >= 2) { sample_count = Int32.Parse(args[1]); } /* Uncomment this to turn on additional logging NDDS.ConfigLogger.get_instance().set_verbosity_by_category( NDDS.LogCategory.NDDS_CONFIG_LOG_CATEGORY_API, NDDS.LogVerbosity.NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL); */ // --- Run --- // try { ChatObjectSubscriber.subscribe( domain_id, sample_count); } catch(DDS.Exception) { Console.WriteLine("error in subscriber"); } } static void subscribe(int domain_id, int sample_count) { // --- Register userGenerated datatype --- DDS.DomainParticipantFactory.get_instance(). register_type_support( ChatObjectTypeSupport.get_instance(), "My::Type::Chat::Obj"); // --- Create participant --- // /* To customize the participant QoS, use the configuration file USER_QOS_PROFILES.xml */ DDS.DomainParticipant participant = DDS.DomainParticipantFactory.get_instance(). create_participant_from_config( "MyParticipant_Library::MySubscriptionParticipant"); if (participant == null) { shutdown(participant); throw new ApplicationException("create_participant error"); } /* Create a data reader listener */ ChatObjectListener reader_listener = new ChatObjectListener(); // --- Lookup reader --- // /* To customize the data reader QoS, use the configuration file USER_QOS_PROFILES.xml */ DDS.DataReader reader = participant.lookup_datareader_by_name( "MySubscriber::ChatObjectReader"); if (reader == null) { shutdown(participant); reader_listener = null; throw new ApplicationException("lookup_datareader error"); } /* >>> Setup StatusCondition */ DDS.StatusCondition status_condition = reader.get_statuscondition(); if (status_condition.Equals(null)) { Console.WriteLine("get_statuscondition error\n"); shutdown(participant); throw new ApplicationException("get_statuscondition error"); } try { status_condition.set_enabled_statuses((DDS.StatusMask)DDS.StatusKind.DATA_AVAILABLE_STATUS); } catch { Console.WriteLine("set_enabled_statuses error\n"); shutdown(participant); throw new ApplicationException("set_enabled_statuses error"); } /* <<< */ /* >>> Setup WaitSet */ DDS.WaitSet waitset = new DDS.WaitSet(); try { waitset.attach_condition(status_condition); } catch { // ... error waitset.Dispose(); waitset = null; shutdown(participant); reader_listener.Dispose(); reader_listener = null; return; } // holder for active conditions DDS.ConditionSeq active_conditions = new DDS.ConditionSeq(); /* <<< */ // --- Wait for data --- // /* Main loop */ const System.Int32 receive_period = 4000; // milliseconds for (int count=0; (sample_count == 0) || (count < sample_count); ++count) { Console.WriteLine( "ChatObject subscriber sleeping ...", receive_period / 1000); /* >>> Wait for condition to trigger */ try { waitset.wait(active_conditions, DDS.Duration_t.DURATION_INFINITE); reader_listener.on_data_available(reader); } catch { } /* <<< */ // System.Threading.Thread.Sleep(receive_period); /*>>><<<*/ } // --- Shutdown --- // /* Delete all entities */ waitset.Dispose(); waitset = null; /*>>><<<*/ shutdown(participant); reader_listener = null; } static void shutdown( DDS.DomainParticipant participant) { /* Delete all entities */ if (participant != null) { participant.delete_contained_entities(); DDS.DomainParticipantFactory.get_instance().delete_participant( ref participant); } /* RTI Connext provides finalize_instance() method on domain participant factory for users who want to release memory used by the participant factory. Uncomment the following block of code for clean destruction of the singleton. */ /* try { DDS.DomainParticipantFactory.finalize_instance(); } catch(DDS.Exception e) { Console.WriteLine("finalize_instance error {0}", e); throw e; } */ } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security; using System.Text; using OpenMetaverse; namespace OpenSim.Region.PhysicsModule.BulletS { // Constraint type values as defined by Bullet public enum ConstraintType : int { POINT2POINT_CONSTRAINT_TYPE = 3, HINGE_CONSTRAINT_TYPE, CONETWIST_CONSTRAINT_TYPE, D6_CONSTRAINT_TYPE, SLIDER_CONSTRAINT_TYPE, CONTACT_CONSTRAINT_TYPE, D6_SPRING_CONSTRAINT_TYPE, GEAR_CONSTRAINT_TYPE, // added in Bullet 2.82 FIXED_CONSTRAINT_TYPE, // added in Bullet 2.82 MAX_CONSTRAINT_TYPE, // last type defined by Bullet // BS_FIXED_CONSTRAINT_TYPE = 1234 // BulletSim constraint that is fixed and unmoving } // =============================================================================== [StructLayout(LayoutKind.Sequential)] public struct ConvexHull { Vector3 Offset; int VertexCount; Vector3[] Vertices; } public enum BSPhysicsShapeType { SHAPE_UNKNOWN = 0, SHAPE_CAPSULE = 1, SHAPE_BOX = 2, SHAPE_CONE = 3, SHAPE_CYLINDER = 4, SHAPE_SPHERE = 5, SHAPE_MESH = 6, SHAPE_HULL = 7, // following defined by BulletSim SHAPE_GROUNDPLANE = 20, SHAPE_TERRAIN = 21, SHAPE_COMPOUND = 22, SHAPE_HEIGHTMAP = 23, SHAPE_AVATAR = 24, SHAPE_CONVEXHULL= 25, SHAPE_GIMPACT = 26, }; // The native shapes have predefined shape hash keys public enum FixedShapeKey : ulong { KEY_NONE = 0, KEY_BOX = 1, KEY_SPHERE = 2, KEY_CONE = 3, KEY_CYLINDER = 4, KEY_CAPSULE = 5, KEY_AVATAR = 6, } [StructLayout(LayoutKind.Sequential)] public struct ShapeData { public UInt32 ID; public BSPhysicsShapeType Type; public Vector3 Position; public Quaternion Rotation; public Vector3 Velocity; public Vector3 Scale; public float Mass; public float Buoyancy; public System.UInt64 HullKey; public System.UInt64 MeshKey; public float Friction; public float Restitution; public float Collidable; // true of things bump into this public float Static; // true if a static object. Otherwise gravity, etc. public float Solid; // true if object cannot be passed through public Vector3 Size; // note that bools are passed as floats since bool size changes by language and architecture public const float numericTrue = 1f; public const float numericFalse = 0f; } [StructLayout(LayoutKind.Sequential)] public struct SweepHit { public UInt32 ID; public float Fraction; public Vector3 Normal; public Vector3 Point; } [StructLayout(LayoutKind.Sequential)] public struct RaycastHit { public UInt32 ID; public float Fraction; public Vector3 Normal; } [StructLayout(LayoutKind.Sequential)] public struct CollisionDesc { public UInt32 aID; public UInt32 bID; public Vector3 point; public Vector3 normal; public float penetration; } [StructLayout(LayoutKind.Sequential)] public struct EntityProperties { public UInt32 ID; public Vector3 Position; public Quaternion Rotation; public Vector3 Velocity; public Vector3 Acceleration; public Vector3 RotationalVelocity; public override string ToString() { StringBuilder buff = new StringBuilder(); buff.Append("<i="); buff.Append(ID.ToString()); buff.Append(",p="); buff.Append(Position.ToString()); buff.Append(",r="); buff.Append(Rotation.ToString()); buff.Append(",v="); buff.Append(Velocity.ToString()); buff.Append(",a="); buff.Append(Acceleration.ToString()); buff.Append(",rv="); buff.Append(RotationalVelocity.ToString()); buff.Append(">"); return buff.ToString(); } } // Format of this structure must match the definition in the C++ code // NOTE: adding the X causes compile breaks if used. These are unused symbols // that can be removed from both here and the unmanaged definition of this structure. [StructLayout(LayoutKind.Sequential)] public struct ConfigurationParameters { public float defaultFriction; public float defaultDensity; public float defaultRestitution; public float collisionMargin; public float gravity; public float maxPersistantManifoldPoolSize; public float maxCollisionAlgorithmPoolSize; public float shouldDisableContactPoolDynamicAllocation; public float shouldForceUpdateAllAabbs; public float shouldRandomizeSolverOrder; public float shouldSplitSimulationIslands; public float shouldEnableFrictionCaching; public float numberOfSolverIterations; public float useSingleSidedMeshes; public float globalContactBreakingThreshold; public float physicsLoggingFrames; public const float numericTrue = 1f; public const float numericFalse = 0f; } // Parameters passed for the conversion of a mesh to a hull using Bullet's HACD library. [StructLayout(LayoutKind.Sequential)] public struct HACDParams { // usual default values public float maxVerticesPerHull; // 100 public float minClusters; // 2 public float compacityWeight; // 0.1 public float volumeWeight; // 0.0 public float concavity; // 100 public float addExtraDistPoints; // false public float addNeighboursDistPoints; // false public float addFacesPoints; // false public float shouldAdjustCollisionMargin; // false // VHACD public float whichHACD; // zero if Bullet HACD, non-zero says VHACD // http://kmamou.blogspot.ca/2014/12/v-hacd-20-parameters-description.html public float vHACDresolution; // 100,000 max number of voxels generated during voxelization stage public float vHACDdepth; // 20 max number of clipping stages public float vHACDconcavity; // 0.0025 maximum concavity public float vHACDplaneDownsampling; // 4 granularity of search for best clipping plane public float vHACDconvexHullDownsampling; // 4 precision of hull gen process public float vHACDalpha; // 0.05 bias toward clipping along symmetry planes public float vHACDbeta; // 0.05 bias toward clipping along revolution axis public float vHACDgamma; // 0.00125 max concavity when merging public float vHACDpca; // 0 on/off normalizing mesh before decomp public float vHACDmode; // 0 0:voxel based, 1: tetrahedron based public float vHACDmaxNumVerticesPerCH; // 64 max triangles per convex hull public float vHACDminVolumePerCH; // 0.0001 sampling of generated convex hulls } // The states a bullet collision object can have public enum ActivationState : uint { ACTIVE_TAG = 1, ISLAND_SLEEPING, WANTS_DEACTIVATION, DISABLE_DEACTIVATION, DISABLE_SIMULATION, } public enum CollisionObjectTypes : int { CO_COLLISION_OBJECT = 1 << 0, CO_RIGID_BODY = 1 << 1, CO_GHOST_OBJECT = 1 << 2, CO_SOFT_BODY = 1 << 3, CO_HF_FLUID = 1 << 4, CO_USER_TYPE = 1 << 5, } // Values used by Bullet and BulletSim to control object properties. // Bullet's "CollisionFlags" has more to do with operations on the // object (if collisions happen, if gravity effects it, ...). public enum CollisionFlags : uint { CF_STATIC_OBJECT = 1 << 0, CF_KINEMATIC_OBJECT = 1 << 1, CF_NO_CONTACT_RESPONSE = 1 << 2, CF_CUSTOM_MATERIAL_CALLBACK = 1 << 3, CF_CHARACTER_OBJECT = 1 << 4, CF_DISABLE_VISUALIZE_OBJECT = 1 << 5, CF_DISABLE_SPU_COLLISION_PROCESS = 1 << 6, // Following used by BulletSim to control collisions and updates BS_SUBSCRIBE_COLLISION_EVENTS = 1 << 10, // return collision events from unmanaged to managed BS_FLOATS_ON_WATER = 1 << 11, // the object should float at water level BS_VEHICLE_COLLISIONS = 1 << 12, // return collisions for vehicle ground checking BS_RETURN_ROOT_COMPOUND_SHAPE = 1 << 13, // return the pos/rot of the root shape in a compound shape BS_NONE = 0, BS_ALL = 0x7FFF // collision flags are a signed short }; // Values f collisions groups and masks public enum CollisionFilterGroups : uint { // Don't use the bit definitions!! Define the use in a // filter/mask definition below. This way collision interactions // are more easily found and debugged. BNoneGroup = 0, BDefaultGroup = 1 << 0, // 0001 BStaticGroup = 1 << 1, // 0002 BKinematicGroup = 1 << 2, // 0004 BDebrisGroup = 1 << 3, // 0008 BSensorTrigger = 1 << 4, // 0010 BCharacterGroup = 1 << 5, // 0020 BAllGroup = 0x0007FFF, // collision flags are a signed short // Filter groups defined by BulletSim BGroundPlaneGroup = 1 << 8, // 0400 BTerrainGroup = 1 << 9, // 0800 BRaycastGroup = 1 << 10, // 1000 BSolidGroup = 1 << 11, // 2000 // BLinksetGroup = xx // a linkset proper is either static or dynamic BLinksetChildGroup = 1 << 12, // 4000 }; // CFM controls the 'hardness' of the constraint. 0=fixed, 0..1=violatable. Default=0 // ERP controls amount of correction per tick. Usable range=0.1..0.8. Default=0.2. public enum ConstraintParams : int { BT_CONSTRAINT_ERP = 1, // this one is not used in Bullet as of 20120730 BT_CONSTRAINT_STOP_ERP, BT_CONSTRAINT_CFM, BT_CONSTRAINT_STOP_CFM, }; public enum ConstraintParamAxis : int { AXIS_LINEAR_X = 0, AXIS_LINEAR_Y, AXIS_LINEAR_Z, AXIS_ANGULAR_X, AXIS_ANGULAR_Y, AXIS_ANGULAR_Z, AXIS_LINEAR_ALL = 20, // added by BulletSim so we don't have to do zillions of calls AXIS_ANGULAR_ALL, AXIS_ALL }; public abstract class BSAPITemplate { // Returns the name of the underlying Bullet engine public abstract string BulletEngineName { get; } public abstract string BulletEngineVersion { get; protected set;} // Initialization and simulation public abstract BulletWorld Initialize(Vector3 maxPosition, ConfigurationParameters parms, int maxCollisions, ref CollisionDesc[] collisionArray, int maxUpdates, ref EntityProperties[] updateArray ); public abstract int PhysicsStep(BulletWorld world, float timeStep, int maxSubSteps, float fixedTimeStep, out int updatedEntityCount, out int collidersCount); public abstract bool UpdateParameter(BulletWorld world, UInt32 localID, String parm, float value); public abstract void Shutdown(BulletWorld sim); public abstract bool PushUpdate(BulletBody obj); // ===================================================================================== // Mesh, hull, shape and body creation helper routines public abstract BulletShape CreateMeshShape(BulletWorld world, int indicesCount, int[] indices, int verticesCount, float[] vertices ); public abstract BulletShape CreateGImpactShape(BulletWorld world, int indicesCount, int[] indices, int verticesCount, float[] vertices ); public abstract BulletShape CreateHullShape(BulletWorld world, int hullCount, float[] hulls); public abstract BulletShape BuildHullShapeFromMesh(BulletWorld world, BulletShape meshShape, HACDParams parms); public abstract BulletShape BuildConvexHullShapeFromMesh(BulletWorld world, BulletShape meshShape); public abstract BulletShape CreateConvexHullShape(BulletWorld world, int indicesCount, int[] indices, int verticesCount, float[] vertices ); public abstract BulletShape BuildNativeShape(BulletWorld world, ShapeData shapeData); public abstract bool IsNativeShape(BulletShape shape); public abstract void SetShapeCollisionMargin(BulletShape shape, float margin); public abstract BulletShape BuildCapsuleShape(BulletWorld world, float radius, float height, Vector3 scale); public abstract BulletShape CreateCompoundShape(BulletWorld sim, bool enableDynamicAabbTree); public abstract int GetNumberOfCompoundChildren(BulletShape cShape); public abstract void AddChildShapeToCompoundShape(BulletShape cShape, BulletShape addShape, Vector3 pos, Quaternion rot); public abstract BulletShape GetChildShapeFromCompoundShapeIndex(BulletShape cShape, int indx); public abstract BulletShape RemoveChildShapeFromCompoundShapeIndex(BulletShape cShape, int indx); public abstract void RemoveChildShapeFromCompoundShape(BulletShape cShape, BulletShape removeShape); public abstract void UpdateChildTransform(BulletShape pShape, int childIndex, Vector3 pos, Quaternion rot, bool shouldRecalculateLocalAabb); public abstract void RecalculateCompoundShapeLocalAabb(BulletShape cShape); public abstract BulletShape DuplicateCollisionShape(BulletWorld sim, BulletShape srcShape, UInt32 id); public abstract bool DeleteCollisionShape(BulletWorld world, BulletShape shape); public abstract CollisionObjectTypes GetBodyType(BulletBody obj); public abstract BulletBody CreateBodyFromShape(BulletWorld sim, BulletShape shape, UInt32 id, Vector3 pos, Quaternion rot); public abstract BulletBody CreateBodyWithDefaultMotionState(BulletShape shape, UInt32 id, Vector3 pos, Quaternion rot); public abstract BulletBody CreateGhostFromShape(BulletWorld sim, BulletShape shape, UInt32 id, Vector3 pos, Quaternion rot); public abstract void DestroyObject(BulletWorld sim, BulletBody obj); // ===================================================================================== public abstract BulletShape CreateGroundPlaneShape(UInt32 id, float height, float collisionMargin); public abstract BulletShape CreateTerrainShape(UInt32 id, Vector3 size, float minHeight, float maxHeight, float[] heightMap, float scaleFactor, float collisionMargin); // ===================================================================================== // Constraint creation and helper routines public abstract BulletConstraint Create6DofConstraint(BulletWorld world, BulletBody obj1, BulletBody obj2, Vector3 frame1loc, Quaternion frame1rot, Vector3 frame2loc, Quaternion frame2rot, bool useLinearReferenceFrameA, bool disableCollisionsBetweenLinkedBodies); public abstract BulletConstraint Create6DofConstraintToPoint(BulletWorld world, BulletBody obj1, BulletBody obj2, Vector3 joinPoint, bool useLinearReferenceFrameA, bool disableCollisionsBetweenLinkedBodies); public abstract BulletConstraint Create6DofConstraintFixed(BulletWorld world, BulletBody obj1, Vector3 frameInBloc, Quaternion frameInBrot, bool useLinearReferenceFrameB, bool disableCollisionsBetweenLinkedBodies); public abstract BulletConstraint Create6DofSpringConstraint(BulletWorld world, BulletBody obj1, BulletBody obj2, Vector3 frame1loc, Quaternion frame1rot, Vector3 frame2loc, Quaternion frame2rot, bool useLinearReferenceFrameA, bool disableCollisionsBetweenLinkedBodies); public abstract BulletConstraint CreateHingeConstraint(BulletWorld world, BulletBody obj1, BulletBody obj2, Vector3 pivotinA, Vector3 pivotinB, Vector3 axisInA, Vector3 axisInB, bool useLinearReferenceFrameA, bool disableCollisionsBetweenLinkedBodies); public abstract BulletConstraint CreateSliderConstraint(BulletWorld world, BulletBody obj1, BulletBody obj2, Vector3 frameInAloc, Quaternion frameInArot, Vector3 frameInBloc, Quaternion frameInBrot, bool useLinearReferenceFrameA, bool disableCollisionsBetweenLinkedBodies); public abstract BulletConstraint CreateConeTwistConstraint(BulletWorld world, BulletBody obj1, BulletBody obj2, Vector3 frameInAloc, Quaternion frameInArot, Vector3 frameInBloc, Quaternion frameInBrot, bool disableCollisionsBetweenLinkedBodies); public abstract BulletConstraint CreateGearConstraint(BulletWorld world, BulletBody obj1, BulletBody obj2, Vector3 axisInA, Vector3 axisInB, float ratio, bool disableCollisionsBetweenLinkedBodies); public abstract BulletConstraint CreatePoint2PointConstraint(BulletWorld world, BulletBody obj1, BulletBody obj2, Vector3 pivotInA, Vector3 pivotInB, bool disableCollisionsBetweenLinkedBodies); public abstract void SetConstraintEnable(BulletConstraint constrain, float numericTrueFalse); public abstract void SetConstraintNumSolverIterations(BulletConstraint constrain, float iterations); public abstract bool SetFrames(BulletConstraint constrain, Vector3 frameA, Quaternion frameArot, Vector3 frameB, Quaternion frameBrot); public abstract bool SetLinearLimits(BulletConstraint constrain, Vector3 low, Vector3 hi); public abstract bool SetAngularLimits(BulletConstraint constrain, Vector3 low, Vector3 hi); public abstract bool UseFrameOffset(BulletConstraint constrain, float enable); public abstract bool TranslationalLimitMotor(BulletConstraint constrain, float enable, float targetVel, float maxMotorForce); public abstract bool SetBreakingImpulseThreshold(BulletConstraint constrain, float threshold); public const int HINGE_NOT_SPECIFIED = -1; public abstract bool HingeSetLimits(BulletConstraint constrain, float low, float high, float softness, float bias, float relaxation); public abstract bool SpringEnable(BulletConstraint constrain, int index, float numericTrueFalse); public const int SPRING_NOT_SPECIFIED = -1; public abstract bool SpringSetEquilibriumPoint(BulletConstraint constrain, int index, float equilibriumPoint); public abstract bool SpringSetStiffness(BulletConstraint constrain, int index, float stiffnesss); public abstract bool SpringSetDamping(BulletConstraint constrain, int index, float damping); public const int SLIDER_LOWER_LIMIT = 0; public const int SLIDER_UPPER_LIMIT = 1; public const int SLIDER_LINEAR = 2; public const int SLIDER_ANGULAR = 3; public abstract bool SliderSetLimits(BulletConstraint constrain, int lowerUpper, int linAng, float val); public const int SLIDER_SET_SOFTNESS = 4; public const int SLIDER_SET_RESTITUTION = 5; public const int SLIDER_SET_DAMPING = 6; public const int SLIDER_SET_DIRECTION = 7; public const int SLIDER_SET_LIMIT = 8; public const int SLIDER_SET_ORTHO = 9; public abstract bool SliderSet(BulletConstraint constrain, int softRestDamp, int dirLimOrtho, int linAng, float val); public abstract bool SliderMotorEnable(BulletConstraint constrain, int linAng, float numericTrueFalse); public const int SLIDER_MOTOR_VELOCITY = 10; public const int SLIDER_MAX_MOTOR_FORCE = 11; public abstract bool SliderMotor(BulletConstraint constrain, int forceVel, int linAng, float val); public abstract bool CalculateTransforms(BulletConstraint constrain); public abstract bool SetConstraintParam(BulletConstraint constrain, ConstraintParams paramIndex, float value, ConstraintParamAxis axis); public abstract bool DestroyConstraint(BulletWorld world, BulletConstraint constrain); // ===================================================================================== // btCollisionWorld entries public abstract void UpdateSingleAabb(BulletWorld world, BulletBody obj); public abstract void UpdateAabbs(BulletWorld world); public abstract bool GetForceUpdateAllAabbs(BulletWorld world); public abstract void SetForceUpdateAllAabbs(BulletWorld world, bool force); // ===================================================================================== // btDynamicsWorld entries // public abstract bool AddObjectToWorld(BulletWorld world, BulletBody obj, Vector3 pos, Quaternion rot); public abstract bool AddObjectToWorld(BulletWorld world, BulletBody obj); public abstract bool RemoveObjectFromWorld(BulletWorld world, BulletBody obj); public abstract bool ClearCollisionProxyCache(BulletWorld world, BulletBody obj); public abstract bool AddConstraintToWorld(BulletWorld world, BulletConstraint constrain, bool disableCollisionsBetweenLinkedObjects); public abstract bool RemoveConstraintFromWorld(BulletWorld world, BulletConstraint constrain); // ===================================================================================== // btCollisionObject entries public abstract Vector3 GetAnisotripicFriction(BulletConstraint constrain); public abstract Vector3 SetAnisotripicFriction(BulletConstraint constrain, Vector3 frict); public abstract bool HasAnisotripicFriction(BulletConstraint constrain); public abstract void SetContactProcessingThreshold(BulletBody obj, float val); public abstract float GetContactProcessingThreshold(BulletBody obj); public abstract bool IsStaticObject(BulletBody obj); public abstract bool IsKinematicObject(BulletBody obj); public abstract bool IsStaticOrKinematicObject(BulletBody obj); public abstract bool HasContactResponse(BulletBody obj); public abstract void SetCollisionShape(BulletWorld sim, BulletBody obj, BulletShape shape); public abstract BulletShape GetCollisionShape(BulletBody obj); public abstract int GetActivationState(BulletBody obj); public abstract void SetActivationState(BulletBody obj, int state); public abstract void SetDeactivationTime(BulletBody obj, float dtime); public abstract float GetDeactivationTime(BulletBody obj); public abstract void ForceActivationState(BulletBody obj, ActivationState state); public abstract void Activate(BulletBody obj, bool forceActivation); public abstract bool IsActive(BulletBody obj); public abstract void SetRestitution(BulletBody obj, float val); public abstract float GetRestitution(BulletBody obj); public abstract void SetFriction(BulletBody obj, float val); public abstract float GetFriction(BulletBody obj); public abstract Vector3 GetPosition(BulletBody obj); public abstract Quaternion GetOrientation(BulletBody obj); public abstract void SetTranslation(BulletBody obj, Vector3 position, Quaternion rotation); // public abstract IntPtr GetBroadphaseHandle(BulletBody obj); // public abstract void SetBroadphaseHandle(BulletBody obj, IntPtr handle); public abstract void SetInterpolationLinearVelocity(BulletBody obj, Vector3 vel); public abstract void SetInterpolationAngularVelocity(BulletBody obj, Vector3 vel); public abstract void SetInterpolationVelocity(BulletBody obj, Vector3 linearVel, Vector3 angularVel); public abstract float GetHitFraction(BulletBody obj); public abstract void SetHitFraction(BulletBody obj, float val); public abstract CollisionFlags GetCollisionFlags(BulletBody obj); public abstract CollisionFlags SetCollisionFlags(BulletBody obj, CollisionFlags flags); public abstract CollisionFlags AddToCollisionFlags(BulletBody obj, CollisionFlags flags); public abstract CollisionFlags RemoveFromCollisionFlags(BulletBody obj, CollisionFlags flags); public abstract float GetCcdMotionThreshold(BulletBody obj); public abstract void SetCcdMotionThreshold(BulletBody obj, float val); public abstract float GetCcdSweptSphereRadius(BulletBody obj); public abstract void SetCcdSweptSphereRadius(BulletBody obj, float val); public abstract IntPtr GetUserPointer(BulletBody obj); public abstract void SetUserPointer(BulletBody obj, IntPtr val); // ===================================================================================== // btRigidBody entries public abstract void ApplyGravity(BulletBody obj); public abstract void SetGravity(BulletBody obj, Vector3 val); public abstract Vector3 GetGravity(BulletBody obj); public abstract void SetDamping(BulletBody obj, float lin_damping, float ang_damping); public abstract void SetLinearDamping(BulletBody obj, float lin_damping); public abstract void SetAngularDamping(BulletBody obj, float ang_damping); public abstract float GetLinearDamping(BulletBody obj); public abstract float GetAngularDamping(BulletBody obj); public abstract float GetLinearSleepingThreshold(BulletBody obj); public abstract void ApplyDamping(BulletBody obj, float timeStep); public abstract void SetMassProps(BulletBody obj, float mass, Vector3 inertia); public abstract Vector3 GetLinearFactor(BulletBody obj); public abstract void SetLinearFactor(BulletBody obj, Vector3 factor); public abstract void SetCenterOfMassByPosRot(BulletBody obj, Vector3 pos, Quaternion rot); // Add a force to the object as if its mass is one. public abstract void ApplyCentralForce(BulletBody obj, Vector3 force); // Set the force being applied to the object as if its mass is one. public abstract void SetObjectForce(BulletBody obj, Vector3 force); public abstract Vector3 GetTotalForce(BulletBody obj); public abstract Vector3 GetTotalTorque(BulletBody obj); public abstract Vector3 GetInvInertiaDiagLocal(BulletBody obj); public abstract void SetInvInertiaDiagLocal(BulletBody obj, Vector3 inert); public abstract void SetSleepingThresholds(BulletBody obj, float lin_threshold, float ang_threshold); public abstract void ApplyTorque(BulletBody obj, Vector3 torque); // Apply force at the given point. Will add torque to the object. public abstract void ApplyForce(BulletBody obj, Vector3 force, Vector3 pos); // Apply impulse to the object. Same as "ApplycentralForce" but force scaled by object's mass. public abstract void ApplyCentralImpulse(BulletBody obj, Vector3 imp); // Apply impulse to the object's torque. Force is scaled by object's mass. public abstract void ApplyTorqueImpulse(BulletBody obj, Vector3 imp); // Apply impulse at the point given. For is scaled by object's mass and effects both linear and angular forces. public abstract void ApplyImpulse(BulletBody obj, Vector3 imp, Vector3 pos); public abstract void ClearForces(BulletBody obj); public abstract void ClearAllForces(BulletBody obj); public abstract void UpdateInertiaTensor(BulletBody obj); public abstract Vector3 GetLinearVelocity(BulletBody obj); public abstract Vector3 GetAngularVelocity(BulletBody obj); public abstract void SetLinearVelocity(BulletBody obj, Vector3 val); public abstract void SetAngularVelocity(BulletBody obj, Vector3 angularVelocity); public abstract Vector3 GetVelocityInLocalPoint(BulletBody obj, Vector3 pos); public abstract void Translate(BulletBody obj, Vector3 trans); public abstract void UpdateDeactivation(BulletBody obj, float timeStep); public abstract bool WantsSleeping(BulletBody obj); public abstract void SetAngularFactor(BulletBody obj, float factor); public abstract void SetAngularFactorV(BulletBody obj, Vector3 factor); public abstract Vector3 GetAngularFactor(BulletBody obj); public abstract bool IsInWorld(BulletWorld world, BulletBody obj); public abstract void AddConstraintRef(BulletBody obj, BulletConstraint constrain); public abstract void RemoveConstraintRef(BulletBody obj, BulletConstraint constrain); public abstract BulletConstraint GetConstraintRef(BulletBody obj, int index); public abstract int GetNumConstraintRefs(BulletBody obj); public abstract bool SetCollisionGroupMask(BulletBody body, UInt32 filter, UInt32 mask); // ===================================================================================== // btCollisionShape entries public abstract float GetAngularMotionDisc(BulletShape shape); public abstract float GetContactBreakingThreshold(BulletShape shape, float defaultFactor); public abstract bool IsPolyhedral(BulletShape shape); public abstract bool IsConvex2d(BulletShape shape); public abstract bool IsConvex(BulletShape shape); public abstract bool IsNonMoving(BulletShape shape); public abstract bool IsConcave(BulletShape shape); public abstract bool IsCompound(BulletShape shape); public abstract bool IsSoftBody(BulletShape shape); public abstract bool IsInfinite(BulletShape shape); public abstract void SetLocalScaling(BulletShape shape, Vector3 scale); public abstract Vector3 GetLocalScaling(BulletShape shape); public abstract Vector3 CalculateLocalInertia(BulletShape shape, float mass); public abstract int GetShapeType(BulletShape shape); public abstract void SetMargin(BulletShape shape, float val); public abstract float GetMargin(BulletShape shape); // ===================================================================================== // Debugging public virtual void DumpRigidBody(BulletWorld sim, BulletBody collisionObject) { } public virtual void DumpCollisionShape(BulletWorld sim, BulletShape collisionShape) { } public virtual void DumpConstraint(BulletWorld sim, BulletConstraint constrain) { } public virtual void DumpActivationInfo(BulletWorld sim) { } public virtual void DumpAllInfo(BulletWorld sim) { } public virtual void DumpPhysicsStatistics(BulletWorld sim) { } public virtual void ResetBroadphasePool(BulletWorld sim) { } public virtual void ResetConstraintSolver(BulletWorld sim) { } }; }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using System.Windows.Threading; using Microsoft.PythonTools.Editor; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Intellisense; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudioTools; using Microsoft.VisualStudioTools.Project; namespace Microsoft.PythonTools.Navigation { /// <summary> /// Implements the navigation bar which appears above a source file in the editor. /// /// The navigation bar consists of two drop-down boxes. On the left hand side is a list /// of top level constructs. On the right hand side are list of nested constructs for the /// currently selected top-level construct. /// /// When the user moves the caret the current selections are automatically updated. If the /// user is inside of a top level construct but not inside any of the available nested /// constructs then the first element of the nested construct list is selected and displayed /// grayed out. If the user is inside of no top level constructs then the 1st top-level /// construct is selected and displayed as grayed out. It's first top-level construct is /// also displayed as being grayed out. /// /// The most difficult part of this is handling the transitions from one state to another. /// We need to change the current selections due to events from two sources: The first is selections /// in the drop down and the 2nd is the user navigating within the source code. When a change /// occurs we may need to update the left hand side (along w/ a corresponding update to the right /// hand side) or we may need to update the right hand side. If we are transitioning from /// being outside of a known element to being in a known element we also need to refresh /// the drop down to remove grayed out elements. /// </summary> class DropDownBarClient : IVsDropdownBarClient, IPythonTextBufferInfoEventSink { private readonly Dispatcher _dispatcher; // current dispatcher so we can get back to our thread private readonly PythonEditorServices _services; private ITextView _textView; // text view we're drop downs for private IVsDropdownBar _dropDownBar; // drop down bar - used to refresh when changes occur private NavigationInfo _navigations; private readonly object _navigationsLock = new object(); private readonly IServiceProvider _serviceProvider; private readonly UIThreadBase _uiThread; private IntPtr _imageList; private const int NavigationLevels = 2; private int[] _curSelection = new int[NavigationLevels]; public DropDownBarClient(IServiceProvider serviceProvider, ITextView textView) { Utilities.ArgumentNotNull(nameof(serviceProvider), serviceProvider); Utilities.ArgumentNotNull(nameof(textView), textView); _serviceProvider = serviceProvider; _uiThread = _serviceProvider.GetUIThread(); _services = _serviceProvider.GetComponentModel().GetService<PythonEditorServices>(); _textView = textView; _dispatcher = Dispatcher.CurrentDispatcher; _textView.Caret.PositionChanged += CaretPositionChanged; foreach (var tb in PythonTextBufferInfo.GetAllFromView(textView)) { tb.AddSink(this, this); } textView.BufferGraph.GraphBuffersChanged += BufferGraph_GraphBuffersChanged; for (int i = 0; i < NavigationLevels; i++) { _curSelection[i] = -1; } } private void BufferGraph_GraphBuffersChanged(object sender, VisualStudio.Text.Projection.GraphBuffersChangedEventArgs e) { foreach (var b in e.RemovedBuffers) { PythonTextBufferInfo.TryGetForBuffer(b)?.RemoveSink(typeof(DropDownBarClient)); } foreach (var b in e.AddedBuffers) { _services.GetBufferInfo(b).AddSink(typeof(DropDownBarClient), this); } } internal int Register(IVsDropdownBarManager manager) { IVsDropdownBar dropDownBar; int hr = manager.GetDropdownBar(out dropDownBar); if (ErrorHandler.Succeeded(hr) && dropDownBar != null) { hr = manager.RemoveDropdownBar(); if (!ErrorHandler.Succeeded(hr)) { return hr; } } int res = manager.AddDropdownBar(2, this); if (ErrorHandler.Succeeded(res)) { // A buffer may have multiple DropDownBarClients, given one may // open multiple CodeWindows over a single buffer using // Window/New Window var clients = _textView.Properties.GetOrCreateSingletonProperty( typeof(DropDownBarClient), () => new List<DropDownBarClient>() ); clients.Add(this); } return res; } internal int Unregister(IVsDropdownBarManager manager) { _textView.Caret.PositionChanged -= CaretPositionChanged; // A buffer may have multiple DropDownBarClients, given one may open multiple CodeWindows // over a single buffer using Window/New Window List<DropDownBarClient> clients; if (_textView.Properties.TryGetProperty(typeof(DropDownBarClient), out clients)) { clients.Remove(this); if (clients.Count == 0) { _textView.Properties.RemoveProperty(typeof(DropDownBarClient)); } } foreach (var tb in PythonTextBufferInfo.GetAllFromView(_textView)) { tb.RemoveSink(this); } #if DEBUG IVsDropdownBar existing; IVsDropdownBarClient existingClient; if (ErrorHandler.Succeeded(manager.GetDropdownBar(out existing)) && ErrorHandler.Succeeded(existing.GetClient(out existingClient))) { Debug.Assert(existingClient == this, "Unregistering the wrong dropdown client"); } #endif return manager.RemoveDropdownBar(); } public void UpdateView(IWpfTextView textView) { if (_textView != textView) { _textView.Caret.PositionChanged -= CaretPositionChanged; _textView = textView; _textView.Caret.PositionChanged += CaretPositionChanged; CaretPositionChanged(this, new CaretPositionChangedEventArgs(null, _textView.Caret.Position, _textView.Caret.Position)); } } #region IVsDropdownBarClient Members /// <summary> /// Gets the attributes for the specified combo box. We return the number of elements that we will /// display, the various attributes that VS should query for next (text, image, and attributes of /// the text such as being grayed out), along with the appropriate image list. /// /// We always return the # of entries based off our entries list, the exact same image list, and /// we have VS query for text, image, and text attributes all the time. /// </summary> public int GetComboAttributes(int iCombo, out uint pcEntries, out uint puEntryType, out IntPtr phImageList) { var navigation = GetNavigation(iCombo); if (navigation == null || navigation.Children == null) { pcEntries = 0; } else { pcEntries = (uint)navigation.Children.Length; } puEntryType = (uint)(DROPDOWNENTRYTYPE.ENTRY_TEXT | DROPDOWNENTRYTYPE.ENTRY_IMAGE | DROPDOWNENTRYTYPE.ENTRY_ATTR); phImageList = GetImageList(); return VSConstants.S_OK; } public int GetComboTipText(int iCombo, out string pbstrText) { pbstrText = null; return VSConstants.S_OK; } /// <summary> /// Gets the entry attributes for the given combo box and index. /// /// We always use plain text unless we are not inside of a valid entry /// for the given combo box. In that case we ensure the 1st item /// is selected and we gray out the 1st entry. /// </summary> public int GetEntryAttributes(int iCombo, int iIndex, out uint pAttr) { pAttr = (uint)DROPDOWNFONTATTR.FONTATTR_PLAIN; lock (_navigationsLock) { if (iIndex == 0) { var cur = GetCurrentNavigation(iCombo); if (cur == null) { pAttr = (uint)DROPDOWNFONTATTR.FONTATTR_GRAY; } } } return VSConstants.S_OK; } private NavigationInfo GetNewNavigation(int depth, int index) { var path = new int[depth + 1]; Array.Copy(_curSelection, path, depth + 1); path[depth] = index; return GetNavigationInfo(path); } private NavigationInfo GetCurrentNavigation(int depth) { var path = new int[depth + 1]; Array.Copy(_curSelection, path, depth + 1); return GetNavigationInfo(path); } private NavigationInfo GetNavigation(int depth) { var path = new int[depth]; Array.Copy(_curSelection, path, depth); return GetNavigationInfo(path); } private NavigationInfo GetNavigationInfo(params int[] path) { lock (_navigationsLock) { var cur = _navigations; for (int i = 0; i < path.Length && cur != null; i++) { int p = path[i]; if (p < 0 || p >= cur.Children.Length) { return null; } cur = cur.Children[p]; } return cur; } } /// <summary> /// Gets the image which is associated with the given index for the /// given combo box. /// </summary> public int GetEntryImage(int iCombo, int iIndex, out int piImageIndex) { piImageIndex = 0; var curNav = GetNavigation(iCombo); if (curNav != null && iIndex < curNav.Children.Length) { var child = curNav.Children[iIndex]; ImageListOverlay overlay = ImageListOverlay.ImageListOverlayNone; string name = child.Name; if (name != null && name.StartsWithOrdinal("_") && !(name.StartsWithOrdinal("__") && name.EndsWithOrdinal("__"))) { overlay = ImageListOverlay.ImageListOverlayPrivate; } ImageListKind kind; switch (child.Kind) { case NavigationKind.Class: kind = ImageListKind.Class; break; case NavigationKind.Function: kind = ImageListKind.Method; break; case NavigationKind.ClassMethod: kind = ImageListKind.ClassMethod; break; case NavigationKind.Property: kind = ImageListKind.Property; break; case NavigationKind.StaticMethod: kind = ImageListKind.StaticMethod; break; default: kind = ImageListKind.ThreeDashes; break; } piImageIndex = GetImageListIndex(kind, overlay); } return VSConstants.S_OK; } /// <summary> /// Gets the text which is displayed for the given index for the /// given combo box. /// </summary> public int GetEntryText(int iCombo, int iIndex, out string ppszText) { ppszText = String.Empty; var curNav = GetNavigation(iCombo); if (curNav != null && iIndex < curNav.Children.Length) { var child = curNav.Children[iIndex]; ppszText = child.Name; } return VSConstants.S_OK; } public int OnComboGetFocus(int iCombo) { return VSConstants.S_OK; } /// <summary> /// Called when the user selects an item from the drop down. We will /// update the caret to beat the correct location, move the view port /// so that the code is centered on the screen, and we may refresh /// the combo box so that the 1st item is no longer grayed out if /// the user was originally outside of valid selection. /// </summary> public int OnItemChosen(int iCombo, int iIndex) { if (_dropDownBar == null) { return VSConstants.E_UNEXPECTED; } int oldIndex = _curSelection[iCombo]; var newNavigation = GetNewNavigation(iCombo, iIndex); _curSelection[iCombo] = iIndex; if (newNavigation != null) { if (oldIndex == -1) { _dropDownBar.RefreshCombo(iCombo, iIndex); } CenterAndFocus(newNavigation.Span.Start); } return VSConstants.S_OK; } public int OnItemSelected(int iCombo, int iIndex) { return VSConstants.S_OK; } /// <summary> /// Called by VS to provide us with the drop down bar. We can call back /// on the drop down bar to force VS to refresh the combo box or change /// the current selection. /// </summary> public int SetDropdownBar(IVsDropdownBar pDropdownBar) { _dropDownBar = pDropdownBar; if (_dropDownBar != null) { CaretPositionChanged(this, new CaretPositionChangedEventArgs(null, _textView.Caret.Position, _textView.Caret.Position)); } return VSConstants.S_OK; } #endregion #region Selection Synchronization private void CaretPositionChanged(object sender, CaretPositionChangedEventArgs e) { int newPosition = e.NewPosition.BufferPosition.Position; List<KeyValuePair<int, int>> changes = new List<KeyValuePair<int, int>>(); lock (_navigationsLock) { var cur = _navigations; for (int level = 0; level < _curSelection.Length; level++) { if (cur == null) { // no valid children, we'll invalidate these... changes.Add(new KeyValuePair<int, int>(_curSelection[level], -1)); continue; } bool found = false; if (cur.Children != null) { for (int i = 0; i < cur.Children.Length; i++) { if (newPosition >= cur.Children[i].Span.Start && newPosition <= cur.Children[i].Span.End) { changes.Add(new KeyValuePair<int, int>(_curSelection[level], i)); _curSelection[level] = i; cur = cur.Children[i]; found = true; break; } } } if (!found) { // continue processing to update the subselections... cur = null; changes.Add(new KeyValuePair<int, int>(_curSelection[level], -1)); _curSelection[level] = -1; } } } for (int i = 0; i < changes.Count; i++) { var change = changes[i]; var oldValue = change.Key; var newValue = change.Value; if (_dropDownBar != null && oldValue != newValue) { if (oldValue == -1 || newValue == -1) { // we've selected something new, we need to refresh the combo to // to remove the grayed out entry _dropDownBar.RefreshCombo(i, newValue); } else { // changing from one top-level to another, just update the selection _dropDownBar.SetCurrentSelection(i, newValue); } } } } #endregion #region Entry Calculation /// <summary> /// An enum which is synchronized with our image list for the various /// kinds of images which are available. This can be combined with the /// ImageListOverlay to select an image for the appropriate member type /// and indicate the appropiate visiblity. These can be combined with /// GetImageListIndex to get the final index. /// /// Most of these are unused as we're just using an image list shipped /// by the VS SDK. /// </summary> enum ImageListKind { Class, Unknown1, Unknown2, Enum, Unknown3, Lightning, Unknown4, BlueBox, Key, BlueStripe, ThreeDashes, TwoBoxes, Method, StaticMethod, Unknown6, Namespace, Unknown7, Property, Unknown8, Unknown9, Unknown10, Unknown11, Unknown12, Unknown13, ClassMethod } /// <summary> /// Indicates the overlay kind which should be used for a drop down members /// image. The overlay kind typically indicates visibility. /// /// Most of these are unused as we're just using an image list shipped /// by the VS SDK. /// </summary> enum ImageListOverlay { ImageListOverlayNone, ImageListOverlayLetter, ImageListOverlayBlue, ImageListOverlayKey, ImageListOverlayPrivate, ImageListOverlayArrow, } /// <summary> /// Turns an image list kind / overlay into the proper index in the image list. /// </summary> private static int GetImageListIndex(ImageListKind kind, ImageListOverlay overlay) { return ((int)kind) * 6 + (int)overlay; } /// <summary> /// Reads our image list from our DLLs resource stream. /// </summary> private IntPtr GetImageList() { if (_imageList == IntPtr.Zero) { var shell = _serviceProvider.GetService(typeof(SVsShell)) as IVsShell; if (shell != null) { object obj; var hr = shell.GetProperty((int)__VSSPROPID.VSSPROPID_ObjectMgrTypesImgList, out obj); if (ErrorHandler.Succeeded(hr) && obj != null) { _imageList = (IntPtr)(int)obj; } } } return _imageList; } #endregion #region Implementation Details /// <summary> /// Moves the caret to the specified index in the current snapshot. Then updates the view port /// so that caret will be centered. Finally moves focus to the text view so the user can /// continue typing. /// </summary> private void CenterAndFocus(int index) { _textView.Caret.MoveTo(new SnapshotPoint(_textView.TextBuffer.CurrentSnapshot, index)); _textView.ViewScroller.EnsureSpanVisible( new SnapshotSpan(_textView.TextBuffer.CurrentSnapshot, index, 1), EnsureSpanVisibleOptions.AlwaysCenter ); ((System.Windows.Controls.Control)_textView).Focus(); } /// <summary> /// Wired to parser event for when the parser has completed parsing a new tree and we need /// to update the navigation bar with the new data. /// </summary> async Task IPythonTextBufferInfoEventSink.PythonTextBufferEventAsync(PythonTextBufferInfo sender, PythonTextBufferInfoEventArgs e) { if (e.Event == PythonTextBufferInfoEvents.NewParseTree) { AnalysisEntry analysisEntry = e.AnalysisEntry; await RefreshNavigationsFromAnalysisEntry(analysisEntry); } } internal async Task RefreshNavigationsFromAnalysisEntry(AnalysisEntry analysisEntry) { var dropDownBar = _dropDownBar; if (dropDownBar == null) { return; } var navigations = await _uiThread.InvokeTask(() => analysisEntry.Analyzer.GetNavigationsAsync(_textView.TextSnapshot)); lock (_navigationsLock) { _navigations = navigations; for (int i = 0; i < _curSelection.Length; i++) { _curSelection[i] = -1; } } Action callback = () => CaretPositionChanged( this, new CaretPositionChangedEventArgs( _textView, _textView.Caret.Position, _textView.Caret.Position ) ); try { await _dispatcher.BeginInvoke(callback, DispatcherPriority.Background); } catch (TaskCanceledException) { } } #endregion } }
//! \file ZLibStream.cs //! \date Tue Jul 28 04:34:13 2015 //! \brief RFC 1950 compatible wrapper around .Net DeflateStream class. // // Copyright (C) 2015 by morkt // // 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.IO; using System.IO.Compression; using GameRes.Utility; namespace GameRes.Compression { public enum CompressionMode { Compress, Decompress } /// <summary> /// Enum for backwards compatibility with ZLibNet /// </summary> public enum CompressionLevel { NoCompression = 0, BestSpeed = 1, BestCompression = 9, Default = 6, Level0 = 0, Level1 = 1, Level2 = 2, Level3 = 3, Level4 = 4, Level5 = 5, Level6 = 6, Level7 = 7, Level8 = 8, Level9 = 9 } public class ZLibStream : Stream { DeflateStream m_stream; CheckedStream m_adler; bool m_should_dispose_base; bool m_writing; int m_total_in = 0; public Stream BaseStream { get { return m_stream.BaseStream; } } /// <summary> /// When compressing: returns total number of uncompressed bytes. Undefined for decompression streams. /// </summary> public int TotalIn { get { return m_total_in; } } public ZLibStream (Stream stream, CompressionMode mode, bool leave_open = false) : this (stream, mode, CompressionLevel.Default, leave_open) { } public ZLibStream (Stream stream, CompressionMode mode, CompressionLevel level, bool leave_open = false) { try { if (CompressionMode.Decompress == mode) InitDecompress (stream); else InitCompress (stream, level); m_should_dispose_base = !leave_open; } catch { if (!leave_open) stream.Dispose(); throw; } } private void InitDecompress (Stream stream) { int b1 = stream.ReadByte(); int b2 = stream.ReadByte(); if ((0x78 != b1 && 0x58 != b1) || 0 != (b1 << 8 | b2) % 31) throw new InvalidDataException ("Data not recoginzed as zlib-compressed stream"); m_stream = new DeflateStream (stream, System.IO.Compression.CompressionMode.Decompress, true); m_writing = false; } private void InitCompress (Stream stream, CompressionLevel level) { int flevel = (int)level; System.IO.Compression.CompressionLevel sys_level; if (0 == flevel) { sys_level = System.IO.Compression.CompressionLevel.NoCompression; } else if (flevel > 5) { sys_level = System.IO.Compression.CompressionLevel.Optimal; flevel = 3; } else { sys_level = System.IO.Compression.CompressionLevel.Fastest; flevel = 1; } int cmf = 0x7800 | flevel << 6; cmf = ((cmf + 30) / 31) * 31; stream.WriteByte ((byte)(cmf >> 8)); stream.WriteByte ((byte)cmf); m_stream = new DeflateStream (stream, sys_level, true); m_adler = new CheckedStream (m_stream, new Adler32()); m_writing = true; } void WriteCheckSum (Stream output) { uint checksum = m_adler.CheckSumValue; output.WriteByte ((byte)(checksum >> 24)); output.WriteByte ((byte)(checksum >> 16)); output.WriteByte ((byte)(checksum >> 8)); output.WriteByte ((byte)(checksum)); } #region IO.Stream Members public override bool CanRead { get { return !m_writing; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return m_writing; } } public override long Length { get { return m_stream.Length; } } public override long Position { get { return m_stream.Position; } set { m_stream.Position = value; } } public override int Read (byte[] buffer, int offset, int count) { return m_stream.Read (buffer, offset, count); } public override int ReadByte () { return m_stream.ReadByte(); } public override void Flush() { m_stream.Flush(); } public override long Seek (long offset, SeekOrigin origin) { throw new NotSupportedException ("ZLibStream.Seek method not supported"); } public override void SetLength (long length) { throw new NotSupportedException ("ZLibStream.SetLength method not supported"); } public override void Write (byte[] buffer, int offset, int count) { if (count > 0) { m_adler.Write (buffer, offset, count); m_total_in += count; } } public override void WriteByte (byte value) { m_adler.WriteByte (value); m_total_in++; } #endregion #region IDisposable Members bool m_disposed = false; protected override void Dispose (bool disposing) { if (!m_disposed) { try { if (disposing) { var output = m_stream.BaseStream; m_stream.Dispose(); if (m_writing) { WriteCheckSum (output); m_adler.Dispose(); } if (m_should_dispose_base) output.Dispose(); } m_disposed = true; } finally { base.Dispose (disposing); } } } #endregion } public class ZLibCompressor { public static MemoryStream Compress (Stream source) { var dest = new MemoryStream(); using (var zs = new ZLibStream (dest, CompressionMode.Compress, true)) { source.CopyTo (zs); } dest.Position = 0; return dest; } public static MemoryStream DeCompress (Stream source) { var dest = new MemoryStream(); using (var zs = new ZLibStream (source, CompressionMode.Decompress, true)) { zs.CopyTo (dest); } dest.Position = 0; return dest; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace InvestmentApi.Web.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// 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.ComponentModel; using System.Collections.Generic; using System.Threading; namespace System.Data { internal readonly struct IndexField { public readonly DataColumn Column; public readonly bool IsDescending; // false = Asc; true = Desc what is default value for this? internal IndexField(DataColumn column, bool isDescending) { Debug.Assert(column != null, "null column"); Column = column; IsDescending = isDescending; } public static bool operator ==(IndexField if1, IndexField if2) => if1.Column == if2.Column && if1.IsDescending == if2.IsDescending; public static bool operator !=(IndexField if1, IndexField if2) => !(if1 == if2); // must override Equals if == operator is defined public override bool Equals(object obj) => obj is IndexField ? this == (IndexField)obj : false; // must override GetHashCode if Equals is redefined public override int GetHashCode() => Column.GetHashCode() ^ IsDescending.GetHashCode(); } internal sealed class Index { private sealed class IndexTree : RBTree<int> { private readonly Index _index; internal IndexTree(Index index) : base(TreeAccessMethod.KEY_SEARCH_AND_INDEX) { _index = index; } protected override int CompareNode(int record1, int record2) => _index.CompareRecords(record1, record2); protected override int CompareSateliteTreeNode(int record1, int record2) => _index.CompareDuplicateRecords(record1, record2); } // these constants are used to update a DataRow when the record and Row are known, but don't match private const int DoNotReplaceCompareRecord = 0; private const int ReplaceNewRecordForCompare = 1; private const int ReplaceOldRecordForCompare = 2; private readonly DataTable _table; internal readonly IndexField[] _indexFields; /// <summary>Allow a user implemented comparison of two DataRow</summary> /// <remarks>User must use correct DataRowVersion in comparison or index corruption will happen</remarks> private readonly System.Comparison<DataRow> _comparison; private readonly DataViewRowState _recordStates; private WeakReference _rowFilter; private IndexTree _records; private int _recordCount; private int _refCount; private Listeners<DataViewListener> _listeners; private bool _suspendEvents; private readonly bool _isSharable; private readonly bool _hasRemoteAggregate; internal const int MaskBits = unchecked(0x7FFFFFFF); private static int s_objectTypeCount; // Bid counter private readonly int _objectID = Interlocked.Increment(ref s_objectTypeCount); public Index(DataTable table, IndexField[] indexFields, DataViewRowState recordStates, IFilter rowFilter) : this(table, indexFields, null, recordStates, rowFilter) { } public Index(DataTable table, System.Comparison<DataRow> comparison, DataViewRowState recordStates, IFilter rowFilter) : this(table, GetAllFields(table.Columns), comparison, recordStates, rowFilter) { } // for the delegate methods, we don't know what the dependent columns are - so all columns are dependent private static IndexField[] GetAllFields(DataColumnCollection columns) { IndexField[] fields = new IndexField[columns.Count]; for (int i = 0; i < fields.Length; ++i) { fields[i] = new IndexField(columns[i], false); } return fields; } private Index(DataTable table, IndexField[] indexFields, System.Comparison<DataRow> comparison, DataViewRowState recordStates, IFilter rowFilter) { DataCommonEventSource.Log.Trace("<ds.Index.Index|API> {0}, table={1}, recordStates={2}", ObjectID, (table != null) ? table.ObjectID : 0, recordStates); Debug.Assert(indexFields != null); Debug.Assert(null != table, "null table"); if ((recordStates & (~(DataViewRowState.CurrentRows | DataViewRowState.OriginalRows))) != 0) { throw ExceptionBuilder.RecordStateRange(); } _table = table; _listeners = new Listeners<DataViewListener>(ObjectID, listener => null != listener); _indexFields = indexFields; _recordStates = recordStates; _comparison = comparison; DataColumnCollection columns = table.Columns; _isSharable = (rowFilter == null) && (comparison == null); // a filter or comparison make an index unsharable if (null != rowFilter) { _rowFilter = new WeakReference(rowFilter); DataExpression expr = (rowFilter as DataExpression); if (null != expr) { _hasRemoteAggregate = expr.HasRemoteAggregate(); } } InitRecords(rowFilter); // do not AddRef in ctor, every caller should be responsible to AddRef it // if caller does not AddRef, it is expected to be a one-time read operation because the index won't be maintained on writes } public bool Equal(IndexField[] indexDesc, DataViewRowState recordStates, IFilter rowFilter) { if (!_isSharable || _indexFields.Length != indexDesc.Length || _recordStates != recordStates || null != rowFilter) { return false; } for (int loop = 0; loop < _indexFields.Length; loop++) { if (_indexFields[loop].Column != indexDesc[loop].Column || _indexFields[loop].IsDescending != indexDesc[loop].IsDescending) { return false; } } return true; } internal bool HasRemoteAggregate => _hasRemoteAggregate; internal int ObjectID => _objectID; public DataViewRowState RecordStates => _recordStates; public IFilter RowFilter => (IFilter)((null != _rowFilter) ? _rowFilter.Target : null); public int GetRecord(int recordIndex) { Debug.Assert(recordIndex >= 0 && recordIndex < _recordCount, "recordIndex out of range"); return _records[recordIndex]; } public bool HasDuplicates => _records.HasDuplicates; public int RecordCount => _recordCount; public bool IsSharable => _isSharable; private bool AcceptRecord(int record) => AcceptRecord(record, RowFilter); private bool AcceptRecord(int record, IFilter filter) { DataCommonEventSource.Log.Trace("<ds.Index.AcceptRecord|API> {0}, record={1}", ObjectID, record); if (filter == null) { return true; } DataRow row = _table._recordManager[record]; if (row == null) { return true; } DataRowVersion version = DataRowVersion.Default; if (row._oldRecord == record) { version = DataRowVersion.Original; } else if (row._newRecord == record) { version = DataRowVersion.Current; } else if (row._tempRecord == record) { version = DataRowVersion.Proposed; } return filter.Invoke(row, version); } /// <remarks>Only call from inside a lock(this)</remarks> internal void ListChangedAdd(DataViewListener listener) => _listeners.Add(listener); /// <remarks>Only call from inside a lock(this)</remarks> internal void ListChangedRemove(DataViewListener listener) => _listeners.Remove(listener); public int RefCount => _refCount; public void AddRef() { DataCommonEventSource.Log.Trace("<ds.Index.AddRef|API> {0}", ObjectID); _table._indexesLock.EnterWriteLock(); try { Debug.Assert(0 <= _refCount, "AddRef on disposed index"); Debug.Assert(null != _records, "null records"); if (_refCount == 0) { _table.ShadowIndexCopy(); _table._indexes.Add(this); } _refCount++; } finally { _table._indexesLock.ExitWriteLock(); } } public int RemoveRef() { DataCommonEventSource.Log.Trace("<ds.Index.RemoveRef|API> {0}", ObjectID); int count; _table._indexesLock.EnterWriteLock(); try { count = --_refCount; if (_refCount <= 0) { _table.ShadowIndexCopy(); _table._indexes.Remove(this); } } finally { _table._indexesLock.ExitWriteLock(); } return count; } private void ApplyChangeAction(int record, int action, int changeRecord) { if (action != 0) { if (action > 0) { if (AcceptRecord(record)) { InsertRecord(record, true); } } else if ((null != _comparison) && (-1 != record)) { // when removing a record, the DataRow has already been updated to the newer record // depending on changeRecord, either the new or old record needs be backdated to record // for Comparison<DataRow> to operate correctly DeleteRecord(GetIndex(record, changeRecord)); } else { // unnecessary codepath other than keeping original code path for redbits DeleteRecord(GetIndex(record)); } } } public bool CheckUnique() { #if DEBUG Debug.Assert(_records.CheckUnique(_records.root) != HasDuplicates, "CheckUnique difference"); #endif return !HasDuplicates; } // only used for main tree compare, not satalite tree private int CompareRecords(int record1, int record2) { if (null != _comparison) { return CompareDataRows(record1, record2); } if (0 < _indexFields.Length) { for (int i = 0; i < _indexFields.Length; i++) { int c = _indexFields[i].Column.Compare(record1, record2); if (c != 0) { return (_indexFields[i].IsDescending ? -c : c); } } return 0; } else { Debug.Assert(null != _table._recordManager[record1], "record1 no datarow"); Debug.Assert(null != _table._recordManager[record2], "record2 no datarow"); // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. return _table.Rows.IndexOf(_table._recordManager[record1]).CompareTo(_table.Rows.IndexOf(_table._recordManager[record2])); } } private int CompareDataRows(int record1, int record2) { _table._recordManager.VerifyRecord(record1, _table._recordManager[record1]); _table._recordManager.VerifyRecord(record2, _table._recordManager[record2]); return _comparison(_table._recordManager[record1], _table._recordManager[record2]); } // PS: same as previous CompareRecords, except it compares row state if needed // only used for satalite tree compare private int CompareDuplicateRecords(int record1, int record2) { #if DEBUG if (null != _comparison) { Debug.Assert(0 == CompareDataRows(record1, record2), "duplicate record not a duplicate by user function"); } else if (record1 != record2) { for (int i = 0; i < _indexFields.Length; i++) { int c = _indexFields[i].Column.Compare(record1, record2); Debug.Assert(0 == c, "duplicate record not a duplicate"); } } #endif Debug.Assert(null != _table._recordManager[record1], "record1 no datarow"); Debug.Assert(null != _table._recordManager[record2], "record2 no datarow"); if (null == _table._recordManager[record1]) { return ((null == _table._recordManager[record2]) ? 0 : -1); } else if (null == _table._recordManager[record2]) { return 1; } // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. int diff = _table._recordManager[record1].rowID.CompareTo(_table._recordManager[record2].rowID); // if they're two records in the same row, we need to be able to distinguish them. if ((diff == 0) && (record1 != record2)) { diff = ((int)_table._recordManager[record1].GetRecordState(record1)).CompareTo((int)_table._recordManager[record2].GetRecordState(record2)); } return diff; } private int CompareRecordToKey(int record1, object[] vals) { for (int i = 0; i < _indexFields.Length; i++) { int c = _indexFields[i].Column.CompareValueTo(record1, vals[i]); if (c != 0) { return (_indexFields[i].IsDescending ? -c : c); } } return 0; } // DeleteRecordFromIndex deletes the given record from index and does not fire any Event. IT SHOULD NOT FIRE EVENT public void DeleteRecordFromIndex(int recordIndex) { // this is for expression use, to maintain expression columns's sort , filter etc. do not fire event DeleteRecord(recordIndex, false); } // old and existing DeleteRecord behavior, we can not use this for silently deleting private void DeleteRecord(int recordIndex) { DeleteRecord(recordIndex, true); } private void DeleteRecord(int recordIndex, bool fireEvent) { DataCommonEventSource.Log.Trace("<ds.Index.DeleteRecord|INFO> {0}, recordIndex={1}, fireEvent={2}", ObjectID, recordIndex, fireEvent); if (recordIndex >= 0) { _recordCount--; int record = _records.DeleteByIndex(recordIndex); MaintainDataView(ListChangedType.ItemDeleted, record, !fireEvent); if (fireEvent) { OnListChanged(ListChangedType.ItemDeleted, recordIndex); } } } // this improves performance by allowing DataView to iterating instead of computing for records over index // this will also allow Linq over DataSet to enumerate over the index // avoid boxing by returning RBTreeEnumerator (a struct) instead of IEnumerator<int> public RBTree<int>.RBTreeEnumerator GetEnumerator(int startIndex) => new IndexTree.RBTreeEnumerator(_records, startIndex); // What it actually does is find the index in the records[] that // this record inhabits, and if it doesn't, suggests what index it would // inhabit while setting the high bit. public int GetIndex(int record) => _records.GetIndexByKey(record); /// <summary> /// When searching by value for a specific record, the DataRow may require backdating to reflect the appropriate state /// otherwise on Delete of a DataRow in the Added state, would result in the <see cref="System.Comparison&lt;DataRow&gt;"/> where the row /// reflection record would be in the Detached instead of Added state. /// </summary> private int GetIndex(int record, int changeRecord) { Debug.Assert(null != _comparison, "missing comparison"); int index; DataRow row = _table._recordManager[record]; int a = row._newRecord; int b = row._oldRecord; try { switch (changeRecord) { case ReplaceNewRecordForCompare: row._newRecord = record; break; case ReplaceOldRecordForCompare: row._oldRecord = record; break; } _table._recordManager.VerifyRecord(record, row); index = _records.GetIndexByKey(record); } finally { switch (changeRecord) { case ReplaceNewRecordForCompare: Debug.Assert(record == row._newRecord, "newRecord has change during GetIndex"); row._newRecord = a; break; case ReplaceOldRecordForCompare: Debug.Assert(record == row._oldRecord, "oldRecord has change during GetIndex"); row._oldRecord = b; break; } #if DEBUG if (-1 != a) { _table._recordManager.VerifyRecord(a, row); } #endif } return index; } public object[] GetUniqueKeyValues() { if (_indexFields == null || _indexFields.Length == 0) { return Array.Empty<object>(); } List<object[]> list = new List<object[]>(); GetUniqueKeyValues(list, _records.root); return list.ToArray(); } /// <summary> /// Find index of maintree node that matches key in record /// </summary> public int FindRecord(int record) { int nodeId = _records.Search(record); if (nodeId != IndexTree.NIL) return _records.GetIndexByNode(nodeId); //always returns the First record index else return -1; } public int FindRecordByKey(object key) { int nodeId = FindNodeByKey(key); if (IndexTree.NIL != nodeId) { return _records.GetIndexByNode(nodeId); } return -1; // return -1 to user indicating record not found } public int FindRecordByKey(object[] key) { int nodeId = FindNodeByKeys(key); if (IndexTree.NIL != nodeId) { return _records.GetIndexByNode(nodeId); } return -1; // return -1 to user indicating record not found } private int FindNodeByKey(object originalKey) { int x, c; if (_indexFields.Length != 1) { throw ExceptionBuilder.IndexKeyLength(_indexFields.Length, 1); } x = _records.root; if (IndexTree.NIL != x) { // otherwise storage may not exist DataColumn column = _indexFields[0].Column; object key = column.ConvertValue(originalKey); x = _records.root; if (_indexFields[0].IsDescending) { while (IndexTree.NIL != x) { c = column.CompareValueTo(_records.Key(x), key); if (c == 0) { break; } if (c < 0) { x = _records.Left(x); } // < for decsending else { x = _records.Right(x); } } } else { while (IndexTree.NIL != x) { c = column.CompareValueTo(_records.Key(x), key); if (c == 0) { break; } if (c > 0) { x = _records.Left(x); } // > for ascending else { x = _records.Right(x); } } } } return x; } private int FindNodeByKeys(object[] originalKey) { int x, c; c = ((null != originalKey) ? originalKey.Length : 0); if ((0 == c) || (_indexFields.Length != c)) { throw ExceptionBuilder.IndexKeyLength(_indexFields.Length, c); } x = _records.root; if (IndexTree.NIL != x) { // otherwise storage may not exist // copy array to avoid changing original object[] key = new object[originalKey.Length]; for (int i = 0; i < originalKey.Length; ++i) { key[i] = _indexFields[i].Column.ConvertValue(originalKey[i]); } x = _records.root; while (IndexTree.NIL != x) { c = CompareRecordToKey(_records.Key(x), key); if (c == 0) { break; } if (c > 0) { x = _records.Left(x); } else { x = _records.Right(x); } } } return x; } private int FindNodeByKeyRecord(int record) { int x, c; x = _records.root; if (IndexTree.NIL != x) { // otherwise storage may not exist x = _records.root; while (IndexTree.NIL != x) { c = CompareRecords(_records.Key(x), record); if (c == 0) { break; } if (c > 0) { x = _records.Left(x); } else { x = _records.Right(x); } } } return x; } internal delegate int ComparisonBySelector<TKey,TRow>(TKey key, TRow row) where TRow:DataRow; /// <summary>This method exists for LinqDataView to keep a level of abstraction away from the RBTree</summary> internal Range FindRecords<TKey,TRow>(ComparisonBySelector<TKey,TRow> comparison, TKey key) where TRow:DataRow { int x = _records.root; while (IndexTree.NIL != x) { int c = comparison(key, (TRow)_table._recordManager[_records.Key(x)]); if (c == 0) { break; } if (c < 0) { x = _records.Left(x); } else { x = _records.Right(x); } } return GetRangeFromNode(x); } private Range GetRangeFromNode(int nodeId) { // fill range with the min and max indexes of matching record (i.e min and max of satelite tree) // min index is the index of the node in main tree, and max is the min + size of satelite tree-1 if (IndexTree.NIL == nodeId) { return new Range(); } int recordIndex = _records.GetIndexByNode(nodeId); if (_records.Next(nodeId) == IndexTree.NIL) return new Range(recordIndex, recordIndex); int span = _records.SubTreeSize(_records.Next(nodeId)); return new Range(recordIndex, recordIndex + span - 1); } public Range FindRecords(object key) { int nodeId = FindNodeByKey(key); // main tree node associated with key return GetRangeFromNode(nodeId); } public Range FindRecords(object[] key) { int nodeId = FindNodeByKeys(key); // main tree node associated with key return GetRangeFromNode(nodeId); } internal void FireResetEvent() { DataCommonEventSource.Log.Trace("<ds.Index.FireResetEvent|API> {0}", ObjectID); if (DoListChanged) { OnListChanged(DataView.s_resetEventArgs); } } private int GetChangeAction(DataViewRowState oldState, DataViewRowState newState) { int oldIncluded = ((int)_recordStates & (int)oldState) == 0 ? 0 : 1; int newIncluded = ((int)_recordStates & (int)newState) == 0 ? 0 : 1; return newIncluded - oldIncluded; } /// <summary>Determine if the record that needs backdating is the newRecord or oldRecord or neither</summary> private static int GetReplaceAction(DataViewRowState oldState) { return ((0 != (DataViewRowState.CurrentRows & oldState)) ? ReplaceNewRecordForCompare : // Added/ModifiedCurrent/Unchanged ((0 != (DataViewRowState.OriginalRows & oldState)) ? ReplaceOldRecordForCompare : // Deleted/ModififedOriginal DoNotReplaceCompareRecord)); // None } public DataRow GetRow(int i) => _table._recordManager[GetRecord(i)]; public DataRow[] GetRows(object[] values) => GetRows(FindRecords(values)); public DataRow[] GetRows(Range range) { DataRow[] newRows = _table.NewRowArray(range.Count); if (0 < newRows.Length) { RBTree<int>.RBTreeEnumerator iterator = GetEnumerator(range.Min); for (int i = 0; i < newRows.Length && iterator.MoveNext(); i++) { newRows[i] = _table._recordManager[iterator.Current]; } } return newRows; } private void InitRecords(IFilter filter) { DataViewRowState states = _recordStates; // this improves performance when the is no filter, like with the default view (creating after rows added) // we know the records are in the correct order, just append to end, duplicates not possible bool append = (0 == _indexFields.Length); _records = new IndexTree(this); _recordCount = 0; // this improves performance by iterating of the index instead of computing record by index foreach (DataRow b in _table.Rows) { int record = -1; if (b._oldRecord == b._newRecord) { if ((states & DataViewRowState.Unchanged) != 0) { record = b._oldRecord; } } else if (b._oldRecord == -1) { if ((states & DataViewRowState.Added) != 0) { record = b._newRecord; } } else if (b._newRecord == -1) { if ((states & DataViewRowState.Deleted) != 0) { record = b._oldRecord; } } else { if ((states & DataViewRowState.ModifiedCurrent) != 0) { record = b._newRecord; } else if ((states & DataViewRowState.ModifiedOriginal) != 0) { record = b._oldRecord; } } if (record != -1 && AcceptRecord(record, filter)) { _records.InsertAt(-1, record, append); _recordCount++; } } } // InsertRecordToIndex inserts the given record to index and does not fire any Event. IT SHOULD NOT FIRE EVENT // I added this since I can not use existing InsertRecord which is not silent operation // it returns the position that record is inserted public int InsertRecordToIndex(int record) { int pos = -1; if (AcceptRecord(record)) { pos = InsertRecord(record, false); } return pos; } // existing functionality, it calls the overlaod with fireEvent== true, so it still fires the event private int InsertRecord(int record, bool fireEvent) { DataCommonEventSource.Log.Trace("<ds.Index.InsertRecord|INFO> {0}, record={1}, fireEvent={2}", ObjectID, record, fireEvent); // this improves performance when the is no filter, like with the default view (creating before rows added) // we know can append when the new record is the last row in table, normal insertion pattern bool append = false; if ((0 == _indexFields.Length) && (null != _table)) { DataRow row = _table._recordManager[record]; append = (_table.Rows.IndexOf(row) + 1 == _table.Rows.Count); } int nodeId = _records.InsertAt(-1, record, append); _recordCount++; MaintainDataView(ListChangedType.ItemAdded, record, !fireEvent); if (fireEvent) { if (DoListChanged) { OnListChanged(ListChangedType.ItemAdded, _records.GetIndexByNode(nodeId)); } return 0; } else { return _records.GetIndexByNode(nodeId); } } // Search for specified key public bool IsKeyInIndex(object key) { int x_id = FindNodeByKey(key); return (IndexTree.NIL != x_id); } public bool IsKeyInIndex(object[] key) { int x_id = FindNodeByKeys(key); return (IndexTree.NIL != x_id); } public bool IsKeyRecordInIndex(int record) { int x_id = FindNodeByKeyRecord(record); return (IndexTree.NIL != x_id); } private bool DoListChanged => (!_suspendEvents && _listeners.HasListeners && !_table.AreIndexEventsSuspended); private void OnListChanged(ListChangedType changedType, int newIndex, int oldIndex) { if (DoListChanged) { OnListChanged(new ListChangedEventArgs(changedType, newIndex, oldIndex)); } } private void OnListChanged(ListChangedType changedType, int index) { if (DoListChanged) { OnListChanged(new ListChangedEventArgs(changedType, index)); } } private void OnListChanged(ListChangedEventArgs e) { DataCommonEventSource.Log.Trace("<ds.Index.OnListChanged|INFO> {0}", ObjectID); Debug.Assert(DoListChanged, "supposed to check DoListChanged before calling to delay create ListChangedEventArgs"); _listeners.Notify(e, false, false, delegate (DataViewListener listener, ListChangedEventArgs args, bool arg2, bool arg3) { listener.IndexListChanged(args); }); } private void MaintainDataView(ListChangedType changedType, int record, bool trackAddRemove) { Debug.Assert(-1 <= record, "bad record#"); _listeners.Notify(changedType, ((0 <= record) ? _table._recordManager[record] : null), trackAddRemove, delegate (DataViewListener listener, ListChangedType type, DataRow row, bool track) { listener.MaintainDataView(changedType, row, track); }); } public void Reset() { DataCommonEventSource.Log.Trace("<ds.Index.Reset|API> {0}", ObjectID); InitRecords(RowFilter); MaintainDataView(ListChangedType.Reset, -1, false); FireResetEvent(); } public void RecordChanged(int record) { DataCommonEventSource.Log.Trace("<ds.Index.RecordChanged|API> {0}, record={1}", ObjectID, record); if (DoListChanged) { int index = GetIndex(record); if (index >= 0) { OnListChanged(ListChangedType.ItemChanged, index); } } } // new RecordChanged which takes oldIndex and newIndex and fires _onListChanged public void RecordChanged(int oldIndex, int newIndex) { DataCommonEventSource.Log.Trace("<ds.Index.RecordChanged|API> {0}, oldIndex={1}, newIndex={2}", ObjectID, oldIndex, newIndex); if (oldIndex > -1 || newIndex > -1) { // no need to fire if it was not and will not be in index: this check means at least one version should be in index if (oldIndex == newIndex) { OnListChanged(ListChangedType.ItemChanged, newIndex, oldIndex); } else if (oldIndex == -1) { // it is added OnListChanged(ListChangedType.ItemAdded, newIndex, oldIndex); } else if (newIndex == -1) { OnListChanged(ListChangedType.ItemDeleted, oldIndex); } else { OnListChanged(ListChangedType.ItemMoved, newIndex, oldIndex); } } } public void RecordStateChanged(int record, DataViewRowState oldState, DataViewRowState newState) { DataCommonEventSource.Log.Trace("<ds.Index.RecordStateChanged|API> {0}, record={1}, oldState={2}, newState={3}", ObjectID, record, oldState, newState); int action = GetChangeAction(oldState, newState); ApplyChangeAction(record, action, GetReplaceAction(oldState)); } public void RecordStateChanged(int oldRecord, DataViewRowState oldOldState, DataViewRowState oldNewState, int newRecord, DataViewRowState newOldState, DataViewRowState newNewState) { DataCommonEventSource.Log.Trace("<ds.Index.RecordStateChanged|API> {0}, oldRecord={1}, oldOldState={2}, oldNewState={3}, newRecord={4}, newOldState={5}, newNewState={6}", ObjectID, oldRecord, oldOldState, oldNewState, newRecord, newOldState, newNewState); Debug.Assert((-1 == oldRecord) || (-1 == newRecord) || _table._recordManager[oldRecord] == _table._recordManager[newRecord], "not the same DataRow when updating oldRecord and newRecord"); int oldAction = GetChangeAction(oldOldState, oldNewState); int newAction = GetChangeAction(newOldState, newNewState); if (oldAction == -1 && newAction == 1 && AcceptRecord(newRecord)) { int oldRecordIndex; if ((null != _comparison) && oldAction < 0) { // when oldRecord is being removed, allow GetIndexByKey updating the DataRow for Comparison<DataRow> oldRecordIndex = GetIndex(oldRecord, GetReplaceAction(oldOldState)); } else { oldRecordIndex = GetIndex(oldRecord); } if ((null == _comparison) && oldRecordIndex != -1 && CompareRecords(oldRecord, newRecord) == 0) { _records.UpdateNodeKey(oldRecord, newRecord); //change in place, as Both records have same key value int commonIndexLocation = GetIndex(newRecord); OnListChanged(ListChangedType.ItemChanged, commonIndexLocation, commonIndexLocation); } else { _suspendEvents = true; if (oldRecordIndex != -1) { _records.DeleteByIndex(oldRecordIndex); // DeleteByIndex doesn't require searching by key _recordCount--; } _records.Insert(newRecord); _recordCount++; _suspendEvents = false; int newRecordIndex = GetIndex(newRecord); if (oldRecordIndex == newRecordIndex) { // if the position is the same OnListChanged(ListChangedType.ItemChanged, newRecordIndex, oldRecordIndex); // be carefull remove oldrecord index if needed } else { if (oldRecordIndex == -1) { MaintainDataView(ListChangedType.ItemAdded, newRecord, false); OnListChanged(ListChangedType.ItemAdded, GetIndex(newRecord)); // oldLocation would be -1 } else { OnListChanged(ListChangedType.ItemMoved, newRecordIndex, oldRecordIndex); } } } } else { ApplyChangeAction(oldRecord, oldAction, GetReplaceAction(oldOldState)); ApplyChangeAction(newRecord, newAction, GetReplaceAction(newOldState)); } } internal DataTable Table => _table; private void GetUniqueKeyValues(List<object[]> list, int curNodeId) { if (curNodeId != IndexTree.NIL) { GetUniqueKeyValues(list, _records.Left(curNodeId)); int record = _records.Key(curNodeId); object[] element = new object[_indexFields.Length]; // number of columns in PK for (int j = 0; j < element.Length; ++j) { element[j] = _indexFields[j].Column[record]; } list.Add(element); GetUniqueKeyValues(list, _records.Right(curNodeId)); } } internal static int IndexOfReference<T>(List<T> list, T item) where T : class { if (null != list) { for (int i = 0; i < list.Count; ++i) { if (ReferenceEquals(list[i], item)) { return i; } } } return -1; } internal static bool ContainsReference<T>(List<T> list, T item) where T : class { return (0 <= IndexOfReference(list, item)); } } internal sealed class Listeners<TElem> where TElem : class { private readonly List<TElem> _listeners; private readonly Func<TElem, bool> _filter; private readonly int _objectID; private int _listenerReaderCount; /// <summary>Wish this was defined in mscorlib.dll instead of System.Core.dll</summary> internal delegate void Action<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4); /// <summary>Wish this was defined in mscorlib.dll instead of System.Core.dll</summary> internal delegate TResult Func<T1, TResult>(T1 arg1); internal Listeners(int ObjectID, Func<TElem, bool> notifyFilter) { _listeners = new List<TElem>(); _filter = notifyFilter; _objectID = ObjectID; _listenerReaderCount = 0; } internal bool HasListeners => (0 < _listeners.Count); /// <remarks>Only call from inside a lock</remarks> internal void Add(TElem listener) { Debug.Assert(null != listener, "null listener"); Debug.Assert(!Index.ContainsReference(_listeners, listener), "already contains reference"); _listeners.Add(listener); } internal int IndexOfReference(TElem listener) { return Index.IndexOfReference(_listeners, listener); } /// <remarks>Only call from inside a lock</remarks> internal void Remove(TElem listener) { Debug.Assert(null != listener, "null listener"); int index = IndexOfReference(listener); Debug.Assert(0 <= index, "listeners don't contain listener"); _listeners[index] = null; if (0 == _listenerReaderCount) { _listeners.RemoveAt(index); _listeners.TrimExcess(); } } /// <summary> /// Write operation which means user must control multi-thread and we can assume single thread /// </summary> internal void Notify<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3, Action<TElem, T1, T2, T3> action) { Debug.Assert(null != action, "no action"); Debug.Assert(0 <= _listenerReaderCount, "negative _listEventCount"); int count = _listeners.Count; if (0 < count) { int nullIndex = -1; // protect against listeners shrinking via Remove _listenerReaderCount++; try { // protect against listeners growing via Add since new listeners will already have the Notify in progress for (int i = 0; i < count; ++i) { // protect against listener being set to null (instead of being removed) TElem listener = _listeners[i]; if (_filter(listener)) { // perform the action on each listener // some actions may throw an exception blocking remaning listeners from being notified (just like events) action(listener, arg1, arg2, arg3); } else { _listeners[i] = null; nullIndex = i; } } } finally { _listenerReaderCount--; } if (0 == _listenerReaderCount) { RemoveNullListeners(nullIndex); } } } private void RemoveNullListeners(int nullIndex) { Debug.Assert((-1 == nullIndex) || (null == _listeners[nullIndex]), "non-null listener"); Debug.Assert(0 == _listenerReaderCount, "0 < _listenerReaderCount"); for (int i = nullIndex; 0 <= i; --i) { if (null == _listeners[i]) { _listeners.RemoveAt(i); } } } } }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * http://www.gnu.org/copyleft/gpl.html */ using System; using NUnit.Framework; using MindTouch.Dream; using MindTouch.Xml; namespace MindTouch.Deki.Tests.SiteTests { [TestFixture] public class BanTests { const string banRevokemask = "9223372036854779902"; [Test] public void GetBans() { // GET:site/bans // ... Plug p = Utils.BuildPlugForAdmin(); DreamMessage msg = p.At("site", "bans").Get(); Assert.AreEqual(DreamStatus.Ok, msg.Status); } [Test] public void CreatingPagesByBanned() { //Assumptions: // //Actions: // Create user1 as contributor // Ban user1 // Try to create page from user1 //Expected result: // Forbidden Plug p = Utils.BuildPlugForAdmin(); string userId = null; string userName = null; DreamMessage msg = UserUtils.CreateRandomContributor(p, out userId, out userName); XDoc ban = new XDoc("bans") .Elem("description", Utils.GetSmallRandomText()) .Elem("date.expires", DateTime.Now.AddDays(10)) .Start("permissions.revoked") .Elem("operations", banRevokemask) .End() .Start("ban.users") .Start("user").Attr("id", userId).End() .End(); msg = p.At("site", "bans").Post(ban); Assert.AreEqual(DreamStatus.Ok, msg.Status); p = Utils.BuildPlugForUser(userName, UserUtils.DefaultUserPsw); string pageTitle = "=" + XUri.DoubleEncode(PageUtils.GenerateUniquePageName()); string content = Utils.GetSmallRandomText(); msg = p.At("pages", pageTitle, "contents").With("edittime", Utils.DateToString(DateTime.MinValue)). PostAsync(DreamMessage.Ok(MimeType.TEXT_UTF8, content)).Wait(); Assert.AreEqual(DreamStatus.Forbidden, msg.Status); } [Test] public void PostBanByIP() { // POST:site/bans // ... Plug p = Utils.BuildPlugForAdmin(); XDoc ban = new XDoc("bans") .Elem("description", Utils.GetSmallRandomText()) .Elem("date.expires", DateTime.Now.AddDays(10)) .Start("permissions.revoked") .Elem("operations", banRevokemask) .End() .Start("ban.addresses") .Elem("address", "192.168.0.1") .End(); DreamMessage msg = p.At("site", "bans").Post(ban); Assert.AreEqual(DreamStatus.Ok, msg.Status); string banid = msg.ToDocument()["@id"].AsText; Assert.IsTrue(!string.IsNullOrEmpty(banid)); msg = p.At("site", "bans").Get(); Assert.AreEqual(DreamStatus.Ok, msg.Status); Assert.IsFalse(msg.ToDocument()[string.Format("ban[@id=\"{0}\"]", banid)].IsEmpty); msg = p.At("site", "bans", banid).Get(); Assert.AreEqual(DreamStatus.Ok, msg.Status); Assert.AreEqual(banid, msg.ToDocument()["@id"].AsText); } [Test] public void PostBanByUserID() { // POST:site/bans // ... Plug p = Utils.BuildPlugForAdmin(); string userid = null; DreamMessage msg = UserUtils.CreateRandomContributor(p, out userid); XDoc ban = new XDoc("bans") .Elem("description", Utils.GetSmallRandomText()) .Elem("date.expires", DateTime.Now.AddDays(10)) .Start("permissions.revoked") .Elem("operations", banRevokemask) .End() .Start("ban.users") .Start("user").Attr("id", userid).End() .End(); msg = p.At("site", "bans").Post(ban); Assert.AreEqual(DreamStatus.Ok, msg.Status); string banid = msg.ToDocument()["@id"].AsText; Assert.IsTrue(!string.IsNullOrEmpty(banid)); msg = p.At("site", "bans").Get(); Assert.AreEqual(DreamStatus.Ok, msg.Status); Assert.IsFalse(msg.ToDocument()[string.Format("ban[@id=\"{0}\"]", banid)].IsEmpty); msg = p.At("site", "bans", banid).Get(); Assert.AreEqual(DreamStatus.Ok, msg.Status); Assert.AreEqual(banid, msg.ToDocument()["@id"].AsText); } [Test] public void DeleteBan() { // DELETE:site/bans // ... Plug p = Utils.BuildPlugForAdmin(); XDoc ban = new XDoc("bans") .Elem("description", Utils.GetSmallRandomText()) .Elem("date.expires", DateTime.Now.AddDays(10)) .Start("permissions.revoked") .Elem("operations", banRevokemask) .End() .Start("ban.addresses") .Elem("address", "192.168.0.1") .End(); DreamMessage msg = p.At("site", "bans").Post(ban); Assert.AreEqual(DreamStatus.Ok, msg.Status); string banid = msg.ToDocument()["@id"].AsText; Assert.IsTrue(!string.IsNullOrEmpty(banid)); msg = p.At("site", "bans", banid).Delete(); Assert.AreEqual(DreamStatus.Ok, msg.Status); msg = p.At("site", "bans").Get(); Assert.AreEqual(DreamStatus.Ok, msg.Status); Assert.IsTrue(msg.ToDocument()[string.Format("ban[@id=\"{0}\"]", banid)].IsEmpty); msg = p.At("site", "bans", banid).GetAsync().Wait(); Assert.AreEqual(DreamStatus.NotFound, msg.Status); } [Test] public void CreatingPageByUnbanned() { //Assumptions: // //Actions: // Create user as contributor // Ban user // Unban user // Try to create page from user //Expected result: // Ok Plug p = Utils.BuildPlugForAdmin(); string userId = null; string userName = null; DreamMessage msg = UserUtils.CreateRandomContributor(p, out userId, out userName); XDoc ban = new XDoc("bans") .Elem("description", Utils.GetSmallRandomText()) .Elem("date.expires", DateTime.Now.AddDays(10)) .Start("permissions.revoked") .Elem("operations", banRevokemask) .End() .Start("ban.users") .Start("user").Attr("id", userId).End() .End(); msg = p.At("site", "bans").Post(ban); Assert.AreEqual(DreamStatus.Ok, msg.Status); string banid = msg.ToDocument()["@id"].AsText; Assert.IsTrue(!string.IsNullOrEmpty(banid)); msg = p.At("site", "bans", banid).Delete(); Assert.AreEqual(DreamStatus.Ok, msg.Status); p = Utils.BuildPlugForUser(userName, UserUtils.DefaultUserPsw); string pageTitle = "=" + XUri.DoubleEncode(PageUtils.GenerateUniquePageName()); string content = Utils.GetSmallRandomText(); msg = p.At("pages", pageTitle, "contents").With("edittime", Utils.DateToString(DateTime.MinValue)). PostAsync(DreamMessage.Ok(MimeType.TEXT_UTF8, content)).Wait(); Assert.AreEqual(DreamStatus.Ok, msg.Status); string pageId = msg.ToDocument()["page/@id"].AsText; p = Utils.BuildPlugForAdmin(); PageUtils.DeletePageByID(p, pageId, true); } [Test] public void AddFileFromBanned() { //Assumptions: // //Actions: // Create page // Create user as contributor // Ban user // Try to upload file to page from banned user //Expected result: // Forbidden Plug p = Utils.BuildPlugForAdmin(); string pageId = null; DreamMessage msg = PageUtils.CreateRandomPage(p, out pageId); string userId = null; string userName = null; msg = UserUtils.CreateRandomContributor(p, out userId, out userName); XDoc ban = new XDoc("bans") .Elem("description", Utils.GetSmallRandomText()) .Elem("date.expires", DateTime.Now.AddDays(10)) .Start("permissions.revoked") .Elem("operations", banRevokemask) .End() .Start("ban.users") .Start("user").Attr("id", userId).End() .End(); msg = p.At("site", "bans").Post(ban); Assert.AreEqual(DreamStatus.Ok, msg.Status); p = Utils.BuildPlugForUser(userName, UserUtils.DefaultUserPsw); try { string fileid = null; string filename = null; msg = FileUtils.UploadRandomFile(p, pageId, out fileid, out filename); Assert.IsTrue(false); } catch (DreamResponseException ex) { Assert.AreEqual(DreamStatus.Forbidden, ex.Response.Status); } p = Utils.BuildPlugForAdmin(); PageUtils.DeletePageByID(p, pageId, true); } [Test] public void AddFileFromUnbanned() { //Assumptions: // //Actions: // Create page // Create user as contributor // Ban user // Unban user // Try to upload file to page from banned user //Expected result: // Ok Plug p = Utils.BuildPlugForAdmin(); string pageId = null; DreamMessage msg = PageUtils.CreateRandomPage(p, out pageId); string userId = null; string userName = null; msg = UserUtils.CreateRandomContributor(p, out userId, out userName); XDoc ban = new XDoc("bans") .Elem("description", Utils.GetSmallRandomText()) .Elem("date.expires", DateTime.Now.AddDays(10)) .Start("permissions.revoked") .Elem("operations", banRevokemask) .End() .Start("ban.users") .Start("user").Attr("id", userId).End() .End(); msg = p.At("site", "bans").Post(ban); Assert.AreEqual(DreamStatus.Ok, msg.Status); string banid = msg.ToDocument()["@id"].AsText; Assert.IsTrue(!string.IsNullOrEmpty(banid)); msg = p.At("site", "bans", banid).Delete(); Assert.AreEqual(DreamStatus.Ok, msg.Status); p = Utils.BuildPlugForUser(userName, UserUtils.DefaultUserPsw); string fileid = null; string filename = null; msg = FileUtils.UploadRandomFile(p, pageId, out fileid, out filename); Assert.AreEqual(DreamStatus.Ok, msg.Status); p = Utils.BuildPlugForAdmin(); PageUtils.DeletePageByID(p, pageId, true); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsAzureSpecials { using Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ApiVersionLocalOperations operations. /// </summary> internal partial class ApiVersionLocalOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, IApiVersionLocalOperations { /// <summary> /// Initializes a new instance of the ApiVersionLocalOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ApiVersionLocalOperations(AutoRestAzureSpecialParametersTestClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutoRestAzureSpecialParametersTestClient /// </summary> public AutoRestAzureSpecialParametersTestClient Client { get; private set; } /// <summary> /// Get method with api-version modeled in the method. pass in api-version = /// '2.0' to succeed /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> GetMethodLocalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { string apiVersion = "2.0"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetMethodLocalValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/method/string/none/query/local/2.0").ToString(); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get method with api-version modeled in the method. pass in api-version = /// null to succeed /// </summary> /// <param name='apiVersion'> /// This should appear as a method parameter, use value null, this should /// result in no serialized parameter /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> GetMethodLocalNullWithHttpMessagesAsync(string apiVersion = default(string), 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("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetMethodLocalNull", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/method/string/none/query/local/null").ToString(); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get method with api-version modeled in the method. pass in api-version = /// '2.0' to succeed /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> GetPathLocalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { string apiVersion = "2.0"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetPathLocalValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/path/string/none/query/local/2.0").ToString(); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get method with api-version modeled in the method. pass in api-version = /// '2.0' to succeed /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> GetSwaggerLocalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { string apiVersion = "2.0"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetSwaggerLocalValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/swagger/string/none/query/local/2.0").ToString(); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Drawing; using System.Linq; using System.Text.RegularExpressions; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using Color = DocumentFormat.OpenXml.Spreadsheet.Color; using Font = DocumentFormat.OpenXml.Spreadsheet.Font; namespace Higgs.OpenXml { public static class SpreadsheetHelper { public static DoubleValue ColumnMaxWidth = 100; public static Stylesheet AddDefaultStyleSheet(this Workbook book) { var styleSheet = new Stylesheet( new NumberingFormats( new NumberingFormat { NumberFormatId = 0, FormatCode = "0" }, new NumberingFormat { NumberFormatId = 1, FormatCode = "dd mmm yyyy" }, new NumberingFormat { NumberFormatId = 2, FormatCode = "dd mmm yyyy hh:mm:ss" }, new NumberingFormat { NumberFormatId = 3, FormatCode = "#,##0" }, new NumberingFormat { NumberFormatId = 4, FormatCode = "#,##0.00" }, new NumberingFormat { NumberFormatId = 5, FormatCode = "mmm yyyy" } ), new Fonts( new Font( // Index 0 - The default font. new FontSize { Val = 11 }, new Color { Rgb = new HexBinaryValue { Value = "000000" } }, new FontName { Val = "Calibri" }), new Font( // Index 1 - The bold font. new Bold(), new FontSize { Val = 11 }, new Color { Rgb = new HexBinaryValue { Value = "000000" } }, new FontName { Val = "Calibri" }), new Font( // Index 2 - The Italic font. new Italic(), new FontSize { Val = 11 }, new Color { Rgb = new HexBinaryValue { Value = "000000" } }, new FontName { Val = "Calibri" }), new Font( // Index 3 - The Underline font. new Underline(), new FontSize { Val = 11 }, new Color { Rgb = new HexBinaryValue { Value = "000000" } }, new FontName { Val = "Calibri" }), new Font( // Index 4 - The Underline+Bold font. new Bold(), new Underline(), new FontSize { Val = 11 }, new Color { Rgb = new HexBinaryValue { Value = "000000" } }, new FontName { Val = "Calibri" }) ), new Fills( new Fill(new PatternFill { PatternType = PatternValues.None }) // Index 0 - The default fill. ), new Borders( new Border( // Index 0 - The default border. new LeftBorder(), new RightBorder(), new TopBorder(), new BottomBorder(), new DiagonalBorder()), new Border( // Index 1 - Applies a Left, Right, Top, Bottom border to a cell new LeftBorder(new Color { Auto = true }) { Style = BorderStyleValues.Thin }, new RightBorder(new Color { Auto = true }) { Style = BorderStyleValues.Thin }, new TopBorder(new Color { Auto = true }) { Style = BorderStyleValues.Thin }, new BottomBorder(new Color { Auto = true }) { Style = BorderStyleValues.Thin }, new DiagonalBorder()) ), new CellFormats( new CellFormat { FontId = 0, FillId = 0, BorderId = 0, Alignment = new Alignment { Vertical = VerticalAlignmentValues.Center } }, // Index 0 - The default cell style. If a cell does not have a style index applied it will use this style combination instead new CellFormat { FontId = 1, FillId = 0, BorderId = 0, ApplyFont = true }, // Index 1 - Bold new CellFormat { FontId = 2, FillId = 0, BorderId = 0, ApplyFont = true }, // Index 2 - Italic new CellFormat { FontId = 3, FillId = 0, BorderId = 0, ApplyFont = true }, // Index 3 - Underline new CellFormat { FontId = 4, FillId = 0, BorderId = 0, ApplyFont = true }, // Index 4 - Bold+Underline new CellFormat( // Index 5 - Alignment Center new Alignment { Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center } ) { FontId = 0, FillId = 0, BorderId = 0, ApplyAlignment = true }, new CellFormat( // Index 6 - Alignment Left new Alignment { Horizontal = HorizontalAlignmentValues.Left, Vertical = VerticalAlignmentValues.Center } ) { FontId = 0, FillId = 0, BorderId = 0, ApplyAlignment = true }, new CellFormat( // Index 7 - Alignment Right new Alignment { Horizontal = HorizontalAlignmentValues.Right, Vertical = VerticalAlignmentValues.Center } ) { FontId = 0, FillId = 0, BorderId = 0, ApplyAlignment = true }, new CellFormat { FontId = 0, FillId = 0, BorderId = 1, ApplyBorder = true, Alignment = new Alignment { Vertical = VerticalAlignmentValues.Center } }, // Index 8 - Border new CellFormat( // Index 9 - Bold+Alignment Center new Alignment { Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center } ) { FontId = 1, FillId = 0, BorderId = 0, ApplyAlignment = true }, new CellFormat( // Index 10 - Bold+Alignment Left new Alignment { Horizontal = HorizontalAlignmentValues.Left, Vertical = VerticalAlignmentValues.Center } ) { FontId = 1, FillId = 0, BorderId = 0, ApplyAlignment = true }, new CellFormat( // Index 11 - Bold+Alignment Right new Alignment { Horizontal = HorizontalAlignmentValues.Right, Vertical = VerticalAlignmentValues.Center } ) { FontId = 1, FillId = 0, BorderId = 0, ApplyAlignment = true }, new CellFormat( // Index 12 - Underline+Alignment Center new Alignment { Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center } ) { FontId = 3, FillId = 0, BorderId = 0, ApplyAlignment = true }, new CellFormat( // Index 13 - Bold+Underline+Alignment Center new Alignment { Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center } ) { FontId = 4, FillId = 0, BorderId = 0, ApplyAlignment = true }, new CellFormat( // Index 14 - Bold+Underline+Alignment Center+Border new Alignment { Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center } ) { FontId = 1, FillId = 0, BorderId = 1, ApplyAlignment = true }, new CellFormat(new Alignment { Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center } // Index 15 - Border + Date ) { FontId = 0, FillId = 0, BorderId = 1, ApplyAlignment = true, NumberFormatId = 1 }, new CellFormat( // Index 16 - Border + Integer new Alignment { Horizontal = HorizontalAlignmentValues.Right, Vertical = VerticalAlignmentValues.Center } ) { FontId = 0, FillId = 0, BorderId = 1, ApplyAlignment = true, NumberFormatId = 3}, new CellFormat( // Index 17 - Border + Money new Alignment { Horizontal = HorizontalAlignmentValues.Right, Vertical = VerticalAlignmentValues.Center } ) { FontId = 0, FillId = 0, BorderId = 1, ApplyAlignment = true, NumberFormatId = 4 }, new CellFormat ( new Alignment { Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center } ){ FontId = 0, FillId = 0, BorderId = 1, ApplyAlignment = true, NumberFormatId = 5 }, // Index 18 - Border + Month, new CellFormat( new Alignment { Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center } ) { FontId = 0, FillId = 0, BorderId = 1, ApplyAlignment = true, NumberFormatId = 1 }, // Index 19 - Border + Date new CellFormat( new Alignment { Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center } ) { FontId = 0, FillId = 0, BorderId = 1, ApplyAlignment = true, NumberFormatId = 2 }, // Index 20 - Border + DateTime new CellFormat { FontId = 4, FillId = 0, BorderId = 0, ApplyFont = true, NumberFormatId = 3 }, // Index 21 - Bold+Underline+Integer new CellFormat { FontId = 4, FillId = 0, BorderId = 0, ApplyFont = true, NumberFormatId = 4 }, // Index 22 - Bold+Underline+Money new CellFormat { FontId = 0, FillId = 0, BorderId = 1, Alignment = new Alignment { Vertical = VerticalAlignmentValues.Top, WrapText = true } } // Index 23 - Long Text ) ); var stylesPart = book.WorkbookPart.AddNewPart<WorkbookStylesPart>(); stylesPart.Stylesheet = styleSheet; stylesPart.Stylesheet.Save(); return styleSheet; } public static OpenXmlPackage SetPackageProperties(this OpenXmlPackage document, string authorName) { document.PackageProperties.Creator = authorName; document.PackageProperties.Created = DateTime.Now; document.PackageProperties.Modified = DateTime.Now; document.PackageProperties.LastModifiedBy = authorName; return document; } public static Row AddRow(this Worksheet sheet, bool isAppend = true) { var sd = sheet.OfType<SheetData>().First(); var row = new Row { RowIndex = Convert.ToUInt32(sd.ChildElements.Count()) + 1 }; if (isAppend) sheet.AppendRow(row); return row; } public static Worksheet AppendRow(this Worksheet sheet, Row row) { var sd = sheet.OfType<SheetData>().First(); sd.AppendChild(row); return sheet; } public static MergeCell MergeCell(this Worksheet sheet, Cell startCell, Cell endCell) { return sheet.MergeCell(startCell.CellReference.Value, endCell.CellReference.Value); } public static MergeCell MergeCell(this Worksheet sheet, string startCell, string endCell) { MergeCells mergeCells; if (sheet.Elements<MergeCells>().Any()) mergeCells = sheet.Elements<MergeCells>().First(); else { mergeCells = new MergeCells(); // Insert a MergeCells object into the specified position. if (sheet.Elements<CustomSheetView>().Any()) sheet.InsertAfter(mergeCells, sheet.Elements<CustomSheetView>().First()); else sheet.InsertAfter(mergeCells, sheet.Elements<SheetData>().First()); } // Create the merged cell and append it to the MergeCells collection. var mergeCell = new MergeCell { Reference = new StringValue(startCell + ":" + endCell) }; mergeCells.AppendChild(mergeCell); return mergeCell; } public static MergeCell MergeCell(this Worksheet sheet, int rowIndex, int startColumnIndex, int endColumnIndex) { var startCell = GetColumnName(startColumnIndex) + rowIndex; var endCell = GetColumnName(endColumnIndex) + rowIndex; return sheet.MergeCell(startCell, endCell); } public static MergeCell MergeCell(this Worksheet sheet, Row row, int startColumnIndex, int endColumnIndex) { var startCell = GetColumnName(startColumnIndex) + row.RowIndex; var endCell = GetColumnName(endColumnIndex) + row.RowIndex; return sheet.MergeCell(startCell, endCell); } public static bool IsMergedCell(this Worksheet sheet, string cellRef) { var mergeCells = sheet.Elements<MergeCells>().FirstOrDefault(); if (mergeCells == null) return false; return mergeCells.OfType<MergeCell>().Any(x => IsInRange(x.Reference.Value, cellRef)); } private static Cell AddCell(this Worksheet sheet, Row row, UInt32? styleIndex = null, bool isAppend = true) { var cell = new Cell(); if (styleIndex.HasValue) cell.StyleIndex = styleIndex.Value; // Get the last cell's column var nextCol = "A"; var c = (Cell)row.LastChild; if (c != null) // if there are some cells already there... { var numIndex = c.CellReference.ToString().IndexOfAny(new[] { '1', '2', '3', '4', '5', '6', '7', '8', '9' }); // Get the last column reference var lastCol = c.CellReference.ToString().Substring(0, numIndex); nextCol = GetNextColumnRef(lastCol); } while (sheet.IsMergedCell(nextCol + row.RowIndex)) { nextCol = GetNextColumnRef(nextCol); } cell.CellReference = nextCol + row.RowIndex; if (isAppend) { row.AppendCell(cell); } return cell; } public static Cell AddCell(this Worksheet sheet, Row row, DefaultCellFormats cellFormat, bool isAppend = true) { return sheet.AddCell(row, (UInt32) cellFormat, isAppend); } public static Cell GetCell(this Worksheet sheet, string cellAddress) { return sheet.Descendants<Cell>().SingleOrDefault(c => cellAddress.Equals(c.CellReference)); } public static CellFormat GetCellFormat(this Workbook book, uint styleIndex) { var workbookStylePart = book.WorkbookPart.WorkbookStylesPart; var cellFormats = workbookStylePart.Stylesheet.Elements<CellFormats>().First(); return cellFormats.Elements<CellFormat>().ElementAt((int)styleIndex); } public static Font GetFontFormat(this Workbook book, uint styleIndex) { var workbookStylePart = book.WorkbookPart.WorkbookStylesPart; var fonts = workbookStylePart.Stylesheet.Elements<Fonts>().First(); return fonts.Elements<Font>().ElementAt((int)styleIndex); } public static Fill GetFillFormat(this Workbook book, uint styleIndex) { var workbookStylePart = book.WorkbookPart.WorkbookStylesPart; var fills = workbookStylePart.Stylesheet.Elements<Fills>().First(); return fills.Elements<Fill>().ElementAt((int)styleIndex); } public static Border GetBorderFormat(this Workbook book, uint styleIndex) { var workbookStylePart = book.WorkbookPart.WorkbookStylesPart; var borders = workbookStylePart.Stylesheet.Elements<Borders>().First(); return borders.Elements<Border>().ElementAt((int)styleIndex); } public static bool IsInMergedCell(MergeCells mergeCell, string cellRef) { var mergeCells = mergeCell.OfType<MergeCell>(); return mergeCells.Any(merge => IsInRange(merge.Reference.Value, cellRef)); } public static bool IsInRange(string range, string cellRef) { var cellColName = GetColumnName(cellRef); var cellColIndex = GetColumnIndex(cellColName); var cellRowIndex = int.Parse(cellRef.Substring(cellColName.Length)); var split = range.Split(':'); var startColName = GetColumnName(split[0]); var startColIndex = GetColumnIndex(startColName); var startRowIndex = int.Parse(split[0].Substring(startColName.Length)); var endColName = GetColumnName(split[1]); var endColIndex = GetColumnIndex(endColName); var endRowIndex = int.Parse(split[1].Substring(endColName.Length)); return cellColIndex >= startColIndex && cellRowIndex >= startRowIndex && cellColIndex <= endColIndex && cellRowIndex <= endRowIndex; } public static Row AppendCell(this Row row, Cell cell) { row.AppendChild(cell); return row; } public static Cell SetValue<T>(this Cell cell, object data) { return cell.SetValue(data, typeof(T)); } public static bool IsNumericType(this Type type) { switch (Type.GetTypeCode(type)) { case TypeCode.Byte: case TypeCode.SByte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Decimal: case TypeCode.Double: case TypeCode.Single: return true; default: return false; } } public static Cell SetValue(this Cell cell, object data, Type dataType) { if (dataType.IsGenericType && dataType.GetGenericTypeDefinition() == typeof(Nullable<>)) { dataType = Nullable.GetUnderlyingType(dataType); } if (dataType == typeof(string) || dataType.IsEnum) { if (data != null) { cell.SetValueInlineString(data.ToString()); } } else if (dataType.IsNumericType()) { cell.DataType = CellValues.Number; var v = new CellValue { Text = data != null ? data.ToString() : "0" }; cell.AppendChild(v); } else if (dataType == typeof(DateTime)) { cell.DataType = CellValues.Number; if (data != null) { var dt = (DateTime)data; var v = new CellValue { Text = dt.ToOADate().ToString() }; cell.AppendChild(v); } } else if (dataType == typeof(Boolean)) { cell.DataType = CellValues.Boolean; if (data != null) { var v = new CellValue { Text = data.ToString() }; cell.AppendChild(v); } } return cell; } public static Cell SetValueInlineString(this Cell cell, string value) { cell.DataType = CellValues.InlineString; var inlineString = new InlineString(); inlineString.AppendChild(new Text { Text = value }); cell.AppendChild(inlineString); return cell; } public static Column AutoFitColumn(this Workbook book, Worksheet sheet, uint columnIndex) { var columns = sheet.Elements<Columns>().First(); var column = columns.Elements<Column>().FirstOrDefault(x => x.Min == columnIndex && x.Max == columnIndex); if (column == null) { column = new Column { Min = columnIndex, Max = columnIndex, CustomWidth = true }; columns.AppendChild(column); } var sheetData = sheet.OfType<SheetData>().First(); var columnName = GetColumnName((int)columnIndex); var cells = sheetData.Descendants<Cell>().Where(x => x.CellReference.Value.StartsWith(columnName)).Take(100); var maxWidth = 0.0; foreach (var c in cells) { var width = book.GetCellWidth(c); if (width > maxWidth) maxWidth = width; } if (maxWidth > 0) { column.Width = maxWidth <= ColumnMaxWidth ? (DoubleValue)maxWidth : ColumnMaxWidth; } return column; } public static Column AutoFitColumn(this Workbook book, Worksheet sheet, uint columnIndex, Cell cell) { var columns = sheet.Elements<Columns>().First(); var column = columns.Elements<Column>().FirstOrDefault(x => x.Min == columnIndex && x.Max == columnIndex); if (column == null) { column = new Column { Min = columnIndex, Max = columnIndex, CustomWidth = true }; columns.AppendChild(column); } column.Width = book.GetCellWidth(cell); return column; } #region Utils public static string GetColumnName(int columnIndex) { var dividend = columnIndex; var columnName = String.Empty; while (dividend > 0) { var modifier = (dividend - 1) % 26; columnName = Convert.ToChar(65 + modifier) + columnName; dividend = ((dividend - modifier) / 26); } return columnName; } public static string GetColumnName(string cellName) { // Create a regular expression to match the column name portion of the cell name. var regex = new Regex("[A-Za-z]+"); var match = regex.Match(cellName); return match.Value; } public static string GetColumnName(Cell cell) { return GetColumnName(cell.CellReference); } public static int GetColumnIndex(string columnName) { var characters = columnName.ToUpperInvariant().ToCharArray(); var sum = 0; for (var i = 0; i < characters.Length; i++) { sum *= 26; sum += (characters[i] - 'A' + 1); } sum++; return sum; } public static SharedStringItem GetSharedStringItemById(this Workbook spreadSheet, int id) { return spreadSheet.WorkbookPart.SharedStringTablePart.SharedStringTable .Elements<SharedStringItem>().ElementAt(id); } public static double GetCellWidth(this Workbook spreadSheet, Cell cell) { string cellValue = null; if (cell.DataType != null) { if (cell.DataType == CellValues.SharedString) { int id; if (Int32.TryParse(cell.InnerText, out id)) { var item = spreadSheet.GetSharedStringItemById(id); if (item.Text != null) { cellValue = item.Text.Text; } else if (item.InnerText != null) { cellValue = item.InnerText; } else if (item.InnerXml != null) { cellValue = item.InnerXml; } } } else if (cell.DataType == CellValues.InlineString) { var inlineString = cell.Elements<InlineString>().Single(); cellValue = inlineString.Text.Text; } else if (cell.DataType == CellValues.Number) { var otherValue = cell.Elements<CellValue>().SingleOrDefault(); if (otherValue != null) { // TODO: Use number format to get real display number. cellValue = double.Parse(otherValue.Text).ToString("N"); } } else { var otherValue = cell.Elements<CellValue>().SingleOrDefault(); if (otherValue != null) { cellValue = otherValue.Text; } } } if (string.IsNullOrEmpty(cellValue)) return 0; var cellFormat = spreadSheet.GetCellFormat(cell.StyleIndex ?? 0); var font = spreadSheet.GetFontFormat(cellFormat.FontId); var fontStyle = font.Bold != null ? FontStyle.Bold : FontStyle.Regular; var stringFont = new System.Drawing.Font(font.FontName.Val.Value, (float)font.FontSize.Val.Value, fontStyle); return cellValue.Split(new []{'\n','\r'}, StringSplitOptions.RemoveEmptyEntries).Max(x => GetWidth(stringFont, x.Trim())); } public static double GetWidth(string font, int fontSize, string text) { var stringFont = new System.Drawing.Font(font, fontSize); return GetWidth(stringFont, text); } public static double GetWidth(System.Drawing.Font stringFont, string text) { // This formula is based on this article plus a nudge ( + 0.2M ) // http://msdn.microsoft.com/en-us/library/documentformat.openxml.spreadsheet.column.width.aspx // Truncate(((256 * Solve_For_This + Truncate(128 / 7)) / 256) * 7) = DeterminePixelsOfString using (var g = Graphics.FromImage(new Bitmap(500, 100))) { g.PageUnit = GraphicsUnit.Pixel; var textSize = g.MeasureString(text, stringFont); var width = (((textSize.Width / (double)7) * 256) - (128 / 7)) / 256; width = (double)decimal.Round((decimal)width, 2); if (width > 0.5) width += 2D; return width; } } // Increment the column reference in an Excel fashion, i.e. A, B, C...Z, AA, AB etc. // Partly stolen from somewhere on the Net and modified for my use. public static string GetNextColumnRef(string cellRef) { var sum = GetColumnIndex(cellRef); var columnName = String.Empty; while (sum > 0) { var modulo = (sum - 1) % 26; columnName = Convert.ToChar(65 + modulo) + columnName; sum = (sum - modulo) / 26; } return columnName; } #endregion } }
using System.Text.Encodings.Web; using System.Text.Json; using GitVersion.Helpers; using YamlDotNet.Serialization; using static GitVersion.Extensions.ObjectExtensions; namespace GitVersion.OutputVariables; public class VersionVariables : IEnumerable<KeyValuePair<string, string>> { public VersionVariables(string major, string minor, string patch, string? buildMetaData, string? buildMetaDataPadded, string? fullBuildMetaData, string? branchName, string? escapedBranchName, string? sha, string? shortSha, string majorMinorPatch, string semVer, string legacySemVer, string legacySemVerPadded, string fullSemVer, string? assemblySemVer, string? assemblySemFileVer, string? preReleaseTag, string? preReleaseTagWithDash, string? preReleaseLabel, string? preReleaseLabelWithDash, string? preReleaseNumber, string weightedPreReleaseNumber, string? informationalVersion, string? commitDate, string nugetVersion, string nugetVersionV2, string? nugetPreReleaseTag, string? nugetPreReleaseTagV2, string? versionSourceSha, string? commitsSinceVersionSource, string? commitsSinceVersionSourcePadded, string? uncommittedChanges) { Major = major; Minor = minor; Patch = patch; BuildMetaData = buildMetaData; BuildMetaDataPadded = buildMetaDataPadded; FullBuildMetaData = fullBuildMetaData; BranchName = branchName; EscapedBranchName = escapedBranchName; Sha = sha; ShortSha = shortSha; MajorMinorPatch = majorMinorPatch; SemVer = semVer; LegacySemVer = legacySemVer; LegacySemVerPadded = legacySemVerPadded; FullSemVer = fullSemVer; AssemblySemVer = assemblySemVer; AssemblySemFileVer = assemblySemFileVer; PreReleaseTag = preReleaseTag; PreReleaseTagWithDash = preReleaseTagWithDash; PreReleaseLabel = preReleaseLabel; PreReleaseLabelWithDash = preReleaseLabelWithDash; PreReleaseNumber = preReleaseNumber; WeightedPreReleaseNumber = weightedPreReleaseNumber; InformationalVersion = informationalVersion; CommitDate = commitDate; NuGetVersion = nugetVersion; NuGetVersionV2 = nugetVersionV2; NuGetPreReleaseTag = nugetPreReleaseTag; NuGetPreReleaseTagV2 = nugetPreReleaseTagV2; VersionSourceSha = versionSourceSha; CommitsSinceVersionSource = commitsSinceVersionSource; CommitsSinceVersionSourcePadded = commitsSinceVersionSourcePadded; UncommittedChanges = uncommittedChanges; } public string Major { get; } public string Minor { get; } public string Patch { get; } public string? PreReleaseTag { get; } public string? PreReleaseTagWithDash { get; } public string? PreReleaseLabel { get; } public string? PreReleaseLabelWithDash { get; } public string? PreReleaseNumber { get; } public string WeightedPreReleaseNumber { get; } public string? BuildMetaData { get; } public string? BuildMetaDataPadded { get; } public string? FullBuildMetaData { get; } public string MajorMinorPatch { get; } public string SemVer { get; } public string LegacySemVer { get; } public string LegacySemVerPadded { get; } public string? AssemblySemVer { get; } public string? AssemblySemFileVer { get; } public string FullSemVer { get; } public string? InformationalVersion { get; } public string? BranchName { get; } public string? EscapedBranchName { get; } public string? Sha { get; } public string? ShortSha { get; } public string NuGetVersionV2 { get; } public string NuGetVersion { get; } public string? NuGetPreReleaseTagV2 { get; } public string? NuGetPreReleaseTag { get; } public string? VersionSourceSha { get; } public string? CommitsSinceVersionSource { get; } public string? CommitsSinceVersionSourcePadded { get; } public string? UncommittedChanges { get; } public string? CommitDate { get; set; } [ReflectionIgnore] public static IEnumerable<string> AvailableVariables => typeof(VersionVariables) .GetProperties() .Where(p => !p.GetCustomAttributes(typeof(ReflectionIgnoreAttribute), false).Any()) .Select(p => p.Name) .OrderBy(a => a, StringComparer.Ordinal); [ReflectionIgnore] public string? FileName { get; set; } [ReflectionIgnore] public string? this[string variable] => typeof(VersionVariables).GetProperty(variable)?.GetValue(this, null) as string; public IEnumerator<KeyValuePair<string, string>> GetEnumerator() => this.GetProperties().GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); // FIX ME: Shall we return an instance with no ctorArgs or explicitly fail when properties is null? private static VersionVariables FromDictionary(IEnumerable<KeyValuePair<string, string>>? properties) { var type = typeof(VersionVariables); var constructors = type.GetConstructors(); var ctor = constructors.Single(); var ctorArgs = ctor.GetParameters() .Select(p => properties?.Single(v => string.Equals(v.Key, p.Name, StringComparison.InvariantCultureIgnoreCase)).Value) .Cast<object>() .ToArray(); return (VersionVariables)Activator.CreateInstance(type, ctorArgs); } public static VersionVariables FromJson(string json) { var serializeOptions = JsonSerializerOptions(); var variablePairs = JsonSerializer.Deserialize<Dictionary<string, string>>(json, serializeOptions); return FromDictionary(variablePairs); } public static VersionVariables FromFile(string filePath, IFileSystem fileSystem) { try { var retryAction = new RetryAction<IOException, VersionVariables>(); return retryAction.Execute(() => FromFileInternal(filePath, fileSystem)); } catch (AggregateException ex) { var lastException = ex.InnerExceptions.LastOrDefault() ?? ex.InnerException; if (lastException != null) { throw lastException; } throw; } } private static VersionVariables FromFileInternal(string filePath, IFileSystem fileSystem) { using var stream = fileSystem.OpenRead(filePath); using var reader = new StreamReader(stream); var dictionary = new Deserializer().Deserialize<Dictionary<string, string>>(reader); var versionVariables = FromDictionary(dictionary); versionVariables.FileName = filePath; return versionVariables; } public bool TryGetValue(string variable, out string? variableValue) { if (ContainsKey(variable)) { variableValue = this[variable]; return true; } variableValue = null; return false; } private static bool ContainsKey(string variable) => typeof(VersionVariables).GetProperty(variable) != null; public override string ToString() { var variablesType = typeof(VersionVariablesJsonModel); var variables = new VersionVariablesJsonModel(); foreach (var (key, value) in this.GetProperties()) { variablesType.GetProperty(key)?.SetValue(variables, value); } var serializeOptions = JsonSerializerOptions(); return JsonSerializer.Serialize(variables, serializeOptions); } private static JsonSerializerOptions JsonSerializerOptions() { var serializeOptions = new JsonSerializerOptions { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, Converters = { new VersionVariablesJsonStringConverter() } }; return serializeOptions; } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; namespace BLToolkit.EditableObjects { [Serializable] [DebuggerDisplay("Count = {Count}")] public class EditableList<T> : EditableArrayList, IList<T> { #region Constructors public EditableList() : base(typeof(T)) { } public EditableList(int capacity) : base(typeof(T), capacity) { } public EditableList(ICollection c) : base(typeof(T), c) { } public EditableList(bool trackChanges) : base(typeof(T), trackChanges) { } public EditableList(int capacity, bool trackChanges) : base(typeof(T), capacity, trackChanges) { } public EditableList(ICollection c, bool trackChanges) : base(typeof(T), c, trackChanges) { } public EditableList(EditableList<T> list) : base(list, true) { } public EditableList(EditableList<T> list, bool trackChanges) : base(list, trackChanges) { } #endregion #region Typed Methods public override object Clone() { return Clone(new EditableList<T>((ArrayList)List.Clone())); } public new T this[int index] { get { return (T)base[index]; } set { base[index] = value; } } public new T[] ToArray() { return (T[])base.ToArray(typeof(T)); } public new T AddNew() { return (T)base.AddNew(); } public int RemoveAll(Predicate<T> match) { int n = 0; for (int i = 0; i < Count; i++) { T item = this[i]; if (match(item)) { Remove((object)item); i--; n++; } } return n; } #endregion #region Like List<T> Methods public T Find(Predicate<T> match) { if (match == null) throw new ArgumentNullException("match"); foreach (T t in List) if (match(t)) return t; return default(T); } public EditableList<T> FindAll(Predicate<T> match) { if (match == null) throw new ArgumentNullException("match"); EditableList<T> list = new EditableList<T>(); foreach (T t in List) if (match(t)) list.Add(t); return list; } public int FindIndex(Predicate<T> match) { return FindIndex(0, List.Count, match); } public int FindIndex(int startIndex, Predicate<T> match) { return FindIndex(startIndex, List.Count - startIndex, match); } public int FindIndex(int startIndex, int count, Predicate<T> match) { if (startIndex > List.Count) throw new ArgumentOutOfRangeException("startIndex"); if (count < 0 || startIndex > List.Count - count) throw new ArgumentOutOfRangeException("count"); if (match == null) throw new ArgumentNullException("match"); for (int i = startIndex; i < startIndex + count; i++) if (match((T)List[i])) return i; return -1; } public T FindLast(Predicate<T> match) { if (match == null) throw new ArgumentNullException("match"); for (int i = List.Count - 1; i >= 0; i--) { T t = (T)List[i]; if (match(t)) return t; } return default(T); } public int FindLastIndex(Predicate<T> match) { return FindLastIndex(List.Count - 1, List.Count, match); } public int FindLastIndex(int startIndex, Predicate<T> match) { return FindLastIndex(startIndex, startIndex + 1, match); } public int FindLastIndex(int startIndex, int count, Predicate<T> match) { if (startIndex >= List.Count) throw new ArgumentOutOfRangeException("startIndex"); if (count < 0 || startIndex - count + 1 < 0) throw new ArgumentOutOfRangeException("count"); if (match == null) throw new ArgumentNullException("match"); for (int i = startIndex; i > startIndex - count; i--) { T t = (T)List[i]; if (match(t)) return i; } return -1; } public void ForEach(Action<T> action) { if (action == null) throw new ArgumentNullException("action"); foreach (T t in List) action(t); } public void Sort(IComparer<T> comparer) { Sort(0, List.Count, comparer); } public void Sort(int index, int count, IComparer<T> comparer) { if (List.Count > 1 && count > 1) { T[] items = new T[count]; List.CopyTo(index, items, 0, count); Array.Sort<T>(items, index, count, comparer); for (int i = 0; i < count; i++) List[i + index] = items[i]; OnListChanged(ListChangedType.Reset, 0); } } public void Sort(Comparison<T> comparison) { if (List.Count > 1) { T[] items = new T[List.Count]; List.CopyTo(items); Array.Sort<T>(items, comparison); for (int i = 0; i < List.Count; i++) List[i] = items[i]; OnListChanged(ListChangedType.Reset, 0); } } #endregion #region Static Methods internal EditableList(ArrayList list) : base(typeof(T), list) { } public static EditableList<T> Adapter(List<T> list) { return new EditableList<T>(ArrayList.Adapter(list)); } public static new EditableList<T> Adapter(IList list) { return list is ArrayList? new EditableList<T>((ArrayList)list): new EditableList<T>(ArrayList.Adapter(list)); } #endregion #region IList<T> Members public int IndexOf(T item) { return IndexOf((object)item); } public void Insert(int index, T item) { Insert(index, (object)item); } #endregion #region ICollection<T> Members public void Add(T item) { Add((object)item); } public bool Contains(T item) { return Contains((object)item); } public void CopyTo(T[] array, int arrayIndex) { CopyTo((Array)array, arrayIndex); } public bool Remove(T item) { if (Contains(item) == false) return false; Remove((object)item); return true; } #endregion #region IEnumerable<T> Members public new IEnumerator<T> GetEnumerator() { return new Enumerator(List.GetEnumerator()); } class Enumerator : IEnumerator<T> { public Enumerator(IEnumerator enumerator) { _enumerator = enumerator; } private readonly IEnumerator _enumerator; #region IEnumerator<T> Members T IEnumerator<T>.Current { get { return (T)_enumerator.Current; } } #endregion #region IEnumerator Members object IEnumerator.Current { get { return _enumerator.Current; } } bool IEnumerator.MoveNext() { return _enumerator.MoveNext(); } void IEnumerator.Reset() { _enumerator.Reset(); } #endregion #region IDisposable Members void IDisposable.Dispose() { } #endregion } #endregion } }
/** * Copyright (c) 2015, GruntTheDivine All rights reserved. * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT ,STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. **/ using System; using System.IO; using System.Text; using Iodine.Compiler; namespace Iodine.Runtime { public class IodineString : IodineObject { public static readonly IodineTypeDefinition TypeDefinition = new StringTypeDef (); public static readonly IodineString Empty = new IodineString (string.Empty); sealed class StringTypeDef : IodineTypeDefinition { public StringTypeDef () : base ("Str") { BindAttributes (this); SetDocumentation ( "An immutable string of UTF-16 characters" ); } public override IodineObject Invoke (VirtualMachine vm, IodineObject[] arguments) { if (arguments.Length <= 0) { vm.RaiseException (new IodineArgumentException (1)); } return new IodineString (arguments [0].ToString ()); } public override IodineObject BindAttributes (IodineObject obj) { IodineIterableMixin.ApplyMixin (obj); obj.SetAttribute ("lower", new BuiltinMethodCallback (Lower, obj)); obj.SetAttribute ("upper", new BuiltinMethodCallback (Upper, obj)); obj.SetAttribute ("substr", new BuiltinMethodCallback (Substring, obj)); obj.SetAttribute ("index", new BuiltinMethodCallback (IndexOf, obj)); obj.SetAttribute ("rindex", new BuiltinMethodCallback (RightIndex, obj)); obj.SetAttribute ("find", new BuiltinMethodCallback (Find, obj)); obj.SetAttribute ("rfind", new BuiltinMethodCallback (RightFind, obj)); obj.SetAttribute ("contains", new BuiltinMethodCallback (Contains, obj)); obj.SetAttribute ("replace", new BuiltinMethodCallback (Replace, obj)); obj.SetAttribute ("startswith", new BuiltinMethodCallback (StartsWith, obj)); obj.SetAttribute ("endswith", new BuiltinMethodCallback (EndsWith, obj)); obj.SetAttribute ("split", new BuiltinMethodCallback (Split, obj)); obj.SetAttribute ("join", new BuiltinMethodCallback (Join, obj)); obj.SetAttribute ("trim", new BuiltinMethodCallback (Trim, obj)); obj.SetAttribute ("format", new BuiltinMethodCallback (Format, obj)); obj.SetAttribute ("isalpha", new BuiltinMethodCallback (IsLetter, obj)); obj.SetAttribute ("isdigit", new BuiltinMethodCallback (IsDigit, obj)); obj.SetAttribute ("isalnum", new BuiltinMethodCallback (IsLetterOrDigit, obj)); obj.SetAttribute ("iswhitespace", new BuiltinMethodCallback (IsWhiteSpace, obj)); obj.SetAttribute ("issymbol", new BuiltinMethodCallback (IsSymbol, obj)); obj.SetAttribute ("ljust", new BuiltinMethodCallback (PadRight, obj)); obj.SetAttribute ("rjust", new BuiltinMethodCallback (PadLeft, obj)); base.BindAttributes (obj); return obj; } [BuiltinDocString ( "Returns the uppercase representation of this string" )] private IodineObject Upper (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } return new IodineString (thisObj.Value.ToUpper ()); } [BuiltinDocString ( "Returns the lowercase representation of this string" )] private IodineObject Lower (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } return new IodineString (thisObj.Value.ToLower ()); } [BuiltinDocString ( "Returns a substring contained within this string.", "@param start The starting index.", "@optional end The ending index (Default is the length of the string)", "@returns The substring between start and end" )] private IodineObject Substring (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } if (args.Length < 1) { vm.RaiseException (new IodineArgumentException (1)); return null; } int start = 0; int len = 0; var startObj = args [0] as IodineInteger; if (startObj == null) { vm.RaiseException (new IodineTypeException ("Int")); return null; } start = (int)startObj.Value; if (args.Length == 1) { len = thisObj.Value.Length; } else { var endObj = args [1] as IodineInteger; if (endObj == null) { vm.RaiseException (new IodineTypeException ("Int")); return null; } len = (int)endObj.Value; } if (start < thisObj.Value.Length && len <= thisObj.Value.Length) { return new IodineString (thisObj.Value.Substring (start, len - start)); } vm.RaiseException (new IodineIndexException ()); return null; } [BuiltinDocString ( "Returns the index of the first occurance of a string within this string. Raises KeyNotFound exception " + "if the specified substring does not exist.", "@param substring The string to find." )] private IodineObject IndexOf (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } if (args.Length < 1) { vm.RaiseException (new IodineArgumentException (1)); return null; } var ch = args [0] as IodineString; if (ch == null) { vm.RaiseException (new IodineTypeException ("Str")); return null; } var val = ch.ToString (); if (!thisObj.Value.Contains (val)) { vm.RaiseException (new IodineKeyNotFound ()); return null; } return new IodineInteger (thisObj.Value.IndexOf (val)); } [BuiltinDocString ( "Returns the index of the last occurance of a string within this string. Raises KeyNotFound exception " + "if the specified substring does not exist.", "@param substring The string to find." )] private IodineObject RightIndex (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } if (args.Length < 1) { vm.RaiseException (new IodineArgumentException (1)); return null; } var ch = args [0] as IodineString; if (ch == null) { vm.RaiseException (new IodineTypeException ("Str")); return null; } var val = ch.ToString (); if (!thisObj.Value.Contains (val)) { vm.RaiseException (new IodineKeyNotFound ()); return null; } return new IodineInteger (thisObj.Value.LastIndexOf (val)); } [BuiltinDocString ( "Returns the index of the first occurance of a string within this string. Returns -1 " + "if the specified substring does not exist.", "@param substring The string to find." )] private IodineObject Find (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } if (args.Length < 1) { vm.RaiseException (new IodineArgumentException (1)); return null; } var ch = args [0] as IodineString; if (ch == null) { vm.RaiseException (new IodineTypeException ("Str")); return null; } var val = ch.ToString (); if (!thisObj.Value.Contains (val)) { return new IodineInteger (-1); } return new IodineInteger (thisObj.Value.IndexOf (val)); } [BuiltinDocString ( "Returns the index of the last occurance of a string within this string. Returns -1 " + "if the specified substring does not exist.", "@param substring The string to find." )] private IodineObject RightFind (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } if (args.Length < 1) { vm.RaiseException (new IodineArgumentException (1)); return null; } var ch = args [0] as IodineString; if (ch == null) { vm.RaiseException (new IodineTypeException ("Str")); return null; } var val = ch.ToString (); if (!thisObj.Value.Contains (val)) { return new IodineInteger (-1); } return new IodineInteger (thisObj.Value.LastIndexOf (val)); } [BuiltinDocString ( "Returns true if the string contains the specified value. ", "@param value The value that this string must contain to return true." )] private IodineObject Contains (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } if (args.Length < 1) { vm.RaiseException (new IodineArgumentException (1)); return null; } return IodineBool.Create (thisObj.Value.Contains (args [0].ToString ())); } [BuiltinDocString ( "Returns true if the string starts with the specified value.", "@param value The value that this string must start with to return true." )] private IodineObject StartsWith (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } if (args.Length < 1) { vm.RaiseException (new IodineArgumentException (1)); return null; } return IodineBool.Create (thisObj.Value.StartsWith (args [0].ToString ())); } [BuiltinDocString ( "Returns true if the string ends with the specified value.", "@param value The value that this string must end with to return true." )] private IodineObject EndsWith (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } if (args.Length < 1) { vm.RaiseException (new IodineArgumentException (1)); return null; } return IodineBool.Create (thisObj.Value.EndsWith (args [0].ToString ())); } [BuiltinDocString ( "Returns a new string where call occurances of [str1] have been replaced with [str2].", "@param str1 The value that will be replaced.", "@param str2 The value to replace [str1] with." )] private IodineObject Replace (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } if (args.Length < 2) { vm.RaiseException (new IodineArgumentException (2)); return null; } var arg1 = args [0] as IodineString; var arg2 = args [1] as IodineString; if (arg1 == null || arg2 == null) { vm.RaiseException (new IodineTypeException ("Str")); return null; } return new IodineString (thisObj.Value.Replace (arg1.Value, arg2.Value)); } [BuiltinDocString ( "Returns a list containing every substring between [seperator].", "@param seperator The seperator to split this string by." )] private IodineObject Split (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } if (args.Length < 1) { vm.RaiseException (new IodineArgumentException (1)); return null; } var ch = args [0] as IodineString; char val; if (ch == null) { vm.RaiseException (new IodineTypeException ("Str")); return null; } val = ch.Value [0]; var list = new IodineList (new IodineObject[]{ }); foreach (string str in thisObj.Value.Split (val)) { list.Add (new IodineString (str)); } return list; } [BuiltinDocString ( "Returns a string where all leading whitespace characters have been removed." )] private IodineObject Trim (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } return new IodineString (thisObj.Value.Trim ()); } [BuiltinDocString ( "Joins all arguments together, returning a string where this string has been placed between all supplied arguments", "@param *args Arguments to join together using this string as a seperator." )] private IodineObject Join (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } var accum = new StringBuilder (); var collection = args [0].GetIterator (vm); collection.IterReset (vm); string last = ""; string sep = ""; while (collection.IterMoveNext (vm)) { IodineObject o = collection.IterGetCurrent (vm); accum.AppendFormat ("{0}{1}", last, sep); last = o.ToString (vm).ToString (); sep = thisObj.Value; } accum.Append (last); return new IodineString (accum.ToString ()); } private IodineObject Format (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } string format = thisObj.Value; var formatter = new IodineFormatter (); return new IodineString (formatter.Format (vm, format, args)); } [BuiltinDocString ( "Returns true if all characters in this string are letters." )] private IodineObject IsLetter (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } bool result = thisObj.Value.Length == 0 ? false : true; for (int i = 0; i < thisObj.Value.Length; i++) { if (!char.IsLetter (thisObj.Value [i])) { return IodineBool.False; } } return IodineBool.Create (result); } [BuiltinDocString ( "Returns true if all characters in this string are digits." )] private IodineObject IsDigit (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } bool result = thisObj.Value.Length == 0 ? false : true; for (int i = 0; i < thisObj.Value.Length; i++) { if (!char.IsDigit (thisObj.Value [i])) { return IodineBool.False; } } return IodineBool.Create (result); } [BuiltinDocString ( "Returns true if all characters in this string are letters or digits." )] private IodineObject IsLetterOrDigit (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } bool result = thisObj.Value.Length == 0 ? false : true; for (int i = 0; i < thisObj.Value.Length; i++) { if (!char.IsLetterOrDigit (thisObj.Value [i])) { return IodineBool.False; } } return IodineBool.Create (result); } [BuiltinDocString ( "Returns true if all characters in this string are white space characters." )] private IodineObject IsWhiteSpace (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } bool result = thisObj.Value.Length == 0 ? false : true; for (int i = 0; i < thisObj.Value.Length; i++) { if (!char.IsWhiteSpace (thisObj.Value [i])) { return IodineBool.False; } } return IodineBool.Create (result); } [BuiltinDocString ( "Returns true if all characters in this string are symbols." )] private IodineObject IsSymbol (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } bool result = thisObj.Value.Length == 0 ? false : true; for (int i = 0; i < thisObj.Value.Length; i++) { if (!char.IsSymbol (thisObj.Value [i])) { return IodineBool.False; } } return IodineBool.Create (result); } [BuiltinDocString ( "Returns a string that has been justified by [n] characters to right.", "@param n How much to justify this string.", "@optional c The string to use as padding (Default is whitespace)." )] private IodineObject PadRight (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } char ch = ' '; if (args.Length == 0) { vm.RaiseException (new IodineArgumentException (1)); return null; } var width = args [0] as IodineInteger; if (width == null) { vm.RaiseException (new IodineTypeException ("Int")); return null; } if (args.Length > 1) { var chStr = args [0] as IodineString; if (chStr == null) { vm.RaiseException (new IodineTypeException ("Str")); return null; } ch = chStr.Value [0]; } return new IodineString (thisObj.Value.PadRight ((int)width.Value, ch)); } [BuiltinDocString ( "Returns a string that has been justified by [n] characters to left.", "@param n How much to justify this string.", "@optional c The string to use as padding (Default is whitespace)." )] private IodineObject PadLeft (VirtualMachine vm, IodineObject self, IodineObject[] args) { var thisObj = self as IodineString; if (thisObj == null) { vm.RaiseException (new IodineFunctionInvocationException ()); return null; } char ch = ' '; if (args.Length == 0) { vm.RaiseException (new IodineArgumentException (1)); return null; } var width = args [0] as IodineInteger; if (width == null) { vm.RaiseException (new IodineTypeException ("Int")); return null; } if (args.Length > 1) { var chStr = args [0] as IodineString; if (chStr == null) { vm.RaiseException (new IodineTypeException ("Str")); return null; } ch = chStr.Value [0]; } return new IodineString (thisObj.Value.PadLeft ((int)width.Value, ch)); } } class StringIterator : IodineObject { static IodineTypeDefinition TypeDefinition = new IodineTypeDefinition ("StrIterator"); private string value; private int iterIndex = 0; public StringIterator (string value) : base (TypeDefinition) { this.value = value; } public override IodineObject IterGetCurrent (VirtualMachine vm) { return new IodineString (value [iterIndex - 1].ToString ()); } public override bool IterMoveNext (VirtualMachine vm) { if (iterIndex >= value.Length) { return false; } iterIndex++; return true; } public override void IterReset (VirtualMachine vm) { iterIndex = 0; } } public string Value { private set; get; } private IodineString (string value, bool supressTypeBinding) { Value = value; } public IodineString (string val) : base (TypeDefinition) { Value = val ?? ""; // HACK: Add __iter__ attribute to match Iterable trait SetAttribute ("__iter__", new BuiltinMethodCallback ((VirtualMachine vm, IodineObject self, IodineObject [] args) => { return GetIterator (vm); }, this)); } public override bool Equals (IodineObject obj) { var strVal = obj as IodineString; if (strVal != null) { return strVal.Value == Value; } return false; } public override IodineObject Len (VirtualMachine vm) { return new IodineInteger (Value.Length); } public override IodineObject Slice (VirtualMachine vm, IodineSlice slice) { return new IodineString (Substring ( slice.Start, slice.Stop, slice.Stride, slice.DefaultStart, slice.DefaultStop) ); } private string Substring (int start, int end, int stride, bool defaultStart, bool defaultEnd) { int actualStart = start >= 0 ? start : Value.Length - (start + 2); int actualEnd = end >= 0 ? end : Value.Length - (end + 2); var accum = new StringBuilder (); if (stride >= 0) { if (defaultStart) { actualStart = 0; } if (defaultEnd) { actualEnd = Value.Length; } for (int i = actualStart; i < actualEnd; i += stride) { accum.Append (Value [i]); } } else { if (defaultStart) { actualStart = Value.Length - 1; } if (defaultEnd) { actualEnd = 0; } for (int i = actualStart; i >= actualEnd; i += stride) { accum.Append (Value [i]); } } return accum.ToString (); } public override IodineObject Compare (VirtualMachine vm, IodineObject obj) { return new IodineInteger (Value.CompareTo (obj.ToString ())); } public override IodineObject Add (VirtualMachine vm, IodineObject right) { var str = right as IodineString; if (str == null) { vm.RaiseException ("Right hand value must be of type Str!"); return null; } return new IodineString (Value + str.Value); } public override bool Equals (object obj) { return Equals (obj as IodineObject); } public override IodineObject Equals (VirtualMachine vm, IodineObject right) { var str = right as IodineString; if (str == null) { return base.Equals (vm, right); } return IodineBool.Create (str.Value == Value); } public override IodineObject NotEquals (VirtualMachine vm, IodineObject right) { var str = right as IodineString; if (str == null) { return base.NotEquals (vm, right); } return IodineBool.Create (str.Value != Value); } public override string ToString () { return Value; } public override int GetHashCode () { if (Value == null) { return 0; } return Value.GetHashCode (); } public override IodineObject GetIndex (VirtualMachine vm, IodineObject key) { var index = key as IodineInteger; if (index == null) { vm.RaiseException (new IodineTypeException ("Int")); return null; } if (index.Value >= Value.Length) { vm.RaiseException (new IodineIndexException ()); return null; } return new IodineString (Value [(int)index.Value].ToString ()); } public override IodineObject GetIterator (VirtualMachine vm) { return new StringIterator (Value); } public override IodineObject Represent (VirtualMachine vm) { return new IodineString (String.Format ("\"{0}\"", Value)); } public override bool IsTrue () { return Value.Length > 0; } internal static IodineString CreateTypelessString (string str) { return new IodineString (str, false); } } }
// 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.Linq; using NUnit.Framework; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Rulesets; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Edit.Blueprints.HitCircles.Components; using osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components; using osu.Game.Rulesets.Osu.UI; using osu.Game.Tests.Beatmaps; using osu.Game.Screens.Edit.Compose.Components; using osuTK; using osuTK.Input; namespace osu.Game.Tests.Visual.Editing { public class TestSceneComposerSelection : EditorTestScene { protected override Ruleset CreateEditorRuleset() => new OsuRuleset(); protected override IBeatmap CreateBeatmap(RulesetInfo ruleset) => new TestBeatmap(ruleset, false); private ComposeBlueprintContainer blueprintContainer => Editor.ChildrenOfType<ComposeBlueprintContainer>().First(); private void moveMouseToObject(Func<HitObject> targetFunc) { AddStep("move mouse to object", () => { var pos = blueprintContainer.SelectionBlueprints .First(s => s.Item == targetFunc()) .ChildrenOfType<HitCirclePiece>() .First().ScreenSpaceDrawQuad.Centre; InputManager.MoveMouseTo(pos); }); } [Test] public void TestNudgeSelection() { HitCircle[] addedObjects = null; AddStep("add hitobjects", () => EditorBeatmap.AddRange(addedObjects = new[] { new HitCircle { StartTime = 100 }, new HitCircle { StartTime = 200, Position = new Vector2(100) }, new HitCircle { StartTime = 300, Position = new Vector2(200) }, new HitCircle { StartTime = 400, Position = new Vector2(300) }, })); AddStep("select objects", () => EditorBeatmap.SelectedHitObjects.AddRange(addedObjects)); AddStep("nudge forwards", () => InputManager.Key(Key.K)); AddAssert("objects moved forwards in time", () => addedObjects[0].StartTime > 100); AddStep("nudge backwards", () => InputManager.Key(Key.J)); AddAssert("objects reverted to original position", () => addedObjects[0].StartTime == 100); } [Test] public void TestBasicSelect() { var addedObject = new HitCircle { StartTime = 100 }; AddStep("add hitobject", () => EditorBeatmap.Add(addedObject)); moveMouseToObject(() => addedObject); AddStep("left click", () => InputManager.Click(MouseButton.Left)); AddAssert("hitobject selected", () => EditorBeatmap.SelectedHitObjects.Single() == addedObject); var addedObject2 = new HitCircle { StartTime = 100, Position = new Vector2(100), }; AddStep("add one more hitobject", () => EditorBeatmap.Add(addedObject2)); AddAssert("selection unchanged", () => EditorBeatmap.SelectedHitObjects.Single() == addedObject); moveMouseToObject(() => addedObject2); AddStep("left click", () => InputManager.Click(MouseButton.Left)); AddAssert("hitobject selected", () => EditorBeatmap.SelectedHitObjects.Single() == addedObject2); } [Test] public void TestMultiSelect() { var addedObjects = new[] { new HitCircle { StartTime = 100 }, new HitCircle { StartTime = 200, Position = new Vector2(100) }, new HitCircle { StartTime = 300, Position = new Vector2(200) }, new HitCircle { StartTime = 400, Position = new Vector2(300) }, }; AddStep("add hitobjects", () => EditorBeatmap.AddRange(addedObjects)); moveMouseToObject(() => addedObjects[0]); AddStep("click first", () => InputManager.Click(MouseButton.Left)); AddAssert("hitobject selected", () => EditorBeatmap.SelectedHitObjects.Single() == addedObjects[0]); AddStep("hold control", () => InputManager.PressKey(Key.ControlLeft)); moveMouseToObject(() => addedObjects[1]); AddStep("click second", () => InputManager.Click(MouseButton.Left)); AddAssert("2 hitobjects selected", () => EditorBeatmap.SelectedHitObjects.Count == 2 && EditorBeatmap.SelectedHitObjects.Contains(addedObjects[1])); moveMouseToObject(() => addedObjects[2]); AddStep("click third", () => InputManager.Click(MouseButton.Left)); AddAssert("3 hitobjects selected", () => EditorBeatmap.SelectedHitObjects.Count == 3 && EditorBeatmap.SelectedHitObjects.Contains(addedObjects[2])); moveMouseToObject(() => addedObjects[1]); AddStep("click second", () => InputManager.Click(MouseButton.Left)); AddAssert("2 hitobjects selected", () => EditorBeatmap.SelectedHitObjects.Count == 2 && !EditorBeatmap.SelectedHitObjects.Contains(addedObjects[1])); } [TestCase(false)] [TestCase(true)] public void TestMultiSelectFromDrag(bool alreadySelectedBeforeDrag) { HitCircle[] addedObjects = null; AddStep("add hitobjects", () => EditorBeatmap.AddRange(addedObjects = new[] { new HitCircle { StartTime = 100 }, new HitCircle { StartTime = 200, Position = new Vector2(100) }, new HitCircle { StartTime = 300, Position = new Vector2(200) }, new HitCircle { StartTime = 400, Position = new Vector2(300) }, })); moveMouseToObject(() => addedObjects[0]); AddStep("click first", () => InputManager.Click(MouseButton.Left)); AddStep("hold control", () => InputManager.PressKey(Key.ControlLeft)); moveMouseToObject(() => addedObjects[1]); if (alreadySelectedBeforeDrag) AddStep("click second", () => InputManager.Click(MouseButton.Left)); AddStep("mouse down on second", () => InputManager.PressButton(MouseButton.Left)); AddAssert("2 hitobjects selected", () => EditorBeatmap.SelectedHitObjects.Count == 2 && EditorBeatmap.SelectedHitObjects.Contains(addedObjects[1])); AddStep("drag to centre", () => InputManager.MoveMouseTo(blueprintContainer.ScreenSpaceDrawQuad.Centre)); AddAssert("positions changed", () => addedObjects[0].Position != Vector2.Zero && addedObjects[1].Position != new Vector2(50)); AddStep("release control", () => InputManager.ReleaseKey(Key.ControlLeft)); AddStep("mouse up", () => InputManager.ReleaseButton(MouseButton.Left)); } [Test] public void TestBasicDeselect() { var addedObject = new HitCircle { StartTime = 100 }; AddStep("add hitobject", () => EditorBeatmap.Add(addedObject)); moveMouseToObject(() => addedObject); AddStep("left click", () => InputManager.Click(MouseButton.Left)); AddAssert("hitobject selected", () => EditorBeatmap.SelectedHitObjects.Single() == addedObject); AddStep("click away", () => { InputManager.MoveMouseTo(blueprintContainer.ScreenSpaceDrawQuad.Centre); InputManager.Click(MouseButton.Left); }); AddAssert("selection lost", () => EditorBeatmap.SelectedHitObjects.Count == 0); } [Test] public void TestQuickDeleteRemovesObjectInPlacement() { var addedObject = new HitCircle { StartTime = 0, Position = OsuPlayfield.BASE_SIZE * 0.5f }; AddStep("add hitobject", () => EditorBeatmap.Add(addedObject)); AddStep("enter placement mode", () => InputManager.PressKey(Key.Number2)); moveMouseToObject(() => addedObject); AddStep("hold shift", () => InputManager.PressKey(Key.ShiftLeft)); AddStep("right click", () => InputManager.Click(MouseButton.Right)); AddStep("release shift", () => InputManager.ReleaseKey(Key.ShiftLeft)); AddAssert("no hitobjects in beatmap", () => EditorBeatmap.HitObjects.Count == 0); } [Test] public void TestQuickDeleteRemovesObjectInSelection() { var addedObject = new HitCircle { StartTime = 0, Position = OsuPlayfield.BASE_SIZE * 0.5f }; AddStep("add hitobject", () => EditorBeatmap.Add(addedObject)); AddStep("select added object", () => EditorBeatmap.SelectedHitObjects.Add(addedObject)); moveMouseToObject(() => addedObject); AddStep("hold shift", () => InputManager.PressKey(Key.ShiftLeft)); AddStep("right click", () => InputManager.Click(MouseButton.Right)); AddStep("release shift", () => InputManager.ReleaseKey(Key.ShiftLeft)); AddAssert("no hitobjects in beatmap", () => EditorBeatmap.HitObjects.Count == 0); } [Test] public void TestQuickDeleteRemovesSliderControlPoint() { Slider slider = null; PathControlPoint[] points = { new PathControlPoint(), new PathControlPoint(new Vector2(50, 0)), new PathControlPoint(new Vector2(100, 0)) }; AddStep("add slider", () => { slider = new Slider { StartTime = 1000, Path = new SliderPath(points) }; EditorBeatmap.Add(slider); }); AddStep("select added slider", () => EditorBeatmap.SelectedHitObjects.Add(slider)); AddStep("move mouse to controlpoint", () => { var pos = blueprintContainer.ChildrenOfType<PathControlPointPiece>().ElementAt(1).ScreenSpaceDrawQuad.Centre; InputManager.MoveMouseTo(pos); }); AddStep("hold shift", () => InputManager.PressKey(Key.ShiftLeft)); AddStep("right click", () => InputManager.Click(MouseButton.Right)); AddAssert("slider has 2 points", () => slider.Path.ControlPoints.Count == 2); AddStep("right click", () => InputManager.Click(MouseButton.Right)); // second click should nuke the object completely. AddAssert("no hitobjects in beatmap", () => EditorBeatmap.HitObjects.Count == 0); AddStep("release shift", () => InputManager.ReleaseKey(Key.ShiftLeft)); } } }
// /* // * Copyright (c) 2016, Alachisoft. All Rights Reserved. // * // * Licensed under the Apache License, Version 2.0 (the "License"); // * you may not use this file except in compliance with the License. // * You may obtain a copy of the License at // * // * http://www.apache.org/licenses/LICENSE-2.0 // * // * Unless required by applicable law or agreed to in writing, software // * distributed under the License is distributed on an "AS IS" BASIS, // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * See the License for the specific language governing permissions and // * limitations under the License. // */ using System; using System.Collections; namespace Alachisoft.NosDB.Common.DataStructures { public class BinaryPriorityQueue : IPriorityQueue, ICollection, ICloneable, IList { protected ArrayList InnerList = new ArrayList(); protected IComparer Comparer; #region contructors public BinaryPriorityQueue() : this(System.Collections.Comparer.Default) {} public BinaryPriorityQueue(IComparer c) { Comparer = c; } public BinaryPriorityQueue(int C) : this(System.Collections.Comparer.Default,C) {} public BinaryPriorityQueue(IComparer c, int Capacity) { Comparer = c; InnerList.Capacity = Capacity; } protected BinaryPriorityQueue(ArrayList Core, IComparer Comp, bool Copy) { if(Copy) InnerList = Core.Clone() as ArrayList; else InnerList = Core; Comparer = Comp; } #endregion protected void SwitchElements(int i, int j) { object h = InnerList[i]; InnerList[i] = InnerList[j]; InnerList[j] = h; } protected virtual int OnCompare(int i, int j) { return Comparer.Compare(InnerList[i],InnerList[j]); } #region public methods /// <summary> /// Push an object onto the PQ /// </summary> /// <param name="O">The new object</param> /// <returns>The index in the list where the object is _now_. This will change when objects are taken from or put onto the PQ.</returns> public int Push(object O) { int p = InnerList.Count,p2; InnerList.Add(O); // E[p] = O do { if(p==0) break; p2 = (p-1)/2; if(OnCompare(p,p2)<0) { SwitchElements(p,p2); p = p2; } else break; }while(true); return p; } /// <summary> /// Get the smallest object and remove it. /// </summary> /// <returns>The smallest object</returns> public object Pop() { object result = InnerList[0]; int p = 0,p1,p2,pn; InnerList[0] = InnerList[InnerList.Count-1]; InnerList.RemoveAt(InnerList.Count-1); do { pn = p; p1 = 2*p+1; p2 = 2*p+2; if(InnerList.Count>p1 && OnCompare(p,p1)>0) p = p1; if(InnerList.Count>p2 && OnCompare(p,p2)>0) p = p2; if(p==pn) break; SwitchElements(p,pn); }while(true); return result; } /// <summary> /// Notify the PQ that the object at position i has changed /// and the PQ needs to restore order. /// Since you dont have access to any indexes (except by using the /// explicit IList.this) you should not call this function without knowing exactly /// what you do. /// </summary> /// <param name="i">The index of the changed object.</param> public void Update(int i) { int p = i,pn; int p1,p2; do { if(p==0) break; p2 = (p-1)/2; if(OnCompare(p,p2)<0) { SwitchElements(p,p2); p = p2; } else break; }while(true); if(p<i) return; do { pn = p; p1 = 2*p+1; p2 = 2*p+2; if(InnerList.Count>p1 && OnCompare(p,p1)>0) p = p1; if(InnerList.Count>p2 && OnCompare(p,p2)>0) p = p2; if(p==pn) break; SwitchElements(p,pn); }while(true); } /// <summary> /// Get the smallest object without removing it. /// </summary> /// <returns>The smallest object</returns> public object Peek() { if(InnerList.Count>0) return InnerList[0]; return null; } public bool Contains(object value) { return InnerList.Contains(value); } public void Clear() { InnerList.Clear(); } public int Count { get { return InnerList.Count; } } IEnumerator IEnumerable.GetEnumerator() { return InnerList.GetEnumerator(); } public void CopyTo(Array array, int index) { InnerList.CopyTo(array,index); } public object Clone() { return new BinaryPriorityQueue(InnerList,Comparer,true); } public bool IsSynchronized { get { return InnerList.IsSynchronized; } } public object SyncRoot { get { return this; } } #endregion #region explicit implementation bool IList.IsReadOnly { get { return false; } } object IList.this[int index] { get { return InnerList[index]; } set { InnerList[index] = value; Update(index); } } int IList.Add(object o) { return Push(o); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } int IList.IndexOf(object value) { throw new NotSupportedException(); } bool IList.IsFixedSize { get { return false; } } public static BinaryPriorityQueue Syncronized(BinaryPriorityQueue P) { return new BinaryPriorityQueue(ArrayList.Synchronized(P.InnerList),P.Comparer,false); } public static BinaryPriorityQueue ReadOnly(BinaryPriorityQueue P) { return new BinaryPriorityQueue(ArrayList.ReadOnly(P.InnerList),P.Comparer,false); } #endregion } }
using System; using UnityEngine; [AddComponentMenu("NGUI/Interaction/Key Navigation")] public class UIKeyNavigation : MonoBehaviour { public enum Constraint { None, Vertical, Horizontal, Explicit } public static BetterList<UIKeyNavigation> list = new BetterList<UIKeyNavigation>(); public UIKeyNavigation.Constraint constraint; public GameObject onUp; public GameObject onDown; public GameObject onLeft; public GameObject onRight; public GameObject onClick; public bool startsSelected; protected virtual void OnEnable() { UIKeyNavigation.list.Add(this); if (this.startsSelected && (UICamera.selectedObject == null || !NGUITools.GetActive(UICamera.selectedObject))) { UICamera.currentScheme = UICamera.ControlScheme.Controller; UICamera.selectedObject = base.gameObject; } } protected virtual void OnDisable() { UIKeyNavigation.list.Remove(this); } protected GameObject GetLeft() { if (NGUITools.GetActive(this.onLeft)) { return this.onLeft; } if (this.constraint == UIKeyNavigation.Constraint.Vertical || this.constraint == UIKeyNavigation.Constraint.Explicit) { return null; } return this.Get(Vector3.left, true); } private GameObject GetRight() { if (NGUITools.GetActive(this.onRight)) { return this.onRight; } if (this.constraint == UIKeyNavigation.Constraint.Vertical || this.constraint == UIKeyNavigation.Constraint.Explicit) { return null; } return this.Get(Vector3.right, true); } protected GameObject GetUp() { if (NGUITools.GetActive(this.onUp)) { return this.onUp; } if (this.constraint == UIKeyNavigation.Constraint.Horizontal || this.constraint == UIKeyNavigation.Constraint.Explicit) { return null; } return this.Get(Vector3.up, false); } protected GameObject GetDown() { if (NGUITools.GetActive(this.onDown)) { return this.onDown; } if (this.constraint == UIKeyNavigation.Constraint.Horizontal || this.constraint == UIKeyNavigation.Constraint.Explicit) { return null; } return this.Get(Vector3.down, false); } protected GameObject Get(Vector3 myDir, bool horizontal) { Transform transform = base.transform; myDir = transform.TransformDirection(myDir); Vector3 center = UIKeyNavigation.GetCenter(base.gameObject); float num = 3.40282347E+38f; GameObject result = null; for (int i = 0; i < UIKeyNavigation.list.size; i++) { UIKeyNavigation uIKeyNavigation = UIKeyNavigation.list[i]; if (!(uIKeyNavigation == this)) { Vector3 direction = UIKeyNavigation.GetCenter(uIKeyNavigation.gameObject) - center; float num2 = Vector3.Dot(myDir, direction.normalized); if (num2 >= 0.707f) { direction = transform.InverseTransformDirection(direction); if (horizontal) { direction.y *= 2f; } else { direction.x *= 2f; } float sqrMagnitude = direction.sqrMagnitude; if (sqrMagnitude <= num) { result = uIKeyNavigation.gameObject; num = sqrMagnitude; } } } } return result; } protected static Vector3 GetCenter(GameObject go) { UIWidget component = go.GetComponent<UIWidget>(); if (component != null) { Vector3[] worldCorners = component.worldCorners; return (worldCorners[0] + worldCorners[2]) * 0.5f; } return go.transform.position; } protected virtual void OnKey(KeyCode key) { if (!NGUITools.GetActive(this)) { return; } GameObject gameObject = null; switch (key) { case KeyCode.UpArrow: gameObject = this.GetUp(); break; case KeyCode.DownArrow: gameObject = this.GetDown(); break; case KeyCode.RightArrow: gameObject = this.GetRight(); break; case KeyCode.LeftArrow: gameObject = this.GetLeft(); break; default: if (key == KeyCode.Tab) { if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) { gameObject = this.GetLeft(); if (gameObject == null) { gameObject = this.GetUp(); } if (gameObject == null) { gameObject = this.GetDown(); } if (gameObject == null) { gameObject = this.GetRight(); } } else { gameObject = this.GetRight(); if (gameObject == null) { gameObject = this.GetDown(); } if (gameObject == null) { gameObject = this.GetUp(); } if (gameObject == null) { gameObject = this.GetLeft(); } } } break; } if (gameObject != null) { UICamera.selectedObject = gameObject; } } protected virtual void OnClick() { if (NGUITools.GetActive(this) && NGUITools.GetActive(this.onClick)) { UICamera.selectedObject = this.onClick; } } private void OnDestroy() { this.onUp = null; this.onDown = null; this.onLeft = null; this.onRight = null; this.onClick = null; } }
namespace IDT4.Engine.CM { internal partial class CollisionModelManager { /* =============================================================================== Trace through the spatial subdivision =============================================================================== */ /* ================ idCollisionModelManagerLocal::TraceTrmThroughNode ================ */ void idCollisionModelManagerLocal::TraceTrmThroughNode( cm_traceWork_t *tw, cm_node_t *node ) { cm_polygonRef_t *pref; cm_brushRef_t *bref; // position test if ( tw->positionTest ) { // if already stuck in solid if ( tw->trace.fraction == 0.0f ) { return; } // test if any of the trm vertices is inside a brush for ( bref = node->brushes; bref; bref = bref->next ) { if ( idCollisionModelManagerLocal::TestTrmVertsInBrush( tw, bref->b ) ) { return; } } // if just testing a point we're done if ( tw->pointTrace ) { return; } // test if the trm is stuck in any polygons for ( pref = node->polygons; pref; pref = pref->next ) { if ( idCollisionModelManagerLocal::TestTrmInPolygon( tw, pref->p ) ) { return; } } } else if ( tw->rotation ) { // rotate through all polygons in this leaf for ( pref = node->polygons; pref; pref = pref->next ) { if ( idCollisionModelManagerLocal::RotateTrmThroughPolygon( tw, pref->p ) ) { return; } } } else { // trace through all polygons in this leaf for ( pref = node->polygons; pref; pref = pref->next ) { if ( idCollisionModelManagerLocal::TranslateTrmThroughPolygon( tw, pref->p ) ) { return; } } } } /* ================ idCollisionModelManagerLocal::TraceThroughAxialBSPTree_r ================ */ //#define NO_SPATIAL_SUBDIVISION void idCollisionModelManagerLocal::TraceThroughAxialBSPTree_r( cm_traceWork_t *tw, cm_node_t *node, float p1f, float p2f, idVec3 &p1, idVec3 &p2) { float t1, t2, offset; float frac, frac2; float idist; idVec3 mid; int side; float midf; if ( !node ) { return; } if ( tw->quickExit ) { return; // stop immediately } if ( tw->trace.fraction <= p1f ) { return; // already hit something nearer } // if we need to test this node for collisions if ( node->polygons || (tw->positionTest && node->brushes) ) { // trace through node with collision data idCollisionModelManagerLocal::TraceTrmThroughNode( tw, node ); } // if already stuck in solid if ( tw->positionTest && tw->trace.fraction == 0.0f ) { return; } // if this is a leaf node if ( node->planeType == -1 ) { return; } #ifdef NO_SPATIAL_SUBDIVISION idCollisionModelManagerLocal::TraceThroughAxialBSPTree_r( tw, node->children[0], p1f, p2f, p1, p2 ); idCollisionModelManagerLocal::TraceThroughAxialBSPTree_r( tw, node->children[1], p1f, p2f, p1, p2 ); return; #endif // distance from plane for trace start and end t1 = p1[node->planeType] - node->planeDist; t2 = p2[node->planeType] - node->planeDist; // adjust the plane distance appropriately for mins/maxs offset = tw->extents[node->planeType]; // see which sides we need to consider if ( t1 >= offset && t2 >= offset ) { idCollisionModelManagerLocal::TraceThroughAxialBSPTree_r( tw, node->children[0], p1f, p2f, p1, p2 ); return; } if ( t1 < -offset && t2 < -offset ) { idCollisionModelManagerLocal::TraceThroughAxialBSPTree_r( tw, node->children[1], p1f, p2f, p1, p2 ); return; } if ( t1 < t2 ) { idist = 1.0f / (t1-t2); side = 1; frac2 = (t1 + offset) * idist; frac = (t1 - offset) * idist; } else if (t1 > t2) { idist = 1.0f / (t1-t2); side = 0; frac2 = (t1 - offset) * idist; frac = (t1 + offset) * idist; } else { side = 0; frac = 1.0f; frac2 = 0.0f; } // move up to the node if ( frac < 0.0f ) { frac = 0.0f; } else if ( frac > 1.0f ) { frac = 1.0f; } midf = p1f + (p2f - p1f)*frac; mid[0] = p1[0] + frac*(p2[0] - p1[0]); mid[1] = p1[1] + frac*(p2[1] - p1[1]); mid[2] = p1[2] + frac*(p2[2] - p1[2]); idCollisionModelManagerLocal::TraceThroughAxialBSPTree_r( tw, node->children[side], p1f, midf, p1, mid ); // go past the node if ( frac2 < 0.0f ) { frac2 = 0.0f; } else if ( frac2 > 1.0f ) { frac2 = 1.0f; } midf = p1f + (p2f - p1f)*frac2; mid[0] = p1[0] + frac2*(p2[0] - p1[0]); mid[1] = p1[1] + frac2*(p2[1] - p1[1]); mid[2] = p1[2] + frac2*(p2[2] - p1[2]); idCollisionModelManagerLocal::TraceThroughAxialBSPTree_r( tw, node->children[side^1], midf, p2f, mid, p2 ); } /* ================ idCollisionModelManagerLocal::TraceThroughModel ================ */ void idCollisionModelManagerLocal::TraceThroughModel( cm_traceWork_t *tw ) { float d; int i, numSteps; idVec3 start, end; idRotation rot; if ( !tw->rotation ) { // trace through spatial subdivision and then through leafs idCollisionModelManagerLocal::TraceThroughAxialBSPTree_r( tw, tw->model->node, 0, 1, tw->start, tw->end ); } else { // approximate the rotation with a series of straight line movements // total length covered along circle d = tw->radius * DEG2RAD( tw->angle ); // if more than one step if ( d > CIRCLE_APPROXIMATION_LENGTH ) { // number of steps for the approximation numSteps = (int) (CIRCLE_APPROXIMATION_LENGTH / d); // start of approximation start = tw->start; // trace circle approximation steps through the BSP tree for ( i = 0; i < numSteps; i++ ) { // calculate next point on approximated circle rot.Set( tw->origin, tw->axis, tw->angle * ((float) (i+1) / numSteps) ); end = start * rot; // trace through spatial subdivision and then through leafs idCollisionModelManagerLocal::TraceThroughAxialBSPTree_r( tw, tw->model->node, 0, 1, start, end ); // no need to continue if something was hit already if ( tw->trace.fraction < 1.0f ) { return; } start = end; } } else { start = tw->start; } // last step of the approximation idCollisionModelManagerLocal::TraceThroughAxialBSPTree_r( tw, tw->model->node, 0, 1, start, tw->end ); } } } }
// 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using GgpGrpc.Cloud; using GgpGrpc.Models; using Microsoft.VisualStudio.Threading; using NSubstitute; using NUnit.Framework; using YetiCommon; using YetiVSI.GameLaunch; using YetiVSI.Metrics; using YetiVSI.ProjectSystem.Abstractions; using YetiVSI.Shared.Metrics; namespace YetiVSI.Test.GameLaunch { [TestFixture] public class VsiGameLaunchTests { const string _launchId = "game-launch-id"; const string _appId = "app-id"; static readonly string _launchName = "organizations/org-id/projects/proj-id/testAccounts/" + $"test-account-id/gameLaunches/{_launchId}"; VsiGameLaunch _target; IGameletClient _gameletClient; CancelableTask.Factory _cancelableTaskFactory; IGameLaunchBeHelper _gameLaunchBeHelper; IMetrics _metrics; ActionRecorder _actionRecorder; IDialogUtil _dialogUtil; IChromeClientsLauncher _launcher; LaunchParams _params; [SetUp] public void Setup() { _gameletClient = Substitute.For<IGameletClient>(); _cancelableTaskFactory = Substitute.For<CancelableTask.Factory>(); _gameLaunchBeHelper = Substitute.For<IGameLaunchBeHelper>(); _metrics = Substitute.For<IMetrics>(); _actionRecorder = Substitute.For<ActionRecorder>(_metrics); _dialogUtil = Substitute.For<IDialogUtil>(); _launcher = Substitute.For<IChromeClientsLauncher>(); _params = new LaunchParams(); _launcher.LaunchParams.Returns(_params); } [Test] public void IdentifiersTest() { _target = GetGameLaunch(false, false); Assert.That(_target.LaunchName, Is.EqualTo(_launchName)); Assert.That(_target.LaunchId, Is.EqualTo(_launchId)); } [Test] public async Task GetLaunchStateAsyncTestAsync() { _target = GetGameLaunch(false, false); var action = Substitute.For<IAction>(); var gameLaunch = GetGameLaunch(); _gameletClient.GetGameLaunchStateAsync(_launchName, action) .Returns(Task.FromResult(gameLaunch)); GgpGrpc.Models.GameLaunch result = await _target.GetLaunchStateAsync(action); Assert.That(result, Is.EqualTo(gameLaunch)); } [TestCase(EndReason.GameExitedWithSuccessfulCode, false, TestName = "GameExitedWithSuccessfulCode")] [TestCase(EndReason.GameExitedWithErrorCode, true, TestName = "GameExitedWithErrorCode")] [TestCase(EndReason.ExitedByUser, true, TestName = "GameExitedWithErrorCode")] [TestCase(EndReason.GameShutdownBySystem, true, TestName = "GameShutdownBySystem")] [TestCase(null, false, TestName = "GameNotEnded")] public async Task WaitForGameLaunchEndedAndRecordTestAsync(EndReason? reason, bool throws) { _target = GetGameLaunch(false, false); var action = Substitute.For<IAction>(); DeveloperLogEvent devEvent = SetupUpdateEvent(action); action.RecordAsync(Arg.Any<Task>()).Returns(callInfo => callInfo.Arg<Task>()); _actionRecorder.CreateToolAction(ActionType.GameLaunchWaitForEnd).Returns(action); var endResult = new DeleteLaunchResult( GetGameLaunch(GameLaunchState.GameLaunchEnded, reason), true); _gameLaunchBeHelper .WaitUntilGameLaunchEndedAsync(_launchName, Arg.Any<ICancelable>(), action) .Returns(Task.FromResult(endResult)); if (throws) { Assert.ThrowsAsync<GameLaunchFailError>( async () => await _target.WaitForGameLaunchEndedAndRecordAsync()); } else { await _target.WaitForGameLaunchEndedAndRecordAsync(); } Assert.That(devEvent.GameLaunchData.LaunchId, Is.EqualTo(_launchId)); Assert.That(devEvent.GameLaunchData.EndReason, Is.EqualTo((int?) reason)); await action.Received(1).RecordAsync(Arg.Any<Task>()); } [TestCase(new[] { GameLaunchState.IncompleteLaunch, GameLaunchState.RunningGame }, new[] { 4, 1 }, true, TestName = "RunningAfterIncomplete")] [TestCase(new[] { GameLaunchState.ReadyToPlay, GameLaunchState.RunningGame }, new[] { 3, 1 }, true, TestName = "RunningAfterLaunching")] [TestCase(new[] { GameLaunchState.IncompleteLaunch, GameLaunchState.GameLaunchEnded }, new[] { 3, 1 }, false, EndReason.GameShutdownBySystem, TestName = "EndAfterIncomplete")] [TestCase(new[] { GameLaunchState.IncompleteLaunch, GameLaunchState.RunningGame }, new[] { 7, 1 }, false, TestName = "RunningTimeout")] [TestCase(new[] { GameLaunchState.IncompleteLaunch, GameLaunchState.RunningGame }, new[] { 7, 1 }, true, null, true, TestName = "NoTimeOutWithDeferred")] [TestCase(new[] { GameLaunchState.IncompleteLaunch, GameLaunchState.RunningGame }, new[] { 3, 1 }, true, null, true, "external", TestName = "RunWithExternalAccount")] public void WaitUntilGameLaunchedTest(GameLaunchState[] launchStates, int[] stateRepeat, bool launchResult, EndReason? endReason = null, bool isDevResumeOfferEnabled = false, string externalId = null) { _target = GetGameLaunch(isDevResumeOfferEnabled, externalId != null); Func<ICancelable, Task> currentTask = null; var action = Substitute.For<IAction>(); DeveloperLogEvent devEvent = SetupUpdateEvent(action); _actionRecorder.CreateToolAction(ActionType.GameLaunchWaitForStart).Returns(action); var cancelable = Substitute.For<ICancelableTask>(); action.Record(Arg.Any<Func<bool>>()).Returns(callInfo => { new JoinableTaskFactory(new JoinableTaskContext()).Run( () => currentTask(new NothingToCancel())); return true; }); if (isDevResumeOfferEnabled) { string message = externalId == null ? TaskMessages.LaunchingDeferredGame : TaskMessages.LaunchingDeferredGameWithExternalId(_appId); _cancelableTaskFactory.Create( message, TaskMessages.LaunchingDeferredGameTitle, Arg.Any<Func<ICancelable, Task>>()).Returns(callInfo => { currentTask = callInfo.Arg<Func<ICancelable, Task>>(); return cancelable; }); } else { _cancelableTaskFactory.Create( TaskMessages.LaunchingGame, Arg.Any<Func<ICancelable, Task>>()).Returns(callInfo => { currentTask = callInfo.Arg<Func<ICancelable, Task>>(); return cancelable; }); } List<GameLaunchState> statusSequence = launchStates .Select((state, i) => Enumerable.Repeat(state, stateRepeat[i])) .SelectMany(states => states).ToList(); Task<GgpGrpc.Models.GameLaunch>[] launches = statusSequence.Select( (state, i) => Task.FromResult(GetGameLaunch(state, i == statusSequence.Count - 1 ? endReason : null))).ToArray(); _gameletClient.GetGameLaunchStateAsync(_launchName, action) .Returns(launches[0], launches.Skip(1).ToArray()); bool launched = _target.WaitUntilGameLaunched(); Assert.That(launched, Is.EqualTo(launchResult)); if (!launchResult) { _dialogUtil.Received(1).ShowError(Arg.Any<string>()); } Assert.That(devEvent.GameLaunchData.LaunchId, Is.EqualTo(_launchId)); Assert.That(devEvent.GameLaunchData.EndReason, Is.EqualTo((int?) endReason)); action.Received(1).Record(Arg.Any<Func<bool>>()); } GgpGrpc.Models.GameLaunch GetGameLaunch(GameLaunchState state = GameLaunchState.RunningGame, EndReason? endReason = null) => new GgpGrpc.Models.GameLaunch { GameletName = "gamelet/123", Name = _launchName, GameLaunchState = state, GameLaunchEnded = endReason.HasValue ? new GameLaunchEnded(endReason.Value) : null }; DeveloperLogEvent SetupUpdateEvent(IAction action) { var devEvent = new DeveloperLogEvent(); action.When(a => a.UpdateEvent(Arg.Any<DeveloperLogEvent>())).Do(callInfo => { var evt = callInfo.Arg<DeveloperLogEvent>(); devEvent.MergeFrom(evt); }); return devEvent; } VsiGameLaunch GetGameLaunch(bool isDeveloperResumeOfferEnabled, bool isExternalAccount) => new VsiGameLaunch(_launchName, isDeveloperResumeOfferEnabled, isExternalAccount, _appId, _gameletClient, _cancelableTaskFactory, _gameLaunchBeHelper, _actionRecorder, _dialogUtil, pollingTimeoutMs: 500, pollingTimeoutResumeOfferMs: 1000, pollDelayMs: 100); } }
// VncSharp - .NET VNC Client Library // Copyright (C) 2008 David Humphrey // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using System.Drawing; using System.Threading; using System.Reflection; using System.Windows.Forms; using System.ComponentModel; using System.Drawing.Imaging; using System.Drawing.Drawing2D; using Nixxis.RfbClient.Encodings; namespace Nixxis.RfbClient { /// <summary> /// Event Handler delegate declaration used by events that signal successful connection with the server. /// </summary> public delegate void ConnectCompleteHandler(object sender, ConnectEventArgs e); /// <summary> /// When connecting to a VNC Host, a password will sometimes be required. Therefore a password must be obtained from the user. A default Password dialog box is included and will be used unless users of the control provide their own Authenticate delegate function for the task. For example, this might pull a password from a configuration file of some type instead of prompting the user. /// </summary> public delegate string AuthenticateDelegate(); /// <summary> /// SpecialKeys is a list of the various keyboard combinations that overlap with the client-side and make it /// difficult to send remotely. These values are used in conjunction with the SendSpecialKeys method. /// </summary> public enum SpecialKeys { CtrlAltDel, AltF4, CtrlEsc, Ctrl, Alt } [ToolboxBitmap(typeof(RemoteDesktop), "Resources.vncviewer.ico")] /// <summary> /// The RemoteDesktop control takes care of all the necessary RFB Protocol and GUI handling, including mouse and keyboard support, as well as requesting and processing screen updates from the remote VNC host. Most users will choose to use the RemoteDesktop control alone and not use any of the other protocol classes directly. /// </summary> public class RemoteDesktop : Panel { [Description("Raised after a successful call to the Connect() method.")] /// <summary> /// Raised after a successful call to the Connect() method. Includes information for updating the local display in ConnectEventArgs. /// </summary> public event ConnectCompleteHandler ConnectComplete; [Description("Raised when the VNC Host drops the connection.")] /// <summary> /// Raised when the VNC Host drops the connection. /// </summary> public event EventHandler ConnectionLost; [Description("Raised when the VNC Host sends text to the client's clipboard.")] /// <summary> /// Raised when the VNC Host sends text to the client's clipboard. /// </summary> public event EventHandler ClipboardChanged; /// <summary> /// Points to a Function capable of obtaining a user's password. By default this means using the PasswordDialog.GetPassword() function; however, users of RemoteDesktop can replace this with any function they like, so long as it matches the delegate type. /// </summary> public AuthenticateDelegate GetPassword; Bitmap desktop; // Internal representation of remote image. Image designModeDesktop; // Used when painting control in VS.NET designer VncClient vnc; // The Client object handling all protocol-level interaction int port = 5900; // The port to connect to on remote host (5900 is default) bool passwordPending = false; // After Connect() is called, a password might be required. bool fullScreenRefresh = false; // Whether or not to request the entire remote screen be sent. VncDesktopTransformPolicy desktopPolicy; RuntimeState state = RuntimeState.Disconnected; private enum RuntimeState { Disconnected, Disconnecting, Connected, Connecting } public RemoteDesktop() : base() { // Since this control will be updated constantly, and all graphics will be drawn by this class, // set the control's painting for best user-drawn performance. SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer | ControlStyles.Selectable | // BUG FIX (Edward Cooke) -- Adding Control.Select() support ControlStyles.ResizeRedraw | ControlStyles.Opaque, true); // Show a screenshot of a Windows desktop from the manifest and cache to be used when painting in design mode //designModeDesktop = Image.FromStream(Assembly.GetAssembly(GetType()).GetManifestResourceStream("VncSharp.Resources.screenshot.png")); // Use a simple desktop policy for design mode. This will be replaced in Connect() desktopPolicy = new VncDesignModeDesktopPolicy(this); AutoScroll = desktopPolicy.AutoScroll; AutoScrollMinSize = desktopPolicy.AutoScrollMinSize; // Users of the control can choose to use their own Authentication GetPassword() method via the delegate above. This is a default only. //GetPassword = new AuthenticateDelegate(PasswordDialog.GetPassword); } [DefaultValue(5900)] [Description("The port number used by the VNC Host (typically 5900)")] /// <summary> /// The port number used by the VNC Host (typically 5900). /// </summary> public int VncPort { get { return port; } set { // Ignore attempts to use invalid port numbers if (value < 1 | value > 65535) value = 5900; port = value; } } /// <summary> /// True if the RemoteDesktop is connected and authenticated (if necessary) with a remote VNC Host; otherwise False. /// </summary> public bool IsConnected { get { return state == RuntimeState.Connected; } } // This is a hack to get around the issue of DesignMode returning // false when the control is being removed from a form at design time. // First check to see if the control is in DesignMode, then work up // to also check any parent controls. DesignMode returns False sometimes // when it is really True for the parent. Thanks to Claes Bergefall for the idea. protected new bool DesignMode { get { if (base.DesignMode) { return true; } else { Control parent = Parent; while (parent != null) { if (parent.Site != null && parent.Site.DesignMode) { return true; } parent = parent.Parent; } return false; } } } /// <summary> /// Returns a more appropriate default size for initial drawing of the control at design time /// </summary> protected override Size DefaultSize { get { return new Size(400, 200); } } [Description("The name of the remote desktop.")] /// <summary> /// The name of the remote desktop, or "Disconnected" if not connected. /// </summary> public string Hostname { get { return vnc == null ? "Disconnected" : vnc.HostName; } } /// <summary> /// The image of the remote desktop. /// </summary> public Image Desktop { get { return desktop; } } /// <summary> /// Get a complete update of the entire screen from the remote host. /// </summary> /// <remarks>You should allow users to call FullScreenUpdate in order to correct /// corruption of the local image. This will simply request that the next update be /// for the full screen, and not a portion of it. It will not do the update while /// blocking. /// </remarks> /// <exception cref="System.InvalidOperationException">Thrown if the RemoteDesktop control is not in the Connected state. See <see cref="Nixxis.RfbClient.RemoteDesktop.IsConnected" />.</exception> public void FullScreenUpdate() { InsureConnection(true); fullScreenRefresh = true; } /// <summary> /// Insures the state of the connection to the server, either Connected or Not Connected depending on the value of the connected argument. /// </summary> /// <param name="connected">True if the connection must be established, otherwise False.</param> /// <exception cref="System.InvalidOperationException">Thrown if the RemoteDesktop control is in the wrong state.</exception> private void InsureConnection(bool connected) { // Grab the name of the calling routine: string methodName = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().Name; if (connected) { System.Diagnostics.Debug.Assert(state == RuntimeState.Connected || state == RuntimeState.Disconnecting, // special case for Disconnect() string.Format("RemoteDesktop must be in RuntimeState.Connected before calling {0}.", methodName)); if (state != RuntimeState.Connected && state != RuntimeState.Disconnecting) { throw new InvalidOperationException("RemoteDesktop must be in Connected state before calling methods that require an established connection."); } } else { // disconnected System.Diagnostics.Debug.Assert(state == RuntimeState.Disconnected, string.Format("RemoteDesktop must be in RuntimeState.Disconnected before calling {0}.", methodName)); if (state != RuntimeState.Disconnected && state != RuntimeState.Disconnecting) { throw new InvalidOperationException("RemoteDesktop cannot be in Connected state when calling methods that establish a connection."); } } } // This event handler deals with Frambebuffer Updates coming from the host. An // EncodedRectangle object is passed via the VncEventArgs (actually an IDesktopUpdater // object so that *only* Draw() can be called here--Decode() is done elsewhere). // The VncClient object handles thread marshalling onto the UI thread. protected void VncUpdate(object sender, VncEventArgs e) { e.DesktopUpdater.Draw(desktop); Invalidate(desktopPolicy.AdjustUpdateRectangle(e.DesktopUpdater.UpdateRectangle)); if (state == RuntimeState.Connected) { vnc.RequestScreenUpdate(fullScreenRefresh); // Make sure the next screen update is incremental fullScreenRefresh = false; } } /// <summary> /// Connect to a VNC Host and determine whether or not the server requires a password. /// </summary> /// <param name="host">The IP Address or Host Name of the VNC Host.</param> /// <exception cref="System.ArgumentNullException">Thrown if host is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown if display is negative.</exception> /// <exception cref="System.InvalidOperationException">Thrown if the RemoteDesktop control is already Connected. See <see cref="Nixxis.RfbClient.RemoteDesktop.IsConnected" />.</exception> public void Connect(string host) { // Use Display 0 by default. Connect(host, 0); } /// <summary> /// Connect to a VNC Host and determine whether or not the server requires a password. /// </summary> /// <param name="host">The IP Address or Host Name of the VNC Host.</param> /// <param name="viewOnly">Determines whether mouse and keyboard events will be sent to the host.</param> /// <exception cref="System.ArgumentNullException">Thrown if host is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown if display is negative.</exception> /// <exception cref="System.InvalidOperationException">Thrown if the RemoteDesktop control is already Connected. See <see cref="Nixxis.RfbClient.RemoteDesktop.IsConnected" />.</exception> public void Connect(string host, bool viewOnly) { // Use Display 0 by default. Connect(host, 0, viewOnly); } /// <summary> /// Connect to a VNC Host and determine whether or not the server requires a password. /// </summary> /// <param name="host">The IP Address or Host Name of the VNC Host.</param> /// <param name="viewOnly">Determines whether mouse and keyboard events will be sent to the host.</param> /// <param name="scaled">Determines whether to use desktop scaling or leave it normal and clip.</param> /// <exception cref="System.ArgumentNullException">Thrown if host is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown if display is negative.</exception> /// <exception cref="System.InvalidOperationException">Thrown if the RemoteDesktop control is already Connected. See <see cref="Nixxis.RfbClient.RemoteDesktop.IsConnected" />.</exception> public void Connect(string host, bool viewOnly, bool scaled) { // Use Display 0 by default. Connect(host, 0, viewOnly, scaled); } /// <summary> /// Connect to a VNC Host and determine whether or not the server requires a password. /// </summary> /// <param name="host">The IP Address or Host Name of the VNC Host.</param> /// <param name="display">The Display number (used on Unix hosts).</param> /// <exception cref="System.ArgumentNullException">Thrown if host is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown if display is negative.</exception> /// <exception cref="System.InvalidOperationException">Thrown if the RemoteDesktop control is already Connected. See <see cref="Nixxis.RfbClient.RemoteDesktop.IsConnected" />.</exception> public void Connect(string host, int display) { Connect(host, display, false); } /// <summary> /// Connect to a VNC Host and determine whether or not the server requires a password. /// </summary> /// <param name="host">The IP Address or Host Name of the VNC Host.</param> /// <param name="display">The Display number (used on Unix hosts).</param> /// <param name="viewOnly">Determines whether mouse and keyboard events will be sent to the host.</param> /// <exception cref="System.ArgumentNullException">Thrown if host is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown if display is negative.</exception> /// <exception cref="System.InvalidOperationException">Thrown if the RemoteDesktop control is already Connected. See <see cref="Nixxis.RfbClient.RemoteDesktop.IsConnected" />.</exception> public void Connect(string host, int display, bool viewOnly) { Connect(host, display, viewOnly, false); } /// <summary> /// Connect to a VNC Host and determine whether or not the server requires a password. /// </summary> /// <param name="host">The IP Address or Host Name of the VNC Host.</param> /// <param name="display">The Display number (used on Unix hosts).</param> /// <param name="viewOnly">Determines whether mouse and keyboard events will be sent to the host.</param> /// <param name="scaled">Determines whether to use desktop scaling or leave it normal and clip.</param> /// <exception cref="System.ArgumentNullException">Thrown if host is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown if display is negative.</exception> /// <exception cref="System.InvalidOperationException">Thrown if the RemoteDesktop control is already Connected. See <see cref="Nixxis.RfbClient.RemoteDesktop.IsConnected" />.</exception> public void Connect(string host, int display, bool viewOnly, bool scaled) { // TODO: Should this be done asynchronously so as not to block the UI? Since an event // indicates the end of the connection, maybe that would be a better design. InsureConnection(false); if (host == null) throw new ArgumentNullException("host"); if (display < 0) throw new ArgumentOutOfRangeException("display", display, "Display number must be a positive integer."); // Start protocol-level handling and determine whether a password is needed vnc = new VncClient(); vnc.ConnectionLost += new EventHandler(VncClientConnectionLost); vnc.ServerCutText += new EventHandler(VncServerCutText); passwordPending = vnc.Connect(host, display, VncPort, viewOnly); SetScalingMode(scaled); if (passwordPending) { // Server needs a password, so call which ever method is refered to by the GetPassword delegate. string password = GetPassword(); if (password == null) { // No password could be obtained (e.g., user clicked Cancel), so stop connecting return; } else { Authenticate(password); } } else { // No password needed, so go ahead and Initialize here Initialize(); } } /// <summary> /// Authenticate with the VNC Host using a user supplied password. /// </summary> /// <exception cref="System.InvalidOperationException">Thrown if the RemoteDesktop control is already Connected. See <see cref="Nixxis.RfbClient.RemoteDesktop.IsConnected" />.</exception> /// <exception cref="System.NullReferenceException">Thrown if the password is null.</exception> /// <param name="password">The user's password.</param> public void Authenticate(string password) { InsureConnection(false); if (!passwordPending) throw new InvalidOperationException("Authentication is only required when Connect() returns True and the VNC Host requires a password."); if (password == null) throw new NullReferenceException("password"); passwordPending = false; // repeated calls to Authenticate should fail. if (vnc.Authenticate(password)) { Initialize(); } else { OnConnectionLost(); } } /// <summary> /// Set the remote desktop's scaling mode. /// </summary> /// <param name="scaled">Determines whether to use desktop scaling or leave it normal and clip.</param> public void SetScalingMode(bool scaled) { if (scaled) { desktopPolicy = new VncScaledDesktopPolicy(vnc, this); } else { desktopPolicy = new VncClippedDesktopPolicy(vnc, this); } AutoScroll = desktopPolicy.AutoScroll; AutoScrollMinSize = desktopPolicy.AutoScrollMinSize; Invalidate(); } /// <summary> /// After protocol-level initialization and connecting is complete, the local GUI objects have to be set-up, and requests for updates to the remote host begun. /// </summary> /// <exception cref="System.InvalidOperationException">Thrown if the RemoteDesktop control is already in the Connected state. See <see cref="Nixxis.RfbClient.RemoteDesktop.IsConnected" />.</exception> protected void Initialize() { // Finish protocol handshake with host now that authentication is done. InsureConnection(false); vnc.Initialize(); SetState(RuntimeState.Connected); // Create a buffer on which updated rectangles will be drawn and draw a "please wait..." // message on the buffer for initial display until we start getting rectangles SetupDesktop(); // Tell the user of this control the necessary info about the desktop in order to setup the display OnConnectComplete(new ConnectEventArgs(vnc.Framebuffer.Width, vnc.Framebuffer.Height, vnc.Framebuffer.DesktopName)); // Refresh scroll properties AutoScrollMinSize = desktopPolicy.AutoScrollMinSize; // Start getting updates from the remote host (vnc.StartUpdates will begin a worker thread). vnc.VncUpdate += new VncUpdateHandler(VncUpdate); vnc.StartUpdates(); } private void SetState(RuntimeState newState) { state = newState; // Set mouse pointer according to new state return; switch (state) { case RuntimeState.Connected: // Change the cursor to the "vnc" custor--a see-through dot Cursor = new Cursor(GetType(), "Resources.vnccursor.cur"); break; // All other states should use the normal cursor. case RuntimeState.Disconnected: default: Cursor = Cursors.Default; break; } } /// <summary> /// Creates and initially sets-up the local bitmap that will represent the remote desktop image. /// </summary> /// <exception cref="System.InvalidOperationException">Thrown if the RemoteDesktop control is not already in the Connected state. See <see cref="Nixxis.RfbClient.RemoteDesktop.IsConnected" />.</exception> protected void SetupDesktop() { InsureConnection(true); // Create a new bitmap to cache locally the remote desktop image. Use the geometry of the // remote framebuffer, and 32bpp pixel format (doesn't matter what the server is sending--8,16, // or 32--we always draw 32bpp here for efficiency). desktop = new Bitmap(vnc.Framebuffer.Width, vnc.Framebuffer.Height, PixelFormat.Format32bppPArgb); // Draw a "please wait..." message on the local desktop until the first // rectangle(s) arrive and overwrite with the desktop image. DrawDesktopMessage("Connecting to VNC host, please wait..."); } /// <summary> /// Draws the given message (white text) on the local desktop (all black). /// </summary> /// <param name="message">The message to be drawn.</param> protected void DrawDesktopMessage(string message) { System.Diagnostics.Debug.Assert(desktop != null, "Can't draw on desktop when null."); // Draw the given message on the local desktop using (Graphics g = Graphics.FromImage(desktop)) { g.FillRectangle(Brushes.Black, vnc.Framebuffer.Rectangle); StringFormat format = new StringFormat(); format.Alignment = StringAlignment.Center; format.LineAlignment = StringAlignment.Center; g.DrawString(message, new Font("Arial", 12), new SolidBrush(Color.White), new PointF(vnc.Framebuffer.Width / 2, vnc.Framebuffer.Height / 2), format); } } /// <summary> /// Stops the remote host from sending further updates and disconnects. /// </summary> /// <exception cref="System.InvalidOperationException">Thrown if the RemoteDesktop control is not already in the Connected state. See <see cref="Nixxis.RfbClient.RemoteDesktop.IsConnected" />.</exception> public void Disconnect() { InsureConnection(true); vnc.ConnectionLost -= new EventHandler(VncClientConnectionLost); vnc.ServerCutText -= new EventHandler(VncServerCutText); vnc.Disconnect(); SetState(RuntimeState.Disconnected); OnConnectionLost(); Invalidate(); } protected override void Dispose(bool disposing) { if (disposing) { // Make sure the connection is closed--should never happen :) if (state != RuntimeState.Disconnected) { Disconnect(); } // See if either of the bitmaps used need clean-up. if (desktop != null) desktop.Dispose(); if (designModeDesktop != null) designModeDesktop.Dispose(); } base.Dispose(disposing); } protected override void OnPaint(PaintEventArgs pe) { // If the control is in design mode, draw a nice background, otherwise paint the desktop. if (!DesignMode) { switch(state) { case RuntimeState.Connected: System.Diagnostics.Debug.Assert(desktop != null); DrawDesktopImage(desktop, pe.Graphics); break; case RuntimeState.Disconnecting: case RuntimeState.Connecting: case RuntimeState.Disconnected: // Do nothing, just black background. break; default: // Sanity check throw new NotImplementedException(string.Format("RemoteDesktop in unknown State: {0}.", state.ToString())); } } else { // Draw a static screenshot of a Windows desktop to simulate the control in action System.Diagnostics.Debug.Assert(designModeDesktop != null); DrawDesktopImage(designModeDesktop, pe.Graphics); } base.OnPaint(pe); } protected override void OnResize(EventArgs eventargs) { // Fix a bug with a ghost scrollbar in clipped mode on maximize Control parent = Parent; while (parent != null) { if (parent is Form) { Form form = parent as Form; if (form.WindowState == FormWindowState.Maximized) form.Invalidate(); parent = null; } else { parent = parent.Parent; } } base.OnResize(eventargs); } /// <summary> /// Draws an image onto the control in a size-aware way. /// </summary> /// <param name="desktopImage">The desktop image to be drawn to the control's sufrace.</param> /// <param name="g">The Graphics object representing the control's drawable surface.</param> /// <exception cref="System.InvalidOperationException">Thrown if the RemoteDesktop control is not already in the Connected state.</exception> protected void DrawDesktopImage(Image desktopImage, Graphics g) { g.DrawImage(desktopImage, desktopPolicy.RepositionImage(desktopImage)); } /// <summary> /// RemoteDesktop listens for ConnectionLost events from the VncClient object. /// </summary> /// <param name="sender">The VncClient object that raised the event.</param> /// <param name="e">An empty EventArgs object.</param> protected void VncClientConnectionLost(object sender, EventArgs e) { // If the remote host dies, and there are attempts to write // keyboard/mouse/update notifications, this may get called // many times, and from main or worker thread. // Guard against this and invoke Disconnect once. if (state == RuntimeState.Connected) { SetState(RuntimeState.Disconnecting); Disconnect(); } } // Handle the VncClient ServerCutText event and bubble it up as ClipboardChanged. protected void VncServerCutText(object sender, EventArgs e) { OnClipboardChanged(); } protected void OnClipboardChanged() { if (ClipboardChanged != null) ClipboardChanged(this, EventArgs.Empty); } /// <summary> /// Dispatches the ConnectionLost event if any targets have registered. /// </summary> /// <param name="e">An EventArgs object.</param> /// <exception cref="System.InvalidOperationException">Thrown if the RemoteDesktop control is in the Connected state.</exception> protected void OnConnectionLost() { if (ConnectionLost != null) { ConnectionLost(this, EventArgs.Empty); } } /// <summary> /// Dispatches the ConnectComplete event if any targets have registered. /// </summary> /// <param name="e">A ConnectEventArgs object with information about the remote framebuffer's geometry.</param> /// <exception cref="System.InvalidOperationException">Thrown if the RemoteDesktop control is not in the Connected state.</exception> protected void OnConnectComplete(ConnectEventArgs e) { if (ConnectComplete != null) { ConnectComplete(this, e); } } // Handle Keyboard Events: ------------------------------------------- // These keys don't normally throw an OnKeyDown event. Returning true here fixes this. protected override bool IsInputKey(Keys keyData) { switch (keyData) { case Keys.Tab: case Keys.Up: case Keys.Down: case Keys.Left: case Keys.Right: case Keys.Shift: case Keys.RWin: case Keys.LWin: return true; default: return base.IsInputKey(keyData); } } } }
// <copyright file="GPGSUtil.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // Keep this even if NO_GPGS is defined so we can clean up the project // post build. #if (UNITY_ANDROID || UNITY_IPHONE) namespace GooglePlayGames.Editor { using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Xml; using UnityEditor; using UnityEngine; /// <summary> /// Utility class to perform various tasks in the editor. /// </summary> public static class GPGSUtil { /// <summary>Property key for project requiring G+ access public const string REQUIREGOOGLEPLUSKEY = "proj.requireGPlus"; /// <summary>Property key for project settings.</summary> public const string SERVICEIDKEY = "App.NearbdServiceId"; /// <summary>Property key for project settings.</summary> public const string APPIDKEY = "proj.AppId"; /// <summary>Property key for project settings.</summary> public const string CLASSDIRECTORYKEY = "proj.classDir"; /// <summary>Property key for project settings.</summary> public const string CLASSNAMEKEY = "proj.ConstantsClassName"; /// <summary>Property key for project settings.</summary> public const string WEBCLIENTIDKEY = "and.ClientId"; /// <summary>Property key for project settings.</summary> public const string IOSCLIENTIDKEY = "ios.ClientId"; /// <summary>Property key for project settings.</summary> public const string IOSBUNDLEIDKEY = "ios.BundleId"; /// <summary>Property key for project settings.</summary> public const string ANDROIDRESOURCEKEY = "and.ResourceData"; /// <summary>Property key for project settings.</summary> public const string ANDROIDSETUPDONEKEY = "android.SetupDone"; /// <summary>Property key for project settings.</summary> public const string ANDROIDBUNDLEIDKEY = "and.BundleId"; /// <summary>Property key for project settings.</summary> public const string IOSRESOURCEKEY = "ios.ResourceData"; /// <summary>Property key for project settings.</summary> public const string IOSSETUPDONEKEY = "ios.SetupDone"; /// <summary>Property key for plugin version.</summary> public const string PLUGINVERSIONKEY = "proj.pluginVersion"; /// <summary>Property key for nearby settings done.</summary> public const string NEARBYSETUPDONEKEY = "android.NearbySetupDone"; /// <summary>Property key for project settings.</summary> public const string LASTUPGRADEKEY = "lastUpgrade"; /// <summary>Constant for token replacement</summary> private const string SERVICEIDPLACEHOLDER = "__NEARBY_SERVICE_ID__"; /// <summary>Constant for token replacement</summary> private const string APPIDPLACEHOLDER = "__APP_ID__"; /// <summary>Constant for token replacement</summary> private const string CLASSNAMEPLACEHOLDER = "__Class__"; /// <summary>Constant for token replacement</summary> private const string WEBCLIENTIDPLACEHOLDER = "__WEB_CLIENTID__"; /// <summary>Constant for token replacement</summary> private const string IOSCLIENTIDPLACEHOLDER = "__IOS_CLIENTID__"; /// <summary>Constant for token replacement</summary> private const string IOSBUNDLEIDPLACEHOLDER = "__BUNDLEID__"; /// <summary>Constant for token replacement</summary> private const string PLUGINVERSIONPLACEHOLDER = "__PLUGIN_VERSION__"; /// <summary>Constant for token replacement</summary> private const string TOKENPERMISSIONSHOLDER = "__TOKEN_PERMISSIONS__"; /// <summary>Constant for require google plus token replacement</summary> private const string REQUIREGOOGLEPLUSPLACEHOLDER = "__REQUIRE_GOOGLE_PLUS__"; /// <summary>Property key for project settings.</summary> private const string TOKENPERMISSIONKEY = "proj.tokenPermissions"; /// <summary>Constant for token replacement</summary> private const string NAMESPACESTARTPLACEHOLDER = "__NameSpaceStart__"; /// <summary>Constant for token replacement</summary> private const string NAMESPACEENDPLACEHOLDER = "__NameSpaceEnd__"; /// <summary>Constant for token replacement</summary> private const string CONSTANTSPLACEHOLDER = "__Constant_Properties__"; /// <summary> /// The game info file path. This is a generated file. /// </summary> private const string GameInfoPath = "Assets/GooglePlayGames/GameInfo.cs"; /// <summary> /// The token permissions to add if needed. /// </summary> private const string TokenPermissions = "<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>\n" + "<uses-permission android:name=\"android.permission.USE_CREDENTIALS\"/>"; /// <summary> /// The map of replacements for filling in code templates. The /// key is the string that appears in the template as a placeholder, /// the value is the key into the GPGSProjectSettings. /// </summary> private static Dictionary<string, string> replacements = new Dictionary<string, string>() { { SERVICEIDPLACEHOLDER, SERVICEIDKEY }, { APPIDPLACEHOLDER, APPIDKEY }, { CLASSNAMEPLACEHOLDER, CLASSNAMEKEY }, { WEBCLIENTIDPLACEHOLDER, WEBCLIENTIDKEY }, { IOSCLIENTIDPLACEHOLDER, IOSCLIENTIDKEY }, { IOSBUNDLEIDPLACEHOLDER, IOSBUNDLEIDKEY }, { TOKENPERMISSIONSHOLDER, TOKENPERMISSIONKEY }, { REQUIREGOOGLEPLUSPLACEHOLDER, REQUIREGOOGLEPLUSKEY }, { PLUGINVERSIONPLACEHOLDER, PLUGINVERSIONKEY} }; /// <summary> /// Replaces / in file path to be the os specific separator. /// </summary> /// <returns>The path.</returns> /// <param name="path">Path with correct separators.</param> public static string SlashesToPlatformSeparator(string path) { return path.Replace("/", System.IO.Path.DirectorySeparatorChar.ToString()); } /// <summary> /// Reads the file. /// </summary> /// <returns>The file contents. The slashes are corrected.</returns> /// <param name="filePath">File path.</param> public static string ReadFile(string filePath) { filePath = SlashesToPlatformSeparator(filePath); if (!File.Exists(filePath)) { Alert("Plugin error: file not found: " + filePath); return null; } StreamReader sr = new StreamReader(filePath); string body = sr.ReadToEnd(); sr.Close(); return body; } /// <summary> /// Reads the editor template. /// </summary> /// <returns>The editor template contents.</returns> /// <param name="name">Name of the template in the editor directory.</param> public static string ReadEditorTemplate(string name) { return ReadFile(SlashesToPlatformSeparator("Assets/GooglePlayGames/Editor/" + name + ".txt")); } /// <summary> /// Writes the file. /// </summary> /// <param name="file">File path - the slashes will be corrected.</param> /// <param name="body">Body of the file to write.</param> public static void WriteFile(string file, string body) { file = SlashesToPlatformSeparator(file); using (var wr = new StreamWriter(file, false)) { wr.Write(body); } } /// <summary> /// Validates the string to be a valid nearby service id. /// </summary> /// <returns><c>true</c>, if like valid service identifier was looksed, <c>false</c> otherwise.</returns> /// <param name="s">string to test.</param> public static bool LooksLikeValidServiceId(string s) { if (s.Length < 3) { return false; } foreach (char c in s) { if (!char.IsLetterOrDigit(c) && c != '.') { return false; } } return true; } /// <summary> /// Looks the like valid app identifier. /// </summary> /// <returns><c>true</c>, if valid app identifier, <c>false</c> otherwise.</returns> /// <param name="s">the string to test.</param> public static bool LooksLikeValidAppId(string s) { if (s.Length < 5) { return false; } foreach (char c in s) { if (c < '0' || c > '9') { return false; } } return true; } /// <summary> /// Looks the like valid client identifier. /// </summary> /// <returns><c>true</c>, if valid client identifier, <c>false</c> otherwise.</returns> /// <param name="s">the string to test.</param> public static bool LooksLikeValidClientId(string s) { return s.EndsWith(".googleusercontent.com"); } /// <summary> /// Looks the like a valid bundle identifier. /// </summary> /// <returns><c>true</c>, if valid bundle identifier, <c>false</c> otherwise.</returns> /// <param name="s">the string to test.</param> public static bool LooksLikeValidBundleId(string s) { return s.Length > 3; } /// <summary> /// Looks like a valid package. /// </summary> /// <returns><c>true</c>, if valid package name, <c>false</c> otherwise.</returns> /// <param name="s">the string to test.</param> public static bool LooksLikeValidPackageName(string s) { if (string.IsNullOrEmpty(s)) { throw new Exception("cannot be empty"); } string[] parts = s.Split(new char[] { '.' }); foreach (string p in parts) { char[] bytes = p.ToCharArray(); for (int i = 0; i < bytes.Length; i++) { if (i == 0 && !char.IsLetter(bytes[i])) { throw new Exception("each part must start with a letter"); } else if (char.IsWhiteSpace(bytes[i])) { throw new Exception("cannot contain spaces"); } else if (!char.IsLetterOrDigit(bytes[i]) && bytes[i] != '_') { throw new Exception("must be alphanumeric or _"); } } } return parts.Length >= 1; } /// <summary> /// Determines if is setup done. /// </summary> /// <returns><c>true</c> if is setup done; otherwise, <c>false</c>.</returns> public static bool IsSetupDone() { bool doneSetup = true; #if UNITY_ANDROID doneSetup = GPGSProjectSettings.Instance.GetBool(ANDROIDSETUPDONEKEY, false); // check gameinfo if (File.Exists(GameInfoPath)) { string contents = ReadFile(GameInfoPath); if (contents.Contains(APPIDPLACEHOLDER)) { Debug.Log("GameInfo not initialized with AppId. " + "Run Window > Google Play Games > Setup > Android Setup..."); return false; } } else { Debug.Log("GameInfo.cs does not exist. Run Window > Google Play Games > Setup > Android Setup..."); return false; } #elif (UNITY_IPHONE && !NO_GPGS) doneSetup = GPGSProjectSettings.Instance.GetBool(IOSSETUPDONEKEY, false); // check gameinfo if (File.Exists(GameInfoPath)) { string contents = ReadFile(GameInfoPath); if (contents.Contains(IOSCLIENTIDPLACEHOLDER)) { Debug.Log("GameInfo not initialized with Client Id. " + "Run Window > Google Play Games > Setup > iOS Setup..."); return false; } } else { Debug.Log("GameInfo.cs does not exist. Run Window > Google Play Games > Setup > iOS Setup..."); return false; } #endif return doneSetup; } /// <summary> /// Makes legal identifier from string. /// Returns a legal C# identifier from the given string. The transformations are: /// - spaces => underscore _ /// - punctuation => empty string /// - leading numbers are prefixed with underscore. /// </summary> /// <returns>the id</returns> /// <param name="key">Key to convert to an identifier.</param> public static string MakeIdentifier(string key) { string s; string retval = string.Empty; if (string.IsNullOrEmpty(key)) { return "_"; } s = key.Trim().Replace(' ', '_'); foreach (char c in s) { if (char.IsLetterOrDigit(c) || c == '_') { retval += c; } } return retval; } /// <summary> /// Displays an error dialog. /// </summary> /// <param name="s">the message</param> public static void Alert(string s) { Alert(GPGSStrings.Error, s); } /// <summary> /// Displays a dialog with the given title and message. /// </summary> /// <param name="title">the title.</param> /// <param name="message">the message.</param> public static void Alert(string title, string message) { EditorUtility.DisplayDialog(title, message, GPGSStrings.Ok); } /// <summary> /// Gets the android sdk path. /// </summary> /// <returns>The android sdk path.</returns> public static string GetAndroidSdkPath() { string sdkPath = EditorPrefs.GetString("AndroidSdkRoot"); if (sdkPath != null && (sdkPath.EndsWith("/") || sdkPath.EndsWith("\\"))) { sdkPath = sdkPath.Substring(0, sdkPath.Length - 1); } return sdkPath; } /// <summary> /// Determines if the android sdk exists. /// </summary> /// <returns><c>true</c> if android sdk exists; otherwise, <c>false</c>.</returns> public static bool HasAndroidSdk() { string sdkPath = GetAndroidSdkPath(); return sdkPath != null && sdkPath.Trim() != string.Empty && System.IO.Directory.Exists(sdkPath); } /// <summary> /// Gets the unity major version. /// </summary> /// <returns>The unity major version.</returns> public static int GetUnityMajorVersion() { #if UNITY_5 string majorVersion = Application.unityVersion.Split('.')[0]; int ver; if (!int.TryParse(majorVersion, out ver)) { ver = 0; } return ver; #elif UNITY_4_6 return 4; #else return 0; #endif } /// <summary> /// Checks for the android manifest file exsistance. /// </summary> /// <returns><c>true</c>, if the file exists <c>false</c> otherwise.</returns> public static bool AndroidManifestExists() { string destFilename = GPGSUtil.SlashesToPlatformSeparator( "Assets/Plugins/Android/MainLibProj/AndroidManifest.xml"); return File.Exists(destFilename); } /// <summary> /// Generates the android manifest. /// </summary> /// <param name="needTokenPermissions">If set to <c>true</c> need token permissions.</param> public static void GenerateAndroidManifest(bool needTokenPermissions) { string destFilename = GPGSUtil.SlashesToPlatformSeparator( "Assets/Plugins/Android/MainLibProj/AndroidManifest.xml"); // Generate AndroidManifest.xml string manifestBody = GPGSUtil.ReadEditorTemplate("template-AndroidManifest"); Dictionary<string, string> overrideValues = new Dictionary<string, string>(); if (!needTokenPermissions) { overrideValues[TOKENPERMISSIONKEY] = string.Empty; overrideValues[WEBCLIENTIDPLACEHOLDER] = string.Empty; } else { overrideValues[TOKENPERMISSIONKEY] = TokenPermissions; } foreach (KeyValuePair<string, string> ent in replacements) { string value = GPGSProjectSettings.Instance.Get(ent.Value, overrideValues); manifestBody = manifestBody.Replace(ent.Key, value); } GPGSUtil.WriteFile(destFilename, manifestBody); GPGSUtil.UpdateGameInfo(); } /// <summary> /// Writes the resource identifiers file. This file contains the /// resource ids copied (downloaded?) from the play game app console. /// </summary> /// <param name="classDirectory">Class directory.</param> /// <param name="className">Class name.</param> /// <param name="resourceKeys">Resource keys.</param> public static void WriteResourceIds(string classDirectory, string className, Hashtable resourceKeys) { string constantsValues = string.Empty; string[] parts = className.Split('.'); string dirName = classDirectory; if (string.IsNullOrEmpty(dirName)) { dirName = "Assets"; } string nameSpace = string.Empty; for (int i = 0; i < parts.Length - 1; i++) { dirName += "/" + parts[i]; if (nameSpace != string.Empty) { nameSpace += "."; } nameSpace += parts[i]; } EnsureDirExists(dirName); foreach (DictionaryEntry ent in resourceKeys) { string key = MakeIdentifier((string)ent.Key); constantsValues += " public const string " + key + " = \"" + ent.Value + "\"; // <GPGSID>\n"; } string fileBody = GPGSUtil.ReadEditorTemplate("template-Constants"); if (nameSpace != string.Empty) { fileBody = fileBody.Replace( NAMESPACESTARTPLACEHOLDER, "namespace " + nameSpace + "\n{"); } else { fileBody = fileBody.Replace(NAMESPACESTARTPLACEHOLDER, string.Empty); } fileBody = fileBody.Replace(CLASSNAMEPLACEHOLDER, parts[parts.Length - 1]); fileBody = fileBody.Replace(CONSTANTSPLACEHOLDER, constantsValues); if (nameSpace != string.Empty) { fileBody = fileBody.Replace( NAMESPACEENDPLACEHOLDER, "}"); } else { fileBody = fileBody.Replace(NAMESPACEENDPLACEHOLDER, string.Empty); } WriteFile(Path.Combine(dirName, parts[parts.Length - 1] + ".cs"), fileBody); } /// <summary> /// Updates the game info file. This is a generated file containing the /// app and client ids. /// </summary> public static void UpdateGameInfo() { string fileBody = GPGSUtil.ReadEditorTemplate("template-GameInfo"); foreach (KeyValuePair<string, string> ent in replacements) { string value = GPGSProjectSettings.Instance.Get(ent.Value); fileBody = fileBody.Replace(ent.Key, value); } GPGSUtil.WriteFile(GameInfoPath, fileBody); } /// <summary> /// Ensures the dir exists. /// </summary> /// <param name="dir">Directory to check.</param> public static void EnsureDirExists(string dir) { dir = SlashesToPlatformSeparator(dir); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } } /// <summary> /// Deletes the dir if exists. /// </summary> /// <param name="dir">Directory to delete.</param> public static void DeleteDirIfExists(string dir) { dir = SlashesToPlatformSeparator(dir); if (Directory.Exists(dir)) { Directory.Delete(dir, true); } } /// <summary> /// Gets the Google Play Services library version. This is only /// needed for Unity versions less than 5. /// </summary> /// <returns>The GPS version.</returns> /// <param name="libProjPath">Lib proj path.</param> private static int GetGPSVersion(string libProjPath) { string versionFile = libProjPath + "/res/values/version.xml"; XmlTextReader reader = new XmlTextReader(new StreamReader(versionFile)); bool inResource = false; int version = -1; while (reader.Read()) { if (reader.Name == "resources") { inResource = true; } if (inResource && reader.Name == "integer") { if ("google_play_services_version".Equals( reader.GetAttribute("name"))) { reader.Read(); Debug.Log("Read version string: " + reader.Value); version = Convert.ToInt32(reader.Value); } } } reader.Close(); return version; } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Runtime.CompilerServices; using System.Text; namespace System.Numerics { /// <summary> /// A structure encapsulating two single precision floating point values and provides hardware accelerated methods. /// </summary> public partial struct Vector2 : IEquatable<Vector2>, IFormattable { #region Public Static Properties /// <summary> /// Returns the vector (0,0). /// </summary> public static Vector2 Zero { [Intrinsic] get { return new Vector2(); } } /// <summary> /// Returns the vector (1,1). /// </summary> public static Vector2 One { [Intrinsic] get { return new Vector2(1.0f, 1.0f); } } /// <summary> /// Returns the vector (1,0). /// </summary> public static Vector2 UnitX { get { return new Vector2(1.0f, 0.0f); } } /// <summary> /// Returns the vector (0,1). /// </summary> public static Vector2 UnitY { get { return new Vector2(0.0f, 1.0f); } } #endregion Public Static Properties #region Public instance methods /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>The hash code.</returns> public override readonly int GetHashCode() { return HashCode.Combine(this.X.GetHashCode(), this.Y.GetHashCode()); } /// <summary> /// Returns a boolean indicating whether the given Object is equal to this Vector2 instance. /// </summary> /// <param name="obj">The Object to compare against.</param> /// <returns>True if the Object is equal to this Vector2; False otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override readonly bool Equals(object? obj) { if (!(obj is Vector2)) return false; return Equals((Vector2)obj); } /// <summary> /// Returns a String representing this Vector2 instance. /// </summary> /// <returns>The string representation.</returns> public override readonly string ToString() { return ToString("G", CultureInfo.CurrentCulture); } /// <summary> /// Returns a String representing this Vector2 instance, using the specified format to format individual elements. /// </summary> /// <param name="format">The format of individual elements.</param> /// <returns>The string representation.</returns> public readonly string ToString(string? format) { return ToString(format, CultureInfo.CurrentCulture); } /// <summary> /// Returns a String representing this Vector2 instance, using the specified format to format individual elements /// and the given IFormatProvider. /// </summary> /// <param name="format">The format of individual elements.</param> /// <param name="formatProvider">The format provider to use when formatting elements.</param> /// <returns>The string representation.</returns> public readonly string ToString(string? format, IFormatProvider? formatProvider) { StringBuilder sb = new StringBuilder(); string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; sb.Append('<'); sb.Append(this.X.ToString(format, formatProvider)); sb.Append(separator); sb.Append(' '); sb.Append(this.Y.ToString(format, formatProvider)); sb.Append('>'); return sb.ToString(); } /// <summary> /// Returns the length of the vector. /// </summary> /// <returns>The vector's length.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly float Length() { if (Vector.IsHardwareAccelerated) { float ls = Vector2.Dot(this, this); return MathF.Sqrt(ls); } else { float ls = X * X + Y * Y; return MathF.Sqrt(ls); } } /// <summary> /// Returns the length of the vector squared. This operation is cheaper than Length(). /// </summary> /// <returns>The vector's length squared.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly float LengthSquared() { if (Vector.IsHardwareAccelerated) { return Vector2.Dot(this, this); } else { return X * X + Y * Y; } } #endregion Public Instance Methods #region Public Static Methods /// <summary> /// Returns the Euclidean distance between the two given points. /// </summary> /// <param name="value1">The first point.</param> /// <param name="value2">The second point.</param> /// <returns>The distance.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(Vector2 value1, Vector2 value2) { if (Vector.IsHardwareAccelerated) { Vector2 difference = value1 - value2; float ls = Vector2.Dot(difference, difference); return MathF.Sqrt(ls); } else { float dx = value1.X - value2.X; float dy = value1.Y - value2.Y; float ls = dx * dx + dy * dy; return MathF.Sqrt(ls); } } /// <summary> /// Returns the Euclidean distance squared between the two given points. /// </summary> /// <param name="value1">The first point.</param> /// <param name="value2">The second point.</param> /// <returns>The distance squared.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DistanceSquared(Vector2 value1, Vector2 value2) { if (Vector.IsHardwareAccelerated) { Vector2 difference = value1 - value2; return Vector2.Dot(difference, difference); } else { float dx = value1.X - value2.X; float dy = value1.Y - value2.Y; return dx * dx + dy * dy; } } /// <summary> /// Returns a vector with the same direction as the given vector, but with a length of 1. /// </summary> /// <param name="value">The vector to normalize.</param> /// <returns>The normalized vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Normalize(Vector2 value) { if (Vector.IsHardwareAccelerated) { float length = value.Length(); return value / length; } else { float ls = value.X * value.X + value.Y * value.Y; float invNorm = 1.0f / MathF.Sqrt(ls); return new Vector2( value.X * invNorm, value.Y * invNorm); } } /// <summary> /// Returns the reflection of a vector off a surface that has the specified normal. /// </summary> /// <param name="vector">The source vector.</param> /// <param name="normal">The normal of the surface being reflected off.</param> /// <returns>The reflected vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Reflect(Vector2 vector, Vector2 normal) { if (Vector.IsHardwareAccelerated) { float dot = Vector2.Dot(vector, normal); return vector - (2 * dot * normal); } else { float dot = vector.X * normal.X + vector.Y * normal.Y; return new Vector2( vector.X - 2.0f * dot * normal.X, vector.Y - 2.0f * dot * normal.Y); } } /// <summary> /// Restricts a vector between a min and max value. /// </summary> /// <param name="value1">The source vector.</param> /// <param name="min">The minimum value.</param> /// <param name="max">The maximum value.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Clamp(Vector2 value1, Vector2 min, Vector2 max) { // This compare order is very important!!! // We must follow HLSL behavior in the case user specified min value is bigger than max value. float x = value1.X; x = (min.X > x) ? min.X : x; // max(x, minx) x = (max.X < x) ? max.X : x; // min(x, maxx) float y = value1.Y; y = (min.Y > y) ? min.Y : y; // max(y, miny) y = (max.Y < y) ? max.Y : y; // min(y, maxy) return new Vector2(x, y); } /// <summary> /// Linearly interpolates between two vectors based on the given weighting. /// </summary> /// <param name="value1">The first source vector.</param> /// <param name="value2">The second source vector.</param> /// <param name="amount">Value between 0 and 1 indicating the weight of the second source vector.</param> /// <returns>The interpolated vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Lerp(Vector2 value1, Vector2 value2, float amount) { return new Vector2( value1.X + (value2.X - value1.X) * amount, value1.Y + (value2.Y - value1.Y) * amount); } /// <summary> /// Transforms a vector by the given matrix. /// </summary> /// <param name="position">The source vector.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Transform(Vector2 position, Matrix3x2 matrix) { return new Vector2( position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M31, position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M32); } /// <summary> /// Transforms a vector by the given matrix. /// </summary> /// <param name="position">The source vector.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Transform(Vector2 position, Matrix4x4 matrix) { return new Vector2( position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M41, position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M42); } /// <summary> /// Transforms a vector normal by the given matrix. /// </summary> /// <param name="normal">The source vector.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 TransformNormal(Vector2 normal, Matrix3x2 matrix) { return new Vector2( normal.X * matrix.M11 + normal.Y * matrix.M21, normal.X * matrix.M12 + normal.Y * matrix.M22); } /// <summary> /// Transforms a vector normal by the given matrix. /// </summary> /// <param name="normal">The source vector.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 TransformNormal(Vector2 normal, Matrix4x4 matrix) { return new Vector2( normal.X * matrix.M11 + normal.Y * matrix.M21, normal.X * matrix.M12 + normal.Y * matrix.M22); } /// <summary> /// Transforms a vector by the given Quaternion rotation value. /// </summary> /// <param name="value">The source vector to be rotated.</param> /// <param name="rotation">The rotation to apply.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Transform(Vector2 value, Quaternion rotation) { float x2 = rotation.X + rotation.X; float y2 = rotation.Y + rotation.Y; float z2 = rotation.Z + rotation.Z; float wz2 = rotation.W * z2; float xx2 = rotation.X * x2; float xy2 = rotation.X * y2; float yy2 = rotation.Y * y2; float zz2 = rotation.Z * z2; return new Vector2( value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2), value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2)); } #endregion Public Static Methods #region Public operator methods // all the below methods should be inlined as they are // implemented over JIT intrinsics /// <summary> /// Adds two vectors together. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The summed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Add(Vector2 left, Vector2 right) { return left + right; } /// <summary> /// Subtracts the second vector from the first. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The difference vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Subtract(Vector2 left, Vector2 right) { return left - right; } /// <summary> /// Multiplies two vectors together. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The product vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Multiply(Vector2 left, Vector2 right) { return left * right; } /// <summary> /// Multiplies a vector by the given scalar. /// </summary> /// <param name="left">The source vector.</param> /// <param name="right">The scalar value.</param> /// <returns>The scaled vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Multiply(Vector2 left, float right) { return left * right; } /// <summary> /// Multiplies a vector by the given scalar. /// </summary> /// <param name="left">The scalar value.</param> /// <param name="right">The source vector.</param> /// <returns>The scaled vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Multiply(float left, Vector2 right) { return left * right; } /// <summary> /// Divides the first vector by the second. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The vector resulting from the division.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Divide(Vector2 left, Vector2 right) { return left / right; } /// <summary> /// Divides the vector by the given scalar. /// </summary> /// <param name="left">The source vector.</param> /// <param name="divisor">The scalar value.</param> /// <returns>The result of the division.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Divide(Vector2 left, float divisor) { return left / divisor; } /// <summary> /// Negates a given vector. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The negated vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Negate(Vector2 value) { return -value; } #endregion Public operator methods } }
namespace BTPCArchiver { using System; using System.IO; using System.Text; using System.Drawing; using System.Resources; using System.Reflection; using System.Diagnostics; using System.Collections; using System.ComponentModel; using Microsoft.BizTalk.Message.Interop; using Microsoft.BizTalk.Component.Interop; using Microsoft.BizTalk.Component; using Microsoft.BizTalk.Messaging; [ComponentCategory(CategoryTypes.CATID_PipelineComponent)] [System.Runtime.InteropServices.Guid("c691e815-de36-4792-8015-50d2519ff346")] [ComponentCategory(CategoryTypes.CATID_Any)] public class Archiver : Microsoft.BizTalk.Component.Interop.IComponent, IBaseComponent, IPersistPropertyBag, IComponentUI { private System.Resources.ResourceManager resourceManager = new System.Resources.ResourceManager("BTPCArchiver.Archiver", Assembly.GetExecutingAssembly()); private string _PropertyName; public string PropertyName { get { return _PropertyName; } set { _PropertyName = value; } } private bool _Enabled; public bool Enabled { get { return _Enabled; } set { _Enabled = value; } } private string _FilenameExtension; public string FilenameExtension { get { return _FilenameExtension; } set { _FilenameExtension = value; } } private string _PropertyNS; public string PropertyNS { get { return _PropertyNS; } set { _PropertyNS = value; } } private string _Filepath; public string Filepath { get { return _Filepath; } set { _Filepath = value; } } private Guid _MessageID; public Guid MessageID { get { return _MessageID; } set { _MessageID = value; } } #region IBaseComponent members /// <summary> /// Name of the component /// </summary> [Browsable(false)] public string Name { get { return resourceManager.GetString("COMPONENTNAME", System.Globalization.CultureInfo.InvariantCulture); } } /// <summary> /// Version of the component /// </summary> [Browsable(false)] public string Version { get { return resourceManager.GetString("COMPONENTVERSION", System.Globalization.CultureInfo.InvariantCulture); } } /// <summary> /// Description of the component /// </summary> [Browsable(false)] public string Description { get { return resourceManager.GetString("COMPONENTDESCRIPTION", System.Globalization.CultureInfo.InvariantCulture); } } #endregion #region IPersistPropertyBag members /// <summary> /// Gets class ID of component for usage from unmanaged code. /// </summary> /// <param name="classid"> /// Class ID of the component /// </param> public void GetClassID(out System.Guid classid) { classid = new System.Guid("c691e815-de36-4792-8015-50d2519ff346"); } /// <summary> /// not implemented /// </summary> public void InitNew() { } /// <summary> /// Loads configuration properties for the component /// </summary> /// <param name="pb">Configuration property bag</param> /// <param name="errlog">Error status</param> public virtual void Load(Microsoft.BizTalk.Component.Interop.IPropertyBag pb, int errlog) { object val = null; val = this.ReadPropertyBag(pb, "PropertyName"); if ((val != null)) { this._PropertyName = ((string)(val)); } val = this.ReadPropertyBag(pb, "Enabled"); if ((val != null)) { this._Enabled = ((bool)(val)); } val = this.ReadPropertyBag(pb, "FilenameExtension"); if ((val != null)) { this._FilenameExtension = ((string)(val)); } val = this.ReadPropertyBag(pb, "PropertyNS"); if ((val != null)) { this._PropertyNS = ((string)(val)); } val = this.ReadPropertyBag(pb, "Filepath"); if ((val != null)) { this._Filepath = ((string)(val)); } } /// <summary> /// Saves the current component configuration into the property bag /// </summary> /// <param name="pb">Configuration property bag</param> /// <param name="fClearDirty">not used</param> /// <param name="fSaveAllProperties">not used</param> public virtual void Save(Microsoft.BizTalk.Component.Interop.IPropertyBag pb, bool fClearDirty, bool fSaveAllProperties) { this.WritePropertyBag(pb, "PropertyName", this.PropertyName); this.WritePropertyBag(pb, "Enabled", this.Enabled); this.WritePropertyBag(pb, "FilenameExtension", this.FilenameExtension); this.WritePropertyBag(pb, "PropertyNS", this.PropertyNS); this.WritePropertyBag(pb, "Filepath", this.Filepath); } #region utility functionality /// <summary> /// Reads property value from property bag /// </summary> /// <param name="pb">Property bag</param> /// <param name="propName">Name of property</param> /// <returns>Value of the property</returns> private object ReadPropertyBag(Microsoft.BizTalk.Component.Interop.IPropertyBag pb, string propName) { object val = null; try { pb.Read(propName, out val, 0); } catch (System.ArgumentException ) { return val; } catch (System.Exception e) { throw new System.ApplicationException(e.Message); } return val; } /// <summary> /// Writes property values into a property bag. /// </summary> /// <param name="pb">Property bag.</param> /// <param name="propName">Name of property.</param> /// <param name="val">Value of property.</param> private void WritePropertyBag(Microsoft.BizTalk.Component.Interop.IPropertyBag pb, string propName, object val) { try { pb.Write(propName, ref val); } catch (System.Exception e) { throw new System.ApplicationException(e.Message); } } #endregion #endregion #region IComponentUI members /// <summary> /// Component icon to use in BizTalk Editor /// </summary> [Browsable(false)] public IntPtr Icon { get { return ((System.Drawing.Bitmap)(this.resourceManager.GetObject("COMPONENTICON", System.Globalization.CultureInfo.InvariantCulture))).GetHicon(); } } /// <summary> /// The Validate method is called by the BizTalk Editor during the build /// of a BizTalk project. /// </summary> /// <param name="obj">An Object containing the configuration properties.</param> /// <returns>The IEnumerator enables the caller to enumerate through a collection of strings containing error messages. These error messages appear as compiler error messages. To report successful property validation, the method should return an empty enumerator.</returns> public System.Collections.IEnumerator Validate(object obj) { // example implementation: // ArrayList errorList = new ArrayList(); // errorList.Add("This is a compiler error"); // return errorList.GetEnumerator(); return null; } #endregion #region IComponent members public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { if (null == pc) throw new ArgumentNullException("PC is null"); if (null == inmsg) throw new ArgumentNullException("inmsg is null"); MessageID = inmsg.MessageID; ArchiverStream archiverStream = new ArchiverStream(inmsg.BodyPart.Data, this); pc.ResourceTracker.AddResource(archiverStream); inmsg.BodyPart.Data = archiverStream; try { inmsg.Context.Promote(_PropertyName, _PropertyNS, archiverStream.finalOutputFilepath()); } catch (Exception e) { } return inmsg; } #endregion } }
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.Utility; using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (CharacterController))] [RequireComponent(typeof (AudioSource))] public class FirstPersonController : MonoBehaviour { [SerializeField] private bool m_IsWalking; [SerializeField] private float m_WalkSpeed; [SerializeField] private float m_RunSpeed; [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten; [SerializeField] private float m_JumpSpeed; [SerializeField] private float m_StickToGroundForce; [SerializeField] private float m_GravityMultiplier; [SerializeField] private MouseLook m_MouseLook; [SerializeField] private bool m_UseFovKick; [SerializeField] private FOVKick m_FovKick = new FOVKick(); [SerializeField] private bool m_UseHeadBob; [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob(); [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob(); [SerializeField] private float m_StepInterval; [SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from. [SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground. [SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground. private Camera m_Camera; private bool m_Jump; private Vector2 m_Input; private Vector3 m_MoveDir = Vector3.zero; private CharacterController m_CharacterController; private CollisionFlags m_CollisionFlags; private bool m_PreviouslyGrounded; private Vector3 m_OriginalCameraPosition; private float m_StepCycle; private float m_NextStep; private bool m_Jumping; private AudioSource m_AudioSource; // Use this for initialization private void Start() { m_CharacterController = GetComponent<CharacterController>(); m_Camera = Camera.main; m_OriginalCameraPosition = m_Camera.transform.localPosition; m_FovKick.Setup(m_Camera); m_HeadBob.Setup(m_Camera, m_StepInterval); m_StepCycle = 0f; m_NextStep = m_StepCycle/2f; m_Jumping = false; m_AudioSource = GetComponent<AudioSource>(); m_MouseLook.Init(transform , m_Camera.transform); } // Update is called once per frame private void Update() { RotateView(); // the jump state needs to read here to make sure it is not missed if (!m_Jump) { m_Jump = CrossPlatformInputManager.GetButtonDown("Jump"); } if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) { StartCoroutine(m_JumpBob.DoBobCycle()); PlayLandingSound(); m_MoveDir.y = 0f; m_Jumping = false; } if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) { m_MoveDir.y = 0f; } m_PreviouslyGrounded = m_CharacterController.isGrounded; } private void PlayLandingSound() { m_AudioSource.clip = m_LandSound; m_AudioSource.Play(); m_NextStep = m_StepCycle + .5f; } private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height/2f, ~0, QueryTriggerInteraction.Ignore); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x*speed; m_MoveDir.z = desiredMove.z*speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); m_MouseLook.UpdateCursorLock(); } private void PlayJumpSound() { m_AudioSource.clip = m_JumpSound; m_AudioSource.Play(); } private void ProgressStepCycle(float speed) { if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)) { m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))* Time.fixedDeltaTime; } if (!(m_StepCycle > m_NextStep)) { return; } m_NextStep = m_StepCycle + m_StepInterval; PlayFootStepAudio(); } private void PlayFootStepAudio() { if (!m_CharacterController.isGrounded) { return; } // pick & play a random footstep sound from the array, // excluding sound at index 0 int n = Random.Range(1, m_FootstepSounds.Length); m_AudioSource.clip = m_FootstepSounds[n]; m_AudioSource.PlayOneShot(m_AudioSource.clip); // move picked sound to index 0 so it's not picked next time m_FootstepSounds[n] = m_FootstepSounds[0]; m_FootstepSounds[0] = m_AudioSource.clip; } private void UpdateCameraPosition(float speed) { Vector3 newCameraPosition; if (!m_UseHeadBob) { return; } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten))); newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); } else { newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset(); } m_Camera.transform.localPosition = newCameraPosition; } private void GetInput(out float speed) { // Read input float horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); float vertical = CrossPlatformInputManager.GetAxis("Vertical"); bool waswalking = m_IsWalking; #if !MOBILE_INPUT // On standalone builds, walk/run speed is modified by a key press. // keep track of whether or not the character is walking or running m_IsWalking = !Input.GetKey(KeyCode.LeftShift); #endif // set the desired speed to be walking or running speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed; m_Input = new Vector2(horizontal, vertical); // normalize input if it exceeds 1 in combined length: if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } // handle speed change to give an fov kick // only if the player is going to a run, is running and the fovkick is to be used if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) { StopAllCoroutines(); StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown()); } } private void RotateView() { m_MouseLook.LookRotation (transform, m_Camera.transform); } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation { /// <summary> /// Searcher class for finding DscResources on the system. /// </summary> internal class DscResourceSearcher : IEnumerable<DscResourceInfo>, IEnumerator<DscResourceInfo> { internal DscResourceSearcher( string resourceName, ExecutionContext context) { Diagnostics.Assert(context != null, "caller to verify context is not null"); Diagnostics.Assert(!string.IsNullOrEmpty(resourceName), "caller to verify commandName is valid"); _resourceName = resourceName; _context = context; } #region private properties private string _resourceName = null; private ExecutionContext _context = null; private DscResourceInfo _currentMatch = null; private IEnumerator<DscResourceInfo> _matchingResource = null; private Collection<DscResourceInfo> _matchingResourceList = null; #endregion #region public methods /// <summary> /// Reset the Iterator. /// </summary> public void Reset() { _currentMatch = null; _matchingResource = null; } /// <summary> /// Reset and dispose the Iterator. /// </summary> public void Dispose() { Reset(); GC.SuppressFinalize(this); } /// <summary> /// Get the Enumerator. /// </summary> /// <returns></returns> IEnumerator<DscResourceInfo> IEnumerable<DscResourceInfo>.GetEnumerator() { return this; } /// <summary> /// Get the Enumerator /// </summary> /// <returns></returns> IEnumerator IEnumerable.GetEnumerator() { return this; } /// <summary> /// Move to the Next value in the enumerator. /// </summary> /// <returns></returns> public bool MoveNext() { _currentMatch = GetNextDscResource(); if (_currentMatch != null) return true; return false; } /// <summary> /// Return the current DscResource /// </summary> DscResourceInfo IEnumerator<DscResourceInfo>.Current { get { return _currentMatch; } } /// <summary> /// Return the current DscResource as object /// </summary> object IEnumerator.Current { get { return ((IEnumerator<DscResourceInfo>)this).Current; } } #endregion #region private methods /// <summary> /// Invoke command Get-DscResource with resource name to find the resource. /// When found add them to the enumerator. If we have already got it, return the next resource. /// </summary> /// <returns>Next DscResource Info object or null if none are found.</returns> private DscResourceInfo GetNextDscResource() { var ps = PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand("Get-DscResource"); WildcardPattern resourceMatcher = WildcardPattern.Get(_resourceName, WildcardOptions.IgnoreCase); if (_matchingResourceList == null) { Collection<PSObject> psObjs = ps.Invoke(); _matchingResourceList = new Collection<DscResourceInfo>(); bool matchFound = false; foreach (dynamic resource in psObjs) { if (resource.Name != null) { string resourceName = resource.Name; if (resourceMatcher.IsMatch(resourceName)) { DscResourceInfo resourceInfo = new DscResourceInfo(resourceName, resource.ResourceType, resource.Path, resource.ParentPath, _context ); resourceInfo.FriendlyName = resource.FriendlyName; resourceInfo.CompanyName = resource.CompanyName; PSModuleInfo psMod = resource.Module as PSModuleInfo; if (psMod != null) resourceInfo.Module = psMod; if (resource.ImplementedAs != null) { ImplementedAsType impType; if (Enum.TryParse<ImplementedAsType>(resource.ImplementedAs.ToString(), out impType)) resourceInfo.ImplementedAs = impType; } var properties = resource.Properties as IList; if (properties != null) { List<DscResourcePropertyInfo> propertyList = new List<DscResourcePropertyInfo>(); foreach (dynamic prop in properties) { DscResourcePropertyInfo propInfo = new DscResourcePropertyInfo(); propInfo.Name = prop.Name; propInfo.PropertyType = prop.PropertyType; propInfo.UpdateValues(prop.Values); propertyList.Add(propInfo); } resourceInfo.UpdateProperties(propertyList); } _matchingResourceList.Add(resourceInfo); matchFound = true; } //if }//if }// foreach if (matchFound) _matchingResource = _matchingResourceList.GetEnumerator(); else return null; }//if if (!_matchingResource.MoveNext()) { _matchingResource = null; } else { return _matchingResource.Current; } return null; } #endregion } }
// The MIT License (MIT) // // Copyright (c) 2014-2017, Institute for Software & Systems Engineering // // 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 SafetySharp.CaseStudies.RobotCell.Modeling.Controllers { using System; using System.Collections.Generic; using System.Linq; using ISSE.SafetyChecking.Modeling; using SafetySharp.Modeling; internal abstract class ObserverController : Component { public const int MaxSteps = 350; private bool _hasReconfed; [NonSerializable] private Tuple<Agent, Capability[]>[] _lastRoleAllocations; // for debugging purposes //[Hidden] private bool _reconfigurationRequested = true; [Range(0, MaxSteps, OverflowBehavior.Clamp)] public int _stepCount; public AnalysisMode Mode = AnalysisMode.AllFaults; public readonly Fault ReconfigurationFailure = new TransientFault(); protected ObserverController(IEnumerable<Agent> agents, List<Task> tasks) { Tasks = tasks; Agents = agents.ToArray(); foreach (var agent in Agents) { agent.ObserverController = this; GenerateConstraints(agent); } } [Hidden] protected List<Task> Tasks { get; } [Hidden(HideElements = true)] public Agent[] Agents { get; } public ReconfStates ReconfigurationState { get; protected set; } = ReconfStates.NotSet; public ReconfStates OracleState { get; protected set; } = ReconfStates.NotSet; protected abstract void Reconfigure(); public void ScheduleReconfiguration() { _reconfigurationRequested = true; } private void GenerateConstraints(Agent agent) { agent.Constraints = new List<Func<bool>> { #if !ENABLE_F6 // missing Observer constraint // I/O Consistency () => agent.AllocatedRoles.All(role => role.PreCondition.Port == null || agent.Inputs.Contains(role.PreCondition.Port)), () => agent.AllocatedRoles.All(role => role.PostCondition.Port == null || agent.Outputs.Contains(role.PostCondition.Port)), #endif // Capability Consistency () => agent.AllocatedRoles.All( role => role.CapabilitiesToApply.All(capability => agent.AvailableCapabilities.Any(c => c.IsEquivalentTo(capability)))), // Pre-PostconditionConsistency () => agent.AllocatedRoles.Any(role => role.PostCondition.Port == null || role.PreCondition.Port == null) || agent.AllocatedRoles.TrueForAll(role => PostMatching(role, agent) && PreMatching(role, agent)) }; } private bool PostMatching(Role role, Agent agent) { if (role.PostCondition.Port.AllocatedRoles.All(role1 => role1.PreCondition.Port != agent)) { ; } else if ( !role.PostCondition.Port.AllocatedRoles.Any( role1 => role.PostCondition.StateMatches(role1.PreCondition.State))) { ; } else if (role.PostCondition.Port.AllocatedRoles.All(role1 => role.PostCondition.Task != role1.PreCondition.Task)) { ; } return role.PostCondition.Port.AllocatedRoles.Any(role1 => role1.PreCondition.Port == agent && role.PostCondition.StateMatches(role1.PreCondition.State) && role.PostCondition.Task == role1.PreCondition.Task); } private bool PreMatching(Role role, Agent agent) { return role.PreCondition.Port.AllocatedRoles.Any(role1 => role1.PostCondition.Port == agent && role.PreCondition.StateMatches(role1.PostCondition.State) && role.PreCondition.Task == role1.PostCondition.Task); } public override void Update() { if (Mode == AnalysisMode.IntolerableFaults) { ++_stepCount; if (_stepCount >= MaxSteps) return; } if (ReconfigurationState == ReconfStates.Failed) return; foreach (var agent in Agents) { if (_reconfigurationRequested) break; agent.Update(); } if (!_reconfigurationRequested) return; if (Mode == AnalysisMode.TolerableFaults) { // This speeds up analyses when checking for reconf failures with DCCA, but is otherwise // unacceptable for other kinds of analyses if (_hasReconfed) return; } foreach (var agent in Agents) agent.CheckAllocatedCapabilities(); foreach (var agent in Agents) { agent.AllocatedRoles.Clear(); agent.OnReconfigured(); } Reconfigure(); _reconfigurationRequested = false; _hasReconfed = true; } /// <summary> /// Applies the <paramref name="roleAllocations" /> to the system. /// </summary> /// <param name="roleAllocations">The sequence of agents and the capabilities they should execute.</param> protected virtual void ApplyConfiguration(Tuple<Agent, Capability[]>[] roleAllocations) { foreach (var task in Tasks) task.IsResourceInProduction = false; _lastRoleAllocations = roleAllocations; var allocatedCapabilities = 0; var remainingCapabilities = Tasks[0].Capabilities.Length; for (var i = 0; i < roleAllocations.Length; i++) { var agent = roleAllocations[i].Item1; var capabilities = roleAllocations[i].Item2; var preAgent = i == 0 ? null : roleAllocations[i - 1].Item1; var postAgent = i == roleAllocations.Length - 1 ? null : roleAllocations[i + 1].Item1; #if ENABLE_F4 || ENABLE_F4b // error F4: incorrect Condition.State format var preCondition = new Condition(Tasks[0], preAgent, remainingCapabilities); var postCondition = new Condition(Tasks[0], postAgent, remainingCapabilities - capabilities.Length); #else var preCondition = new Condition(Tasks[0], preAgent, allocatedCapabilities); var postCondition = new Condition(Tasks[0], postAgent, allocatedCapabilities + capabilities.Length); #endif var role = new Role(preCondition, postCondition, allocatedCapabilities, capabilities.Length); allocatedCapabilities += capabilities.Length; remainingCapabilities -= capabilities.Length; agent.Configure(role); } } #region oracle for back-to-back testing protected bool IsReconfPossible(IEnumerable<RobotAgent> robotsAgents, IEnumerable<Task> tasks) { var isReconfPossible = true; var matrix = GetConnectionMatrix(robotsAgents); foreach (var task in tasks) { isReconfPossible &= task.Capabilities.All(capability => robotsAgents.Any(agent => ContainsCapability(agent.AvailableCapabilities, capability))); if (!isReconfPossible) break; var candidates = robotsAgents.Where(agent => ContainsCapability(agent.AvailableCapabilities, task.Capabilities.First())).ToArray(); for (var i = 0; i < task.Capabilities.Length - 1; i++) { candidates = candidates.SelectMany(r => matrix[r]) .Where(r => ContainsCapability(r.AvailableCapabilities, task.Capabilities[i + 1])) .ToArray(); if (candidates.Length == 0) { isReconfPossible = false; } } } return isReconfPossible; } private Dictionary<RobotAgent, List<RobotAgent>> GetConnectionMatrix(IEnumerable<RobotAgent> robotAgents) { var matrix = new Dictionary<RobotAgent, List<RobotAgent>>(); foreach (var robot in robotAgents) { var list = new List<RobotAgent>(robotAgents.Where(r => IsConnected(robot, r, new HashSet<RobotAgent>()))); matrix.Add(robot, list); } return matrix; } private static bool IsConnected(RobotAgent sourceRobot, RobotAgent targetRobot, HashSet<RobotAgent> seenRobots) { if (sourceRobot == targetRobot) return true; if (!seenRobots.Add(sourceRobot)) return false; #if ENABLE_F2 // F2: routes are assumed to be unidirectional, while they are in fact bidirectional. // Since this is reflected by incorrect assignments to agents' Inputs and Outputs, // the oracle must be fixed to account for this. var neighbouringRobots = sourceRobot.Outputs.Concat(sourceRobot.Inputs) .SelectMany(cart => cart.Outputs.Concat(cart.Inputs)); #else var neighbouringRobots = sourceRobot.Outputs.SelectMany(cart => cart.Outputs); #endif foreach (var neighbouringRobot in neighbouringRobots) { if (neighbouringRobot == targetRobot) return true; if (IsConnected((RobotAgent)neighbouringRobot, targetRobot, seenRobots)) return true; } return false; } private bool ContainsCapability(IEnumerable<Capability> capabilities, Capability capability) { return capabilities.Any(c => c.IsEquivalentTo(capability)); } #endregion [FaultEffect(Fault = nameof(ReconfigurationFailure))] public abstract class ReconfigurationFailureEffect : ObserverController { protected ReconfigurationFailureEffect(IEnumerable<Agent> agents, List<Task> tasks) : base(agents, tasks) { } protected override void ApplyConfiguration(Tuple<Agent, Capability[]>[] roleAllocations) { ReconfigurationState = ReconfStates.Failed; } } } }
// 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 BroadcastScalarToVector256SByte() { var test = new SimpleUnaryOpTest__BroadcastScalarToVector256SByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.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 (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.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__BroadcastScalarToVector256SByte { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); 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<SByte, 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 Vector128<SByte> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__BroadcastScalarToVector256SByte testClass) { var result = Avx2.BroadcastScalarToVector256(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__BroadcastScalarToVector256SByte testClass) { fixed (Vector128<SByte>* pFld1 = &_fld1) { var result = Avx2.BroadcastScalarToVector256( Sse2.LoadVector128((SByte*)(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<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static Vector128<SByte> _clsVar1; private Vector128<SByte> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__BroadcastScalarToVector256SByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public SimpleUnaryOpTest__BroadcastScalarToVector256SByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.BroadcastScalarToVector256( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.BroadcastScalarToVector256( Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.BroadcastScalarToVector256( Sse2.LoadAlignedVector128((SByte*)(_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(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector256), new Type[] { typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector256), new Type[] { typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector256), new Type[] { typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.BroadcastScalarToVector256( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar1 = &_clsVar1) { var result = Avx2.BroadcastScalarToVector256( Sse2.LoadVector128((SByte*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr); var result = Avx2.BroadcastScalarToVector256(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)); var result = Avx2.BroadcastScalarToVector256(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)); var result = Avx2.BroadcastScalarToVector256(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__BroadcastScalarToVector256SByte(); var result = Avx2.BroadcastScalarToVector256(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__BroadcastScalarToVector256SByte(); fixed (Vector128<SByte>* pFld1 = &test._fld1) { var result = Avx2.BroadcastScalarToVector256( Sse2.LoadVector128((SByte*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.BroadcastScalarToVector256(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld1 = &_fld1) { var result = Avx2.BroadcastScalarToVector256( Sse2.LoadVector128((SByte*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.BroadcastScalarToVector256(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 = Avx2.BroadcastScalarToVector256( Sse2.LoadVector128((SByte*)(&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(Vector128<SByte> op1, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (firstOp[0] != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((firstOp[0] != result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.BroadcastScalarToVector256)}<SByte>(Vector128<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Serialization; using System.Xml.XPath; using Subtext.Framework.Components; namespace Subtext.Web.Admin { public static class OpmlProvider { public static IXPathNavigable Export(ICollection<Link> items) { var doc = new XmlDocument(); XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.AppendChild(declaration); XmlNode rootNode = doc.CreateElement("opml"); doc.AppendChild(rootNode); XmlNode headNode = doc.CreateElement("head"); rootNode.AppendChild(headNode); XmlNode bodyNode = doc.CreateElement("body"); rootNode.AppendChild(bodyNode); foreach (Link currentItem in items) { XmlNode outline = doc.CreateElement("outline"); XmlAttribute title = doc.CreateAttribute("title"); title.Value = currentItem.Title; outline.Attributes.Append(title); XmlAttribute description = doc.CreateAttribute("description"); description.Value = currentItem.Title; outline.Attributes.Append(description); XmlAttribute htmlurl = doc.CreateAttribute("htmlurl"); htmlurl.Value = currentItem.Url; outline.Attributes.Append(htmlurl); XmlAttribute xmlurl = doc.CreateAttribute("xmlurl"); xmlurl.Value = currentItem.Rss; outline.Attributes.Append(xmlurl); bodyNode.AppendChild(outline); } return doc; //doc.LoadXml(sw.ToString()); //return doc.CreateNavigator(); } public static void WriteOpmlItem(OpmlItem item, XmlWriter writer) { item.RenderOpml(writer); foreach (OpmlItem childItem in item.ChildItems) { WriteOpmlItem(childItem, writer); } } public static OpmlItemCollection Import(Stream fileStream) { var _currentBatch = new OpmlItemCollection(); XmlReader reader = new XmlTextReader(fileStream); var doc = new XPathDocument(reader); XPathNavigator nav = doc.CreateNavigator(); XPathNodeIterator outlineItems = nav.Select("/opml/body/outline"); while (outlineItems.MoveNext()) { _currentBatch.AddRange(DeserializeItem(outlineItems.Current)); } return _currentBatch; } public static IEnumerable<OpmlItem> DeserializeItem(XPathNavigator nav) { var items = new List<OpmlItem>(); if (nav.HasAttributes) { string title = nav.GetAttribute("title", ""); if (String.IsNullOrEmpty(title)) { title = nav.GetAttribute("text", ""); } string htmlUrl = nav.GetAttribute("htmlurl", ""); if (String.IsNullOrEmpty(htmlUrl)) { htmlUrl = nav.GetAttribute("htmlUrl", ""); } string xmlUrl = nav.GetAttribute("xmlurl", ""); if (String.IsNullOrEmpty(xmlUrl)) { xmlUrl = nav.GetAttribute("xmlUrl", ""); } OpmlItem currentItem = null; string description = nav.GetAttribute("description", ""); if (!String.IsNullOrEmpty(title) && !String.IsNullOrEmpty(htmlUrl)) { currentItem = new OpmlItem(title, description, xmlUrl, htmlUrl); } if (null != currentItem) { items.Add(currentItem); } } if (nav.HasChildren) { XPathNodeIterator childItems = nav.SelectChildren("outline", ""); while (childItems.MoveNext()) { IEnumerable<OpmlItem> children = DeserializeItem(childItems.Current); if (null != children) { items.InsertRange(items.Count, children); } } } return items; } } [Serializable] [XmlRoot(ElementName = "outline", IsNullable = true)] public class OpmlItem { private OpmlItemCollection _childItems; private string _description; private string _htmlurl; private string _title; private string _xmlurl; public OpmlItem() { _childItems = new OpmlItemCollection(); } public OpmlItem(string title, string description, string xmlUrl, string htmlUrl) : this() { _title = title; _description = description; _xmlurl = xmlUrl; _htmlurl = htmlUrl; } [XmlAttribute("title")] public string Title { get { return _title; } set { _title = value; } } [XmlAttribute("description")] public string Description { get { return _description; } set { _description = value; } } [XmlAttribute("xmlurl")] public string XmlUrl { get { return _xmlurl; } set { _xmlurl = value; } } [XmlAttribute("htmlurl")] public string HtmlUrl { get { return _htmlurl; } set { _htmlurl = value; } } public OpmlItemCollection ChildItems { get { return _childItems; } set { _childItems = value; } } internal void RenderOpml(XmlWriter writer) { writer.WriteStartElement("outline"); writer.WriteAttributeString("title", Title); writer.WriteAttributeString("description", Description); writer.WriteAttributeString("htmlurl", HtmlUrl); writer.WriteAttributeString("xmlurl", XmlUrl); writer.WriteEndElement(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Storage.Queues; using Azure.Storage.Queues.Models; using Microsoft.Extensions.Logging; using Orleans.AzureUtils.Utilities; using Orleans.Configuration; using Orleans.Runtime; namespace Orleans.AzureUtils { /// <summary> /// How to use the Queue Storage Service: http://www.windowsazure.com/en-us/develop/net/how-to-guides/queue-service/ /// Windows Azure Storage Abstractions and their Scalability Targets: http://blogs.msdn.com/b/windowsazurestorage/archive/2010/05/10/windows-azure-storage-abstractions-and-their-scalability-targets.aspx /// Naming Queues and Metadata: http://msdn.microsoft.com/en-us/library/windowsazure/dd179349.aspx /// Windows Azure Queues and Windows Azure Service Bus Queues - Compared and Contrasted: http://msdn.microsoft.com/en-us/library/hh767287(VS.103).aspx /// Status and Error Codes: http://msdn.microsoft.com/en-us/library/dd179382.aspx /// /// http://blogs.msdn.com/b/windowsazurestorage/archive/tags/scalability/ /// http://blogs.msdn.com/b/windowsazurestorage/archive/2010/12/30/windows-azure-storage-architecture-overview.aspx /// http://blogs.msdn.com/b/windowsazurestorage/archive/2010/11/06/how-to-get-most-out-of-windows-azure-tables.aspx /// /// </summary> internal static class AzureQueueDefaultPolicies { public static int MaxQueueOperationRetries; public static TimeSpan PauseBetweenQueueOperationRetries; public static TimeSpan QueueOperationTimeout; static AzureQueueDefaultPolicies() { MaxQueueOperationRetries = 5; PauseBetweenQueueOperationRetries = TimeSpan.FromMilliseconds(100); QueueOperationTimeout = PauseBetweenQueueOperationRetries.Multiply(MaxQueueOperationRetries).Multiply(6); // 3 sec } } /// <summary> /// Utility class to encapsulate access to Azure queue storage. /// </summary> /// <remarks> /// Used by Azure queue streaming provider. /// </remarks> public class AzureQueueDataManager { /// <summary> Name of the table queue instance is managing. </summary> public string QueueName { get; private set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] private readonly ILogger logger; private readonly TimeSpan? messageVisibilityTimeout; private readonly AzureQueueOptions options; private QueueClient _queueClient; /// <summary> /// Constructor. /// </summary> /// <param name="loggerFactory">logger factory to use</param> /// <param name="queueName">Name of the queue to be connected to.</param> /// <param name="storageConnectionString">Connection string for the Azure storage account used to host this table.</param> /// <param name="visibilityTimeout">A TimeSpan specifying the visibility timeout interval</param> public AzureQueueDataManager(ILoggerFactory loggerFactory, string queueName, string storageConnectionString, TimeSpan? visibilityTimeout = null) : this (loggerFactory, queueName, ConfigureOptions(storageConnectionString, visibilityTimeout)) { } private static AzureQueueOptions ConfigureOptions(string storageConnectionString, TimeSpan? visibilityTimeout) { var options = new AzureQueueOptions { MessageVisibilityTimeout = visibilityTimeout }; options.ConfigureQueueServiceClient(storageConnectionString); return options; } /// <summary> /// Constructor. /// </summary> /// <param name="loggerFactory">logger factory to use</param> /// <param name="queueName">Name of the queue to be connected to.</param> /// <param name="options">Queue connection options.</param> public AzureQueueDataManager(ILoggerFactory loggerFactory, string queueName, AzureQueueOptions options) { queueName = SanitizeQueueName(queueName); ValidateQueueName(queueName); logger = loggerFactory.CreateLogger<AzureQueueDataManager>(); QueueName = queueName; messageVisibilityTimeout = options.MessageVisibilityTimeout; this.options = options; } private ValueTask<QueueClient> GetQueueClient() { if (_queueClient is { } client) { return new(client); } return GetQueueClientAsync(); async ValueTask<QueueClient> GetQueueClientAsync() => _queueClient ??= await GetCloudQueueClient(options, logger); } /// <summary> /// Initializes the connection to the queue. /// </summary> public async Task InitQueueAsync() { var startTime = DateTime.UtcNow; try { // Create the queue if it doesn't already exist. var client = await GetQueueClient(); var response = await client.CreateIfNotExistsAsync(); logger.LogInformation((int)AzureQueueErrorCode.AzureQueue_01, "Connected to Azure storage queue {QueueName}", QueueName); } catch (Exception exc) { ReportErrorAndRethrow(exc, "CreateIfNotExist", AzureQueueErrorCode.AzureQueue_02); } finally { CheckAlertSlowAccess(startTime, "InitQueue_Async"); } } /// <summary> /// Deletes the queue. /// </summary> public async Task DeleteQueue() { var startTime = DateTime.UtcNow; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Deleting queue: {0}", QueueName); try { // that way we don't have first to create the queue to be able later to delete it. var client = await GetQueueClient(); if (await client.DeleteIfExistsAsync()) { logger.Info((int)AzureQueueErrorCode.AzureQueue_03, "Deleted Azure Queue {0}", QueueName); } } catch (Exception exc) { ReportErrorAndRethrow(exc, "DeleteQueue", AzureQueueErrorCode.AzureQueue_04); } finally { CheckAlertSlowAccess(startTime, "DeleteQueue"); } } /// <summary> /// Clears the queue. /// </summary> public async Task ClearQueue() { var startTime = DateTime.UtcNow; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Clearing a queue: {0}", QueueName); try { // that way we don't have first to create the queue to be able later to delete it. var client = await GetQueueClient(); await client.ClearMessagesAsync(); logger.Info((int)AzureQueueErrorCode.AzureQueue_05, "Cleared Azure Queue {0}", QueueName); } catch (RequestFailedException exc) { if (exc.Status != (int)HttpStatusCode.NotFound) { ReportErrorAndRethrow(exc, "ClearQueue", AzureQueueErrorCode.AzureQueue_06); } } catch (Exception exc) { ReportErrorAndRethrow(exc, "ClearQueue", AzureQueueErrorCode.AzureQueue_06); } finally { CheckAlertSlowAccess(startTime, "ClearQueue"); } } /// <summary> /// Adds a new message to the queue. /// </summary> /// <param name="message">Message to be added to the queue.</param> public async Task AddQueueMessage(string message) { var startTime = DateTime.UtcNow; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Adding message {0} to queue: {1}", message, QueueName); try { var client = await GetQueueClient(); await client.SendMessageAsync(message); } catch (Exception exc) { ReportErrorAndRethrow(exc, "AddQueueMessage", AzureQueueErrorCode.AzureQueue_07); } finally { CheckAlertSlowAccess(startTime, "AddQueueMessage"); } } /// <summary> /// Peeks in the queue for latest message, without dequeuing it. /// </summary> public async Task<PeekedMessage> PeekQueueMessage() { var startTime = DateTime.UtcNow; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Peeking a message from queue: {0}", QueueName); try { var client = await GetQueueClient(); var messages = await client.PeekMessagesAsync(maxMessages: 1); return messages.Value.FirstOrDefault(); } catch (Exception exc) { ReportErrorAndRethrow(exc, "PeekQueueMessage", AzureQueueErrorCode.AzureQueue_08); return null; // Dummy statement to keep compiler happy } finally { CheckAlertSlowAccess(startTime, "PeekQueueMessage"); } } /// <summary> /// Gets a new message from the queue. /// </summary> public async Task<QueueMessage> GetQueueMessage() { var startTime = DateTime.UtcNow; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Getting a message from queue: {0}", QueueName); try { //BeginGetMessage and EndGetMessage is not supported in netstandard, may be use GetMessageAsync // http://msdn.microsoft.com/en-us/library/ee758456.aspx // If no messages are visible in the queue, GetMessage returns null. var client = await GetQueueClient(); var messages = await client.ReceiveMessagesAsync(maxMessages: 1, messageVisibilityTimeout); return messages.Value.FirstOrDefault(); } catch (Exception exc) { ReportErrorAndRethrow(exc, "GetQueueMessage", AzureQueueErrorCode.AzureQueue_09); return null; // Dummy statement to keep compiler happy } finally { CheckAlertSlowAccess(startTime, "GetQueueMessage"); } } /// <summary> /// Gets a number of new messages from the queue. /// </summary> /// <param name="count">Number of messages to get from the queue.</param> public async Task<IEnumerable<QueueMessage>> GetQueueMessages(int? count = null) { var startTime = DateTime.UtcNow; if (count == -1) { count = null; } if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Getting up to {0} messages from queue: {1}", count, QueueName); try { var client = await GetQueueClient(); var messages = await client.ReceiveMessagesAsync(count, messageVisibilityTimeout); return messages.Value; } catch (Exception exc) { ReportErrorAndRethrow(exc, "GetQueueMessages", AzureQueueErrorCode.AzureQueue_10); return null; // Dummy statement to keep compiler happy } finally { CheckAlertSlowAccess(startTime, "GetQueueMessages"); } } /// <summary> /// Deletes a messages from the queue. /// </summary> /// <param name="message">A message to be deleted from the queue.</param> public async Task DeleteQueueMessage(QueueMessage message) { var startTime = DateTime.UtcNow; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Deleting a message from queue: {0}", QueueName); try { var client = await GetQueueClient(); await client.DeleteMessageAsync(message.MessageId, message.PopReceipt); } catch (Exception exc) { ReportErrorAndRethrow(exc, "DeleteMessage", AzureQueueErrorCode.AzureQueue_11); } finally { CheckAlertSlowAccess(startTime, "DeleteQueueMessage"); } } internal async Task GetAndDeleteQueueMessage() { var message = await GetQueueMessage(); await DeleteQueueMessage(message); } /// <summary> /// Returns an approximate number of messages in the queue. /// </summary> public async Task<int> GetApproximateMessageCount() { var startTime = DateTime.UtcNow; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("GetApproximateMessageCount a message from queue: {0}", QueueName); try { var client = await GetQueueClient(); var properties = await client.GetPropertiesAsync(); return properties.Value.ApproximateMessagesCount; } catch (Exception exc) { ReportErrorAndRethrow(exc, "FetchAttributes", AzureQueueErrorCode.AzureQueue_12); return 0; // Dummy statement to keep compiler happy } finally { CheckAlertSlowAccess(startTime, "GetApproximateMessageCount"); } } private void CheckAlertSlowAccess(DateTime startOperation, string operation) { var timeSpan = DateTime.UtcNow - startOperation; if (timeSpan > AzureQueueDefaultPolicies.QueueOperationTimeout) { logger.Warn((int)AzureQueueErrorCode.AzureQueue_13, "Slow access to Azure queue {0} for {1}, which took {2}.", QueueName, operation, timeSpan); } } private void ReportErrorAndRethrow(Exception exc, string operation, AzureQueueErrorCode errorCode) { var errMsg = String.Format( "Error doing {0} for Azure storage queue {1} " + Environment.NewLine + "Exception = {2}", operation, QueueName, exc); logger.Error((int)errorCode, errMsg, exc); throw new AggregateException(errMsg, exc); } private async Task<QueueClient> GetCloudQueueClient(AzureQueueOptions options, ILogger logger) { try { var client = await options.CreateClient(); return client.GetQueueClient(QueueName); } catch (Exception exc) { logger.LogError((int)AzureQueueErrorCode.AzureQueue_14, exc, "Error creating Azure Storage Queues client"); throw; } } private string SanitizeQueueName(string queueName) { var tmp = queueName; //Azure queue naming rules : https://docs.microsoft.com/en-us/rest/api/storageservices/Naming-Queues-and-Metadata?redirectedfrom=MSDN tmp = tmp.ToLowerInvariant(); tmp = tmp .Replace('/', '-') // Forward slash .Replace('\\', '-') // Backslash .Replace('#', '-') // Pound sign .Replace('?', '-') // Question mark .Replace('&', '-') .Replace('+', '-') .Replace(':', '-') .Replace('.', '-') .Replace('%', '-'); return tmp; } private void ValidateQueueName(string queueName) { // Naming Queues and Metadata: http://msdn.microsoft.com/en-us/library/windowsazure/dd179349.aspx if (!(queueName.Length >= 3 && queueName.Length <= 63)) { // A queue name must be from 3 through 63 characters long. throw new ArgumentException(String.Format("A queue name must be from 3 through 63 characters long, while your queueName length is {0}, queueName is {1}.", queueName.Length, queueName), queueName); } if (!Char.IsLetterOrDigit(queueName.First())) { // A queue name must start with a letter or number throw new ArgumentException(String.Format("A queue name must start with a letter or number, while your queueName is {0}.", queueName), queueName); } if (!Char.IsLetterOrDigit(queueName.Last())) { // The first and last letters in the queue name must be alphanumeric. The dash (-) character cannot be the first or last character. throw new ArgumentException(String.Format("The last letter in the queue name must be alphanumeric, while your queueName is {0}.", queueName), queueName); } if (!queueName.All(c => Char.IsLetterOrDigit(c) || c.Equals('-'))) { // A queue name can only contain letters, numbers, and the dash (-) character. throw new ArgumentException(String.Format("A queue name can only contain letters, numbers, and the dash (-) character, while your queueName is {0}.", queueName), queueName); } if (queueName.Contains("--")) { // Consecutive dash characters are not permitted in the queue name. throw new ArgumentException(String.Format("Consecutive dash characters are not permitted in the queue name, while your queueName is {0}.", queueName), queueName); } if (queueName.Where(Char.IsLetter).Any(c => !Char.IsLower(c))) { // All letters in a queue name must be lowercase. throw new ArgumentException(String.Format("All letters in a queue name must be lowercase, while your queueName is {0}.", queueName), queueName); } } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- // Provide default values for all World Editor settings. These make use of // the EditorSettings instance of the Settings class, as defined in the Tools // package onStart(). EditorSettings.beginGroup( "WorldEditor", true ); EditorSettings.setDefaultValue( "currentEditor", "WorldEditorInspectorPlugin" ); EditorSettings.setDefaultValue( "dropType", "screenCenter" ); EditorSettings.setDefaultValue( "undoLimit", "40" ); EditorSettings.setDefaultValue( "forceLoadDAE", "0" ); EditorSettings.setDefaultValue( "displayType", $EditTsCtrl::DisplayTypePerspective ); EditorSettings.setDefaultValue( "orthoFOV", "50" ); EditorSettings.setDefaultValue( "orthoShowGrid", "1" ); EditorSettings.setDefaultValue( "currentEditor", "WorldEditorInspectorPlugin" ); EditorSettings.setDefaultValue( "newLevelFile", "tools/levels/BlankRoom.mis" ); if( isFile( "C:/Program Files/Torsion/Torsion.exe" ) ) EditorSettings.setDefaultValue( "torsionPath", "C:/Program Files/Torsion/Torsion.exe" ); else if( isFile( "C:/Program Files (x86)/Torsion/Torsion.exe" ) ) EditorSettings.setDefaultValue( "torsionPath", "C:/Program Files (x86)/Torsion/Torsion.exe" ); else EditorSettings.setDefaultValue( "torsionPath", "" ); EditorSettings.beginGroup( "ObjectIcons" ); EditorSettings.setDefaultValue( "fadeIcons", "1" ); EditorSettings.setDefaultValue( "fadeIconsStartDist", "8" ); EditorSettings.setDefaultValue( "fadeIconsEndDist", "20" ); EditorSettings.setDefaultValue( "fadeIconsStartAlpha", "255" ); EditorSettings.setDefaultValue( "fadeIconsEndAlpha", "0" ); EditorSettings.endGroup(); EditorSettings.beginGroup( "Grid" ); EditorSettings.setDefaultValue( "gridSize", "1" ); EditorSettings.setDefaultValue( "gridSnap", "0" ); EditorSettings.setDefaultValue( "gridColor", "102 102 102 100" ); EditorSettings.setDefaultValue( "gridOriginColor", "255 255 255 100" ); EditorSettings.setDefaultValue( "gridMinorColor", "51 51 51 100" ); EditorSettings.endGroup(); EditorSettings.beginGroup( "Tools" ); EditorSettings.setDefaultValue( "snapGround", "0" ); EditorSettings.setDefaultValue( "snapSoft", "0" ); EditorSettings.setDefaultValue( "snapSoftSize", "2.0" ); EditorSettings.setDefaultValue( "boundingBoxCollision", "0" ); EditorSettings.setDefaultValue( "objectsUseBoxCenter", "1" ); EditorSettings.setDefaultValue( "dropAtScreenCenterScalar","1.0" ); EditorSettings.setDefaultValue( "dropAtScreenCenterMax", "100.0" ); EditorSettings.endGroup(); EditorSettings.beginGroup( "Render" ); EditorSettings.setDefaultValue( "renderObjHandle", "1" ); EditorSettings.setDefaultValue( "renderObjText", "1" ); EditorSettings.setDefaultValue( "renderPopupBackground", "1" ); EditorSettings.setDefaultValue( "renderSelectionBox", "1" ); //<-- Does not currently render EditorSettings.setDefaultValue( "showMousePopupInfo", "1" ); //EditorSettings.setDefaultValue( "visibleDistanceScale", "1" ); EditorSettings.endGroup(); EditorSettings.beginGroup( "Color" ); EditorSettings.setDefaultValue( "dragRectColor", "255 255 0 255" ); EditorSettings.setDefaultValue( "objectTextColor", "255 255 255 255" ); EditorSettings.setDefaultValue( "objMouseOverColor", "0 255 0 255" ); //<-- Currently ignored by editor (always white) EditorSettings.setDefaultValue( "objMouseOverSelectColor", "0 0 255 255" ); //<-- Currently ignored by editor (always white) EditorSettings.setDefaultValue( "objSelectColor", "255 0 0 255" ); //<-- Currently ignored by editor (always white) EditorSettings.setDefaultValue( "popupBackgroundColor", "100 100 100 255" ); EditorSettings.setDefaultValue( "popupTextColor", "255 255 0 255" ); EditorSettings.setDefaultValue( "raceSelectColor", "0 0 100 100" ); //<-- What is this used for? EditorSettings.setDefaultValue( "selectionBoxColor", "255 255 0 255" ); //<-- Does not currently render EditorSettings.setDefaultValue( "uvEditorHandleColor", "1" ); //<-- Index into color popup EditorSettings.endGroup(); EditorSettings.beginGroup( "Images" ); EditorSettings.setDefaultValue( "defaultHandle", "tools/worldEditor/images/DefaultHandle" ); EditorSettings.setDefaultValue( "lockedHandle", "tools/worldEditor/images/LockedHandle" ); EditorSettings.setDefaultValue( "selectHandle", "tools/worldEditor/images/SelectHandle" ); EditorSettings.endGroup(); EditorSettings.beginGroup( "Docs" ); EditorSettings.setDefaultValue( "documentationLocal", "../../../Documentation/Official Documentation.html" ); EditorSettings.setDefaultValue( "documentationReference", "../../../Documentation/Torque 3D - Script Manual.chm"); EditorSettings.setDefaultValue( "documentationURL", "http://www.garagegames.com/products/torque-3d/documentation/user" ); EditorSettings.setDefaultValue( "forumURL", "http://www.garagegames.com/products/torque-3d/forums" ); EditorSettings.endGroup(); EditorSettings.endGroup(); // WorldEditor //------------------------------------- // After setting up the default value, this field should be altered immediately // after successfully using such functionality such as Open... or Save As... EditorSettings.beginGroup( "LevelInformation" ); EditorSettings.setDefaultValue( "levelsDirectory", "levels" ); EditorSettings.endGroup(); //------------------------------------- EditorSettings.beginGroup( "AxisGizmo", true ); EditorSettings.setDefaultValue( "axisGizmoMaxScreenLen", "100" ); //<-- What is this used for? EditorSettings.setDefaultValue( "rotationSnap", "15" ); //<-- Not currently used EditorSettings.setDefaultValue( "snapRotations", "0" ); //<-- Not currently used EditorSettings.setDefaultValue( "mouseRotateScalar", "0.8" ); EditorSettings.setDefaultValue( "mouseScaleScalar", "0.8" ); EditorSettings.setDefaultValue( "renderWhenUsed", "0" ); EditorSettings.setDefaultValue( "renderInfoText", "1" ); EditorSettings.beginGroup( "Grid" ); EditorSettings.setDefaultValue( "gridColor", "255 255 255 20" ); EditorSettings.setDefaultValue( "gridSize", "10 10 10" ); EditorSettings.setDefaultValue( "snapToGrid", "0" ); //<-- Not currently used EditorSettings.setDefaultValue( "renderPlane", "0" ); EditorSettings.setDefaultValue( "renderPlaneHashes", "0" ); EditorSettings.setDefaultValue( "planeDim", "500" ); EditorSettings.endGroup(); EditorSettings.endGroup(); //------------------------------------- EditorSettings.beginGroup( "TerrainEditor", true ); EditorSettings.setDefaultValue( "currentAction", "raiseHeight" ); EditorSettings.beginGroup( "Brush" ); EditorSettings.setDefaultValue( "maxBrushSize", "40 40" ); EditorSettings.setDefaultValue( "brushSize", "1 1" ); EditorSettings.setDefaultValue( "brushType", "box" ); EditorSettings.setDefaultValue( "brushPressure", "1" ); EditorSettings.setDefaultValue( "brushSoftness", "1" ); EditorSettings.endGroup(); EditorSettings.beginGroup( "ActionValues" ); EditorSettings.setDefaultValue( "adjustHeightVal", "10" ); EditorSettings.setDefaultValue( "setHeightVal", "100" ); EditorSettings.setDefaultValue( "scaleVal", "1" ); //<-- Tool not currently implemented EditorSettings.setDefaultValue( "smoothFactor", "0.1" ); EditorSettings.setDefaultValue( "noiseFactor", "1.0" ); EditorSettings.setDefaultValue( "softSelectRadius", "50" ); EditorSettings.setDefaultValue( "softSelectFilter", "1.000000 0.833333 0.666667 0.500000 0.333333 0.166667 0.000000" ); EditorSettings.setDefaultValue( "softSelectDefaultFilter", "1.000000 0.833333 0.666667 0.500000 0.333333 0.166667 0.000000" ); EditorSettings.setDefaultValue( "slopeMinAngle", "0" ); EditorSettings.setDefaultValue( "slopeMaxAngle", "90" ); EditorSettings.endGroup(); EditorSettings.endGroup(); //------------------------------------- EditorSettings.beginGroup( "TerrainPainter", true ); EditorSettings.endGroup(); //------------------------------------- //TODO: this doesn't belong here function setDefault( %name, %value ) { if( !isDefined( %name ) ) eval( %name SPC "=" SPC "\"" @ %value @ "\";" ); } setDefault( "$pref::WorldEditor::visibleDistanceScale", "1" ); // DAW: Keep this around for now as is used by EditTSCtrl // JCF: Couldn't some or all of these be exposed // from WorldEditor::ConsoleInit via Con::AddVariable() // and do away with this file? function EditorGui::readWorldEditorSettings(%this) { EditorSettings.beginGroup( "WorldEditor", true ); EWorldEditor.dropType = EditorSettings.value( "dropType" ); //$pref::WorldEditor::dropType; EWorldEditor.undoLimit = EditorSettings.value( "undoLimit" ); //$pref::WorldEditor::undoLimit; EWorldEditor.forceLoadDAE = EditorSettings.value( "forceLoadDAE" ); //$pref::WorldEditor::forceLoadDAE; %this.currentDisplayType = EditorSettings.value( "displayType" ); %this.currentOrthoFOV = EditorSettings.value( "orthoFOV" ); EWorldEditor.renderOrthoGrid = EditorSettings.value( "orthoShowGrid" ); %this.currentEditor = EditorSettings.value( "currentEditor" ); %this.torsionPath = EditorSettings.value( "torsionPath" ); EditorSettings.beginGroup( "ObjectIcons" ); EWorldEditor.fadeIcons = EditorSettings.value( "fadeIcons" ); EWorldEditor.fadeIconsStartDist = EditorSettings.value( "fadeIconsStartDist" ); EWorldEditor.fadeIconsEndDist = EditorSettings.value( "fadeIconsEndDist" ); EWorldEditor.fadeIconsStartAlpha = EditorSettings.value( "fadeIconsStartAlpha" ); EWorldEditor.fadeIconsEndAlpha = EditorSettings.value( "fadeIconsEndAlpha" ); EditorSettings.endGroup(); EditorSettings.beginGroup( "Grid" ); EWorldEditor.gridSize = EditorSettings.value( "gridSize" ); EWorldEditor.gridSnap = EditorSettings.value( "gridSnap" ); EWorldEditor.gridColor = EditorSettings.value( "gridColor" ); EWorldEditor.gridOriginColor = EditorSettings.value( "gridOriginColor" ); EWorldEditor.gridMinorColor = EditorSettings.value( "gridMinorColor" ); EditorSettings.endGroup(); EditorSettings.beginGroup( "Tools" ); EWorldEditor.stickToGround = EditorSettings.value("snapGround"); //$pref::WorldEditor::snapGround; EWorldEditor.setSoftSnap( EditorSettings.value("snapSoft") ); //$pref::WorldEditor::snapSoft EWorldEditor.setSoftSnapSize( EditorSettings.value("snapSoftSize") ); //$pref::WorldEditor::snapSoftSize EWorldEditor.boundingBoxCollision = EditorSettings.value("boundingBoxCollision"); //$pref::WorldEditor::boundingBoxCollision; EWorldEditor.objectsUseBoxCenter = EditorSettings.value("objectsUseBoxCenter"); //$pref::WorldEditor::objectsUseBoxCenter; EWorldEditor.dropAtScreenCenterScalar = EditorSettings.value("dropAtScreenCenterScalar"); EWorldEditor.dropAtScreenCenterMax = EditorSettings.value("dropAtScreenCenterMax"); EditorSettings.endGroup(); EditorSettings.beginGroup( "Render" ); EWorldEditor.renderObjHandle = EditorSettings.value("renderObjHandle"); //$pref::WorldEditor::renderObjHandle; EWorldEditor.renderObjText = EditorSettings.value("renderObjText"); //$pref::WorldEditor::renderObjText; EWorldEditor.renderPopupBackground = EditorSettings.value("renderPopupBackground"); //$pref::WorldEditor::renderPopupBackground; EWorldEditor.renderSelectionBox = EditorSettings.value("renderSelectionBox"); //$pref::WorldEditor::renderSelectionBox; EWorldEditor.showMousePopupInfo = EditorSettings.value("showMousePopupInfo"); //$pref::WorldEditor::showMousePopupInfo; EditorSettings.endGroup(); EditorSettings.beginGroup( "Color" ); EWorldEditor.dragRectColor = EditorSettings.value("dragRectColor"); //$pref::WorldEditor::dragRectColor; EWorldEditor.objectTextColor = EditorSettings.value("objectTextColor"); //$pref::WorldEditor::objectTextColor; EWorldEditor.objMouseOverColor = EditorSettings.value("objMouseOverColor"); //$pref::WorldEditor::objMouseOverColor; EWorldEditor.objMouseOverSelectColor = EditorSettings.value("objMouseOverSelectColor"); //$pref::WorldEditor::objMouseOverSelectColor; EWorldEditor.objSelectColor = EditorSettings.value("objSelectColor"); //$pref::WorldEditor::objSelectColor; EWorldEditor.popupBackgroundColor = EditorSettings.value("popupBackgroundColor"); //$pref::WorldEditor::popupBackgroundColor; EWorldEditor.popupTextColor = EditorSettings.value("popupTextColor"); //$pref::WorldEditor::popupTextColor; EWorldEditor.selectionBoxColor = EditorSettings.value("selectionBoxColor"); //$pref::WorldEditor::selectionBoxColor; EditorSettings.endGroup(); EditorSettings.beginGroup( "Images" ); EWorldEditor.defaultHandle = EditorSettings.value("defaultHandle"); //$pref::WorldEditor::defaultHandle; EWorldEditor.lockedHandle = EditorSettings.value("lockedHandle"); //$pref::WorldEditor::lockedHandle; EWorldEditor.selectHandle = EditorSettings.value("selectHandle"); //$pref::WorldEditor::selectHandle; EditorSettings.endGroup(); EditorSettings.beginGroup( "Docs" ); EWorldEditor.documentationLocal = EditorSettings.value( "documentationLocal" ); EWorldEditor.documentationURL = EditorSettings.value( "documentationURL" ); EWorldEditor.documentationReference = EditorSettings.value( "documentationReference" ); EWorldEditor.forumURL = EditorSettings.value( "forumURL" ); EditorSettings.endGroup(); //EWorldEditor.planarMovement = $pref::WorldEditor::planarMovement; //<-- What is this used for? EditorSettings.endGroup(); // WorldEditor EditorSettings.beginGroup( "AxisGizmo", true ); GlobalGizmoProfile.screenLength = EditorSettings.value("axisGizmoMaxScreenLen"); //$pref::WorldEditor::axisGizmoMaxScreenLen; GlobalGizmoProfile.rotationSnap = EditorSettings.value("rotationSnap"); //$pref::WorldEditor::rotationSnap; GlobalGizmoProfile.snapRotations = EditorSettings.value("snapRotations"); //$pref::WorldEditor::snapRotations; GlobalGizmoProfile.rotateScalar = EditorSettings.value("mouseRotateScalar"); //$pref::WorldEditor::mouseRotateScalar; GlobalGizmoProfile.scaleScalar = EditorSettings.value("mouseScaleScalar"); //$pref::WorldEditor::mouseScaleScalar; GlobalGizmoProfile.renderWhenUsed = EditorSettings.value("renderWhenUsed"); GlobalGizmoProfile.renderInfoText = EditorSettings.value("renderInfoText"); EditorSettings.beginGroup( "Grid" ); GlobalGizmoProfile.gridColor = EditorSettings.value("gridColor"); //$pref::WorldEditor::gridColor; GlobalGizmoProfile.gridSize = EditorSettings.value("gridSize"); //$pref::WorldEditor::gridSize; GlobalGizmoProfile.snapToGrid = EditorSettings.value("snapToGrid"); //$pref::WorldEditor::snapToGrid; GlobalGizmoProfile.renderPlane = EditorSettings.value("renderPlane"); //$pref::WorldEditor::renderPlane; GlobalGizmoProfile.renderPlaneHashes = EditorSettings.value("renderPlaneHashes"); //$pref::WorldEditor::renderPlaneHashes; GlobalGizmoProfile.planeDim = EditorSettings.value("planeDim"); //$pref::WorldEditor::planeDim; EditorSettings.endGroup(); EditorSettings.endGroup(); // AxisGizmo } function EditorGui::writeWorldEditorSettings(%this) { EditorSettings.beginGroup( "WorldEditor", true ); EditorSettings.setValue( "dropType", EWorldEditor.dropType ); //$pref::WorldEditor::dropType EditorSettings.setValue( "undoLimit", EWorldEditor.undoLimit ); //$pref::WorldEditor::undoLimit EditorSettings.setValue( "forceLoadDAE", EWorldEditor.forceLoadDAE ); //$pref::WorldEditor::forceLoadDAE EditorSettings.setValue( "displayType", %this.currentDisplayType ); EditorSettings.setValue( "orthoFOV", %this.currentOrthoFOV ); EditorSettings.setValue( "orthoShowGrid", EWorldEditor.renderOrthoGrid ); EditorSettings.setValue( "currentEditor", %this.currentEditor ); EditorSettings.setvalue( "torsionPath", %this.torsionPath ); EditorSettings.beginGroup( "ObjectIcons" ); EditorSettings.setValue( "fadeIcons", EWorldEditor.fadeIcons ); EditorSettings.setValue( "fadeIconsStartDist", EWorldEditor.fadeIconsStartDist ); EditorSettings.setValue( "fadeIconsEndDist", EWorldEditor.fadeIconsEndDist ); EditorSettings.setValue( "fadeIconsStartAlpha", EWorldEditor.fadeIconsStartAlpha ); EditorSettings.setValue( "fadeIconsEndAlpha", EWorldEditor.fadeIconsEndAlpha ); EditorSettings.endGroup(); EditorSettings.beginGroup( "Grid" ); EditorSettings.setValue( "gridSize", EWorldEditor.gridSize ); EditorSettings.setValue( "gridSnap", EWorldEditor.gridSnap ); EditorSettings.setValue( "gridColor", EWorldEditor.gridColor ); EditorSettings.setValue( "gridOriginColor", EWorldEditor.gridOriginColor ); EditorSettings.setValue( "gridMinorColor", EWorldEditor.gridMinorColor ); EditorSettings.endGroup(); EditorSettings.beginGroup( "Tools" ); EditorSettings.setValue( "snapGround", EWorldEditor.stickToGround ); //$Pref::WorldEditor::snapGround EditorSettings.setValue( "snapSoft", EWorldEditor.getSoftSnap() ); //$Pref::WorldEditor::snapSoft EditorSettings.setValue( "snapSoftSize", EWorldEditor.getSoftSnapSize() ); //$Pref::WorldEditor::snapSoftSize EditorSettings.setValue( "boundingBoxCollision", EWorldEditor.boundingBoxCollision ); //$Pref::WorldEditor::boundingBoxCollision EditorSettings.setValue( "objectsUseBoxCenter", EWorldEditor.objectsUseBoxCenter ); //$Pref::WorldEditor::objectsUseBoxCenter EditorSettings.setValue( "dropAtScreenCenterScalar", EWorldEditor.dropAtScreenCenterScalar ); EditorSettings.setValue( "dropAtScreenCenterMax", EWorldEditor.dropAtScreenCenterMax ); EditorSettings.endGroup(); EditorSettings.beginGroup( "Render" ); EditorSettings.setValue( "renderObjHandle", EWorldEditor.renderObjHandle ); //$Pref::WorldEditor::renderObjHandle EditorSettings.setValue( "renderObjText", EWorldEditor.renderObjText ); //$Pref::WorldEditor::renderObjText EditorSettings.setValue( "renderPopupBackground", EWorldEditor.renderPopupBackground ); //$Pref::WorldEditor::renderPopupBackground EditorSettings.setValue( "renderSelectionBox", EWorldEditor.renderSelectionBox ); //$Pref::WorldEditor::renderSelectionBox EditorSettings.setValue( "showMousePopupInfo", EWorldEditor.showMousePopupInfo ); //$Pref::WorldEditor::showMousePopupInfo EditorSettings.endGroup(); EditorSettings.beginGroup( "Color" ); EditorSettings.setValue( "dragRectColor", EWorldEditor.dragRectColor ); //$Pref::WorldEditor::dragRectColor EditorSettings.setValue( "objectTextColor", EWorldEditor.objectTextColor ); //$Pref::WorldEditor::objectTextColor EditorSettings.setValue( "objMouseOverColor", EWorldEditor.objMouseOverColor ); //$Pref::WorldEditor::objMouseOverColor EditorSettings.setValue( "objMouseOverSelectColor",EWorldEditor.objMouseOverSelectColor );//$Pref::WorldEditor::objMouseOverSelectColor EditorSettings.setValue( "objSelectColor", EWorldEditor.objSelectColor ); //$Pref::WorldEditor::objSelectColor EditorSettings.setValue( "popupBackgroundColor", EWorldEditor.popupBackgroundColor ); //$Pref::WorldEditor::popupBackgroundColor EditorSettings.setValue( "selectionBoxColor", EWorldEditor.selectionBoxColor ); //$Pref::WorldEditor::selectionBoxColor EditorSettings.endGroup(); EditorSettings.beginGroup( "Images" ); EditorSettings.setValue( "defaultHandle", EWorldEditor.defaultHandle ); //$Pref::WorldEditor::defaultHandle EditorSettings.setValue( "selectHandle", EWorldEditor.selectHandle ); //$Pref::WorldEditor::selectHandle EditorSettings.setValue( "lockedHandle", EWorldEditor.lockedHandle ); //$Pref::WorldEditor::lockedHandle EditorSettings.endGroup(); EditorSettings.beginGroup( "Docs" ); EditorSettings.setValue( "documentationLocal", EWorldEditor.documentationLocal ); EditorSettings.setValue( "documentationReference", EWorldEditor.documentationReference ); EditorSettings.setValue( "documentationURL", EWorldEditor.documentationURL ); EditorSettings.setValue( "forumURL", EWorldEditor.forumURL ); EditorSettings.endGroup(); EditorSettings.endGroup(); // WorldEditor EditorSettings.beginGroup( "AxisGizmo", true ); EditorSettings.setValue( "axisGizmoMaxScreenLen", GlobalGizmoProfile.screenLength ); //$Pref::WorldEditor::axisGizmoMaxScreenLen EditorSettings.setValue( "rotationSnap", GlobalGizmoProfile.rotationSnap ); //$Pref::WorldEditor::rotationSnap EditorSettings.setValue( "snapRotations", GlobalGizmoProfile.snapRotations ); //$Pref::WorldEditor::snapRotations EditorSettings.setValue( "mouseRotateScalar", GlobalGizmoProfile.rotateScalar ); //$Pref::WorldEditor::mouseRotateScalar EditorSettings.setValue( "mouseScaleScalar", GlobalGizmoProfile.scaleScalar ); //$Pref::WorldEditor::mouseScaleScalar EditorSettings.setValue( "renderWhenUsed", GlobalGizmoProfile.renderWhenUsed ); EditorSettings.setValue( "renderInfoText", GlobalGizmoProfile.renderInfoText ); EditorSettings.beginGroup( "Grid" ); EditorSettings.setValue( "gridColor", GlobalGizmoProfile.gridColor ); //$Pref::WorldEditor::gridColor EditorSettings.setValue( "gridSize", GlobalGizmoProfile.gridSize ); //$Pref::WorldEditor::gridSize EditorSettings.setValue( "snapToGrid", GlobalGizmoProfile.snapToGrid ); //$Pref::WorldEditor::snapToGrid EditorSettings.setValue( "renderPlane", GlobalGizmoProfile.renderPlane ); //$Pref::WorldEditor::renderPlane EditorSettings.setValue( "renderPlaneHashes", GlobalGizmoProfile.renderPlaneHashes );//$Pref::WorldEditor::renderPlaneHashes EditorSettings.setValue( "planeDim", GlobalGizmoProfile.planeDim ); //$Pref::WorldEditor::planeDim EditorSettings.endGroup(); EditorSettings.endGroup(); // AxisGizmo } function EditorGui::readTerrainEditorSettings(%this) { EditorSettings.beginGroup( "TerrainEditor", true ); ETerrainEditor.savedAction = EditorSettings.value("currentAction"); EditorSettings.beginGroup( "Brush" ); ETerrainEditor.maxBrushSize = EditorSettings.value("maxBrushSize"); ETerrainEditor.setBrushSize( EditorSettings.value("brushSize") ); ETerrainEditor.setBrushType( EditorSettings.value("brushType") ); ETerrainEditor.setBrushPressure( EditorSettings.value("brushPressure") ); ETerrainEditor.setBrushSoftness( EditorSettings.value("brushSoftness") ); EditorSettings.endGroup(); EditorSettings.beginGroup( "ActionValues" ); ETerrainEditor.adjustHeightVal = EditorSettings.value("adjustHeightVal"); ETerrainEditor.setHeightVal = EditorSettings.value("setHeightVal"); ETerrainEditor.scaleVal = EditorSettings.value("scaleVal"); ETerrainEditor.smoothFactor = EditorSettings.value("smoothFactor"); ETerrainEditor.noiseFactor = EditorSettings.value("noiseFactor"); ETerrainEditor.softSelectRadius = EditorSettings.value("softSelectRadius"); ETerrainEditor.softSelectFilter = EditorSettings.value("softSelectFilter"); ETerrainEditor.softSelectDefaultFilter = EditorSettings.value("softSelectDefaultFilter"); ETerrainEditor.setSlopeLimitMinAngle( EditorSettings.value("slopeMinAngle") ); ETerrainEditor.setSlopeLimitMaxAngle( EditorSettings.value("slopeMaxAngle") ); EditorSettings.endGroup(); EditorSettings.endGroup(); } function EditorGui::writeTerrainEditorSettings(%this) { EditorSettings.beginGroup( "TerrainEditor", true ); EditorSettings.setValue( "currentAction", ETerrainEditor.savedAction ); EditorSettings.beginGroup( "Brush" ); EditorSettings.setValue( "maxBrushSize", ETerrainEditor.maxBrushSize ); EditorSettings.setValue( "brushSize", ETerrainEditor.getBrushSize() ); EditorSettings.setValue( "brushType", ETerrainEditor.getBrushType() ); EditorSettings.setValue( "brushPressure", ETerrainEditor.getBrushPressure() ); EditorSettings.setValue( "brushSoftness", ETerrainEditor.getBrushSoftness() ); EditorSettings.endGroup(); EditorSettings.beginGroup( "ActionValues" ); EditorSettings.setValue( "adjustHeightVal", ETerrainEditor.adjustHeightVal ); EditorSettings.setValue( "setHeightVal", ETerrainEditor.setHeightVal ); EditorSettings.setValue( "scaleVal", ETerrainEditor.scaleVal ); EditorSettings.setValue( "smoothFactor", ETerrainEditor.smoothFactor ); EditorSettings.setValue( "noiseFactor", ETerrainEditor.noiseFactor ); EditorSettings.setValue( "softSelectRadius", ETerrainEditor.softSelectRadius ); EditorSettings.setValue( "softSelectFilter", ETerrainEditor.softSelectFilter ); EditorSettings.setValue( "softSelectDefaultFilter",ETerrainEditor.softSelectDefaultFilter ); EditorSettings.setValue( "slopeMinAngle", ETerrainEditor.getSlopeLimitMinAngle() ); EditorSettings.setValue( "slopeMaxAngle", ETerrainEditor.getSlopeLimitMaxAngle() ); EditorSettings.endGroup(); EditorSettings.endGroup(); }
using System; namespace Xwt.GoogleMaterialDesignIcons { public class ActionIconId { public const string Rotation3d = "3dRotation"; public const string Accessibility = "Accessibility"; public const string Accessible = "Accessible"; public const string AccountBalance = "AccountBalance"; public const string AccountBalanceWallet = "AccountBalanceWallet"; public const string AccountBox = "AccountBox"; public const string AccountCircle = "AccountCircle"; public const string AddShoppingCart = "AddShoppingCart"; public const string Alarm = "Alarm"; public const string AlarmAdd = "AlarmAdd"; public const string AlarmOff = "AlarmOff"; public const string AlarmOn = "AlarmOn"; public const string AllOut = "AllOut"; public const string Android = "Android"; public const string Announcement = "Announcement"; public const string AspectRatio = "AspectRatio"; public const string Assessment = "Assessment"; public const string Assignment = "Assignment"; public const string AssignmentInd = "AssignmentInd"; public const string AssignmentLate = "AssignmentLate"; public const string AssignmentReturn = "AssignmentReturn"; public const string AssignmentReturned = "AssignmentReturned"; public const string AssignmentTurnedIn = "AssignmentTurnedIn"; public const string Autorenew = "Autorenew"; public const string Backup = "Backup"; public const string Book = "Book"; public const string Bookmark = "Bookmark"; public const string BookmarkBorder = "BookmarkBorder"; public const string BugReport = "BugReport"; public const string Build = "Build"; public const string Cached = "Cached"; public const string CardGiftcard = "CardGiftcard"; public const string CardMembership = "CardMembership"; public const string CardTravel = "CardTravel"; public const string ChangeHistory = "ChangeHistory"; public const string CheckCircle = "CheckCircle"; public const string ChromeReaderMode = "ChromeReaderMode"; public const string Class = "Class"; public const string Code = "Code"; public const string CompareArrows = "CompareArrows"; public const string Copyright = "Copyright"; public const string CreditCard = "CreditCard"; public const string Dashboard = "Dashboard"; public const string DateRange = "DateRange"; public const string Delete = "Delete"; public const string DeleteForever = "DeleteForever"; public const string Description = "Description"; public const string Dns = "Dns"; public const string Done = "Done"; public const string DoneAll = "DoneAll"; public const string DonutLarge = "DonutLarge"; public const string DonutSmall = "DonutSmall"; public const string EuroSymbol = "EuroSymbol"; public const string Event = "Event"; public const string EventSeat = "EventSeat"; public const string ExitToApp = "ExitToApp"; public const string Explore = "Explore"; public const string Extension = "Extension"; public const string Face = "Face"; public const string Favorite = "Favorite"; public const string FavoriteBorder = "FavoriteBorder"; public const string Feedback = "Feedback"; public const string FindInPage = "FindInPage"; public const string FindReplace = "FindReplace"; public const string Fingerprint = "Fingerprint"; public const string FlightLand = "FlightLand"; public const string FlightTakeoff = "FlightTakeoff"; public const string FlipToBack = "FlipToBack"; public const string FlipToFront = "FlipToFront"; public const string Gavel = "Gavel"; public const string GetApp = "GetApp"; public const string Grade = "Grade"; public const string GroupWork = "GroupWork"; public const string GTranslate = "GTranslate"; public const string Help = "Help"; public const string HighlightOff = "HighlightOff"; public const string History = "History"; public const string Home = "Home"; public const string HourglassEmpty = "HourglassEmpty"; public const string HourglassFull = "HourglassFull"; public const string Http = "Http"; public const string Https = "Https"; public const string ImportantDevices = "ImportantDevices"; public const string Info = "Info"; public const string InfoOutline = "InfoOutline"; public const string Input = "Input"; public const string InvertColors = "InvertColors"; public const string Label = "Label"; public const string LabelOutline = "LabelOutline"; public const string Language = "Language"; public const string Launch = "Launch"; public const string LightbulbOutline = "LightbulbOutline"; public const string LineStyle = "LineStyle"; public const string LineWeight = "LineWeight"; public const string List = "List"; public const string Lock = "Lock"; public const string LockOpen = "LockOpen"; public const string LockOutline = "LockOutline"; public const string Loyalty = "Loyalty"; public const string MarkunreadMailbox = "MarkunreadMailbox"; public const string Motorcycle = "Motorcycle"; public const string NoteAdd = "NoteAdd"; public const string Opacity = "Opacity"; public const string OpenInBrowser = "OpenInBrowser"; public const string OpenInNew = "OpenInNew"; public const string OpenWith = "OpenWith"; public const string Pageview = "Pageview"; public const string PanTool = "PanTool"; public const string Payment = "Payment"; public const string PermCameraMic = "PermCameraMic"; public const string PermContactCalendar = "PermContactCalendar"; public const string PermDataSetting = "PermDataSetting"; public const string PermDeviceInformation = "PermDeviceInformation"; public const string PermIdentity = "PermIdentity"; public const string PermMedia = "PermMedia"; public const string PermPhoneMsg = "PermPhoneMsg"; public const string PermScanWifi = "PermScanWifi"; public const string Pets = "Pets"; public const string PictureInPicture = "PictureInPicture"; public const string PictureInPictureAlt = "PictureInPictureAlt"; public const string PlayForWork = "PlayForWork"; public const string Polymer = "Polymer"; public const string PowerSettingsNew = "PowerSettingsNew"; public const string PregnantWoman = "PregnantWoman"; public const string Print = "Print"; public const string QueryBuilder = "QueryBuilder"; public const string QuestionAnswer = "QuestionAnswer"; public const string Receipt = "Receipt"; public const string RecordVoiceOver = "RecordVoiceOver"; public const string Redeem = "Redeem"; public const string RemoveShoppingCart = "RemoveShoppingCart"; public const string ReportProblem = "ReportProblem"; public const string Restore = "Restore"; public const string RestorePage = "RestorePage"; public const string Room = "Room"; public const string RoundedCorner = "RoundedCorner"; public const string Rowing = "Rowing"; public const string Schedule = "Schedule"; public const string Search = "Search"; public const string Settings = "Settings"; public const string SettingsApplications = "SettingsApplications"; public const string SettingsBackupRestore = "SettingsBackupRestore"; public const string SettingsBluetooth = "SettingsBluetooth"; public const string SettingsBrightness = "SettingsBrightness"; public const string SettingsCell = "SettingsCell"; public const string SettingsEthernet = "SettingsEthernet"; public const string SettingsInputAntenna = "SettingsInputAntenna"; public const string SettingsInputComponent = "SettingsInputComponent"; public const string SettingsInputComposite = "SettingsInputComposite"; public const string SettingsInputHdmi = "SettingsInputHdmi"; public const string SettingsInputSvideo = "SettingsInputSvideo"; public const string SettingsOverscan = "SettingsOverscan"; public const string SettingsPhone = "SettingsPhone"; public const string SettingsPower = "SettingsPower"; public const string SettingsRemote = "SettingsRemote"; public const string SettingsVoice = "SettingsVoice"; public const string Shop = "Shop"; public const string ShoppingBasket = "ShoppingBasket"; public const string ShoppingCart = "ShoppingCart"; public const string ShopTwo = "ShopTwo"; public const string SpeakerNotes = "SpeakerNotes"; public const string SpeakerNotesOff = "SpeakerNotesOff"; public const string Spellcheck = "Spellcheck"; public const string Stars = "Stars"; public const string Store = "Store"; public const string Subject = "Subject"; public const string SupervisorAccount = "SupervisorAccount"; public const string SwapHoriz = "SwapHoriz"; public const string SwapVert = "SwapVert"; public const string SwapVerticalCircle = "SwapVerticalCircle"; public const string SystemUpdateAlt = "SystemUpdateAlt"; public const string Tab = "Tab"; public const string TabUnselected = "TabUnselected"; public const string Theaters = "Theaters"; public const string ThumbDown = "ThumbDown"; public const string ThumbsUpDown = "ThumbsUpDown"; public const string ThumbUp = "ThumbUp"; public const string Timeline = "Timeline"; public const string Toc = "Toc"; public const string Today = "Today"; public const string Toll = "Toll"; public const string TouchApp = "TouchApp"; public const string TrackChanges = "TrackChanges"; public const string Translate = "Translate"; public const string TrendingDown = "TrendingDown"; public const string TrendingFlat = "TrendingFlat"; public const string TrendingUp = "TrendingUp"; public const string TurnedIn = "TurnedIn"; public const string TurnedInNot = "TurnedInNot"; public const string Update = "Update"; public const string VerifiedUser = "VerifiedUser"; public const string ViewAgenda = "ViewAgenda"; public const string ViewArray = "ViewArray"; public const string ViewCarousel = "ViewCarousel"; public const string ViewColumn = "ViewColumn"; public const string ViewDay = "ViewDay"; public const string ViewHeadline = "ViewHeadline"; public const string ViewList = "ViewList"; public const string ViewModule = "ViewModule"; public const string ViewQuilt = "ViewQuilt"; public const string ViewStream = "ViewStream"; public const string ViewWeek = "ViewWeek"; public const string Visibility = "Visibility"; public const string VisibilityOff = "VisibilityOff"; public const string WatchLater = "WatchLater"; public const string Work = "Work"; public const string YoutubeSearchedFor = "YoutubeSearchedFor"; } }
// 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 gagr = Google.Api.Gax.ResourceNames; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Talent.V4.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedTenantServiceClientTest { [xunit::FactAttribute] public void CreateTenantRequestObject() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", }; mockGrpcClient.Setup(x => x.CreateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.CreateTenant(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTenantRequestObjectAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", }; mockGrpcClient.Setup(x => x.CreateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.CreateTenantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.CreateTenantAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTenant() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", }; mockGrpcClient.Setup(x => x.CreateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.CreateTenant(request.Parent, request.Tenant); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTenantAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", }; mockGrpcClient.Setup(x => x.CreateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.CreateTenantAsync(request.Parent, request.Tenant, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.CreateTenantAsync(request.Parent, request.Tenant, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTenantResourceNames() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", }; mockGrpcClient.Setup(x => x.CreateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.CreateTenant(request.ParentAsProjectName, request.Tenant); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTenantResourceNamesAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", }; mockGrpcClient.Setup(x => x.CreateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.CreateTenantAsync(request.ParentAsProjectName, request.Tenant, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.CreateTenantAsync(request.ParentAsProjectName, request.Tenant, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTenantRequestObject() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", }; mockGrpcClient.Setup(x => x.GetTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.GetTenant(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTenantRequestObjectAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", }; mockGrpcClient.Setup(x => x.GetTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.GetTenantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.GetTenantAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTenant() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", }; mockGrpcClient.Setup(x => x.GetTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.GetTenant(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTenantAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", }; mockGrpcClient.Setup(x => x.GetTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.GetTenantAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.GetTenantAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTenantResourceNames() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", }; mockGrpcClient.Setup(x => x.GetTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.GetTenant(request.TenantName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTenantResourceNamesAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", }; mockGrpcClient.Setup(x => x.GetTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.GetTenantAsync(request.TenantName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.GetTenantAsync(request.TenantName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateTenantRequestObject() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); UpdateTenantRequest request = new UpdateTenantRequest { Tenant = new Tenant(), UpdateMask = new wkt::FieldMask(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", }; mockGrpcClient.Setup(x => x.UpdateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.UpdateTenant(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateTenantRequestObjectAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); UpdateTenantRequest request = new UpdateTenantRequest { Tenant = new Tenant(), UpdateMask = new wkt::FieldMask(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", }; mockGrpcClient.Setup(x => x.UpdateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.UpdateTenantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.UpdateTenantAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateTenant() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); UpdateTenantRequest request = new UpdateTenantRequest { Tenant = new Tenant(), UpdateMask = new wkt::FieldMask(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", }; mockGrpcClient.Setup(x => x.UpdateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.UpdateTenant(request.Tenant, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateTenantAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); UpdateTenantRequest request = new UpdateTenantRequest { Tenant = new Tenant(), UpdateMask = new wkt::FieldMask(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", }; mockGrpcClient.Setup(x => x.UpdateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.UpdateTenantAsync(request.Tenant, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.UpdateTenantAsync(request.Tenant, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTenantRequestObject() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); client.DeleteTenant(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTenantRequestObjectAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteTenantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTenantAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTenant() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); client.DeleteTenant(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTenantAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteTenantAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTenantAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTenantResourceNames() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); client.DeleteTenant(request.TenantName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTenantResourceNamesAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteTenantAsync(request.TenantName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTenantAsync(request.TenantName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } } }
// 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.Windows.Media; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.Language.Intellisense; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class GlyphExtensions { public static StandardGlyphGroup GetStandardGlyphGroup(this Glyph glyph) { switch (glyph) { case Glyph.Assembly: return StandardGlyphGroup.GlyphAssembly; case Glyph.BasicFile: case Glyph.BasicProject: return StandardGlyphGroup.GlyphVBProject; case Glyph.ClassPublic: case Glyph.ClassProtected: case Glyph.ClassPrivate: case Glyph.ClassInternal: return StandardGlyphGroup.GlyphGroupClass; case Glyph.ConstantPublic: case Glyph.ConstantProtected: case Glyph.ConstantPrivate: case Glyph.ConstantInternal: return StandardGlyphGroup.GlyphGroupConstant; case Glyph.CSharpFile: return StandardGlyphGroup.GlyphCSharpFile; case Glyph.CSharpProject: return StandardGlyphGroup.GlyphCoolProject; case Glyph.DelegatePublic: case Glyph.DelegateProtected: case Glyph.DelegatePrivate: case Glyph.DelegateInternal: return StandardGlyphGroup.GlyphGroupDelegate; case Glyph.EnumPublic: case Glyph.EnumProtected: case Glyph.EnumPrivate: case Glyph.EnumInternal: return StandardGlyphGroup.GlyphGroupEnum; case Glyph.EnumMember: return StandardGlyphGroup.GlyphGroupEnumMember; case Glyph.Error: return StandardGlyphGroup.GlyphGroupError; case Glyph.ExtensionMethodPublic: return StandardGlyphGroup.GlyphExtensionMethod; case Glyph.ExtensionMethodProtected: return StandardGlyphGroup.GlyphExtensionMethodProtected; case Glyph.ExtensionMethodPrivate: return StandardGlyphGroup.GlyphExtensionMethodPrivate; case Glyph.ExtensionMethodInternal: return StandardGlyphGroup.GlyphExtensionMethodInternal; case Glyph.EventPublic: case Glyph.EventProtected: case Glyph.EventPrivate: case Glyph.EventInternal: return StandardGlyphGroup.GlyphGroupEvent; case Glyph.FieldPublic: case Glyph.FieldProtected: case Glyph.FieldPrivate: case Glyph.FieldInternal: return StandardGlyphGroup.GlyphGroupField; case Glyph.InterfacePublic: case Glyph.InterfaceProtected: case Glyph.InterfacePrivate: case Glyph.InterfaceInternal: return StandardGlyphGroup.GlyphGroupInterface; case Glyph.Intrinsic: return StandardGlyphGroup.GlyphGroupIntrinsic; case Glyph.Keyword: return StandardGlyphGroup.GlyphKeyword; case Glyph.Label: return StandardGlyphGroup.GlyphGroupIntrinsic; case Glyph.Local: return StandardGlyphGroup.GlyphGroupVariable; case Glyph.Namespace: return StandardGlyphGroup.GlyphGroupNamespace; case Glyph.MethodPublic: case Glyph.MethodProtected: case Glyph.MethodPrivate: case Glyph.MethodInternal: return StandardGlyphGroup.GlyphGroupMethod; case Glyph.ModulePublic: case Glyph.ModuleProtected: case Glyph.ModulePrivate: case Glyph.ModuleInternal: return StandardGlyphGroup.GlyphGroupModule; case Glyph.OpenFolder: return StandardGlyphGroup.GlyphOpenFolder; case Glyph.Operator: return StandardGlyphGroup.GlyphGroupOperator; case Glyph.Parameter: return StandardGlyphGroup.GlyphGroupVariable; case Glyph.PropertyPublic: case Glyph.PropertyProtected: case Glyph.PropertyPrivate: case Glyph.PropertyInternal: return StandardGlyphGroup.GlyphGroupProperty; case Glyph.RangeVariable: return StandardGlyphGroup.GlyphGroupVariable; case Glyph.Reference: return StandardGlyphGroup.GlyphReference; case Glyph.StructurePublic: case Glyph.StructureProtected: case Glyph.StructurePrivate: case Glyph.StructureInternal: return StandardGlyphGroup.GlyphGroupStruct; case Glyph.TypeParameter: return StandardGlyphGroup.GlyphGroupType; case Glyph.Snippet: return StandardGlyphGroup.GlyphCSharpExpansion; case Glyph.CompletionWarning: return StandardGlyphGroup.GlyphCompletionWarning; default: throw new ArgumentException("glyph"); } } public static StandardGlyphItem GetStandardGlyphItem(this Glyph icon) { switch (icon) { case Glyph.ClassProtected: case Glyph.ConstantProtected: case Glyph.DelegateProtected: case Glyph.EnumProtected: case Glyph.EventProtected: case Glyph.FieldProtected: case Glyph.InterfaceProtected: case Glyph.MethodProtected: case Glyph.ModuleProtected: case Glyph.PropertyProtected: case Glyph.StructureProtected: return StandardGlyphItem.GlyphItemProtected; case Glyph.ClassPrivate: case Glyph.ConstantPrivate: case Glyph.DelegatePrivate: case Glyph.EnumPrivate: case Glyph.EventPrivate: case Glyph.FieldPrivate: case Glyph.InterfacePrivate: case Glyph.MethodPrivate: case Glyph.ModulePrivate: case Glyph.PropertyPrivate: case Glyph.StructurePrivate: return StandardGlyphItem.GlyphItemPrivate; case Glyph.ClassInternal: case Glyph.ConstantInternal: case Glyph.DelegateInternal: case Glyph.EnumInternal: case Glyph.EventInternal: case Glyph.FieldInternal: case Glyph.InterfaceInternal: case Glyph.MethodInternal: case Glyph.ModuleInternal: case Glyph.PropertyInternal: case Glyph.StructureInternal: return StandardGlyphItem.GlyphItemFriend; default: // We don't want any overlays return StandardGlyphItem.GlyphItemPublic; } } public static ImageSource GetImageSource(this Glyph? glyph, IGlyphService glyphService) { return glyph.HasValue ? glyph.Value.GetImageSource(glyphService) : null; } public static ImageSource GetImageSource(this Glyph glyph, IGlyphService glyphService) { return glyphService.GetGlyph(glyph.GetStandardGlyphGroup(), glyph.GetStandardGlyphItem()); } public static ImageMoniker GetImageMoniker(this Glyph glyph) { switch (glyph) { case Glyph.Assembly: return KnownMonikers.Assembly; case Glyph.BasicFile: return KnownMonikers.VBFileNode; case Glyph.BasicProject: return KnownMonikers.VBProjectNode; case Glyph.ClassPublic: return KnownMonikers.ClassPublic; case Glyph.ClassProtected: return KnownMonikers.ClassProtected; case Glyph.ClassPrivate: return KnownMonikers.ClassPrivate; case Glyph.ClassInternal: return KnownMonikers.ClassInternal; case Glyph.CSharpFile: return KnownMonikers.CSFileNode; case Glyph.CSharpProject: return KnownMonikers.CSProjectNode; case Glyph.ConstantPublic: return KnownMonikers.ConstantPublic; case Glyph.ConstantProtected: return KnownMonikers.ConstantProtected; case Glyph.ConstantPrivate: return KnownMonikers.ConstantPrivate; case Glyph.ConstantInternal: return KnownMonikers.ConstantInternal; case Glyph.DelegatePublic: return KnownMonikers.DelegatePublic; case Glyph.DelegateProtected: return KnownMonikers.DelegateProtected; case Glyph.DelegatePrivate: return KnownMonikers.DelegatePrivate; case Glyph.DelegateInternal: return KnownMonikers.DelegateInternal; case Glyph.EnumPublic: return KnownMonikers.EnumerationPublic; case Glyph.EnumProtected: return KnownMonikers.EnumerationProtected; case Glyph.EnumPrivate: return KnownMonikers.EnumerationPrivate; case Glyph.EnumInternal: return KnownMonikers.EnumerationInternal; case Glyph.EnumMember: return KnownMonikers.EnumerationItemPublic; case Glyph.Error: return KnownMonikers.StatusError; case Glyph.EventPublic: return KnownMonikers.EventPublic; case Glyph.EventProtected: return KnownMonikers.EventProtected; case Glyph.EventPrivate: return KnownMonikers.EventPrivate; case Glyph.EventInternal: return KnownMonikers.EventInternal; // Extension methods have the same glyph regardless of accessibility. case Glyph.ExtensionMethodPublic: case Glyph.ExtensionMethodProtected: case Glyph.ExtensionMethodPrivate: case Glyph.ExtensionMethodInternal: return KnownMonikers.ExtensionMethod; case Glyph.FieldPublic: return KnownMonikers.FieldPublic; case Glyph.FieldProtected: return KnownMonikers.FieldProtected; case Glyph.FieldPrivate: return KnownMonikers.FieldPrivate; case Glyph.FieldInternal: return KnownMonikers.FieldInternal; case Glyph.InterfacePublic: return KnownMonikers.InterfacePublic; case Glyph.InterfaceProtected: return KnownMonikers.InterfaceProtected; case Glyph.InterfacePrivate: return KnownMonikers.InterfacePrivate; case Glyph.InterfaceInternal: return KnownMonikers.InterfaceInternal; // TODO: Figure out the right thing to return here. case Glyph.Intrinsic: return KnownMonikers.Type; case Glyph.Keyword: return KnownMonikers.IntellisenseKeyword; case Glyph.Label: return KnownMonikers.Label; case Glyph.Parameter: case Glyph.Local: return KnownMonikers.LocalVariable; case Glyph.Namespace: return KnownMonikers.Namespace; case Glyph.MethodPublic: return KnownMonikers.MethodPublic; case Glyph.MethodProtected: return KnownMonikers.MethodProtected; case Glyph.MethodPrivate: return KnownMonikers.MethodPrivate; case Glyph.MethodInternal: return KnownMonikers.MethodInternal; case Glyph.ModulePublic: return KnownMonikers.ModulePublic; case Glyph.ModuleProtected: return KnownMonikers.ModuleProtected; case Glyph.ModulePrivate: return KnownMonikers.ModulePrivate; case Glyph.ModuleInternal: return KnownMonikers.ModuleInternal; case Glyph.OpenFolder: return KnownMonikers.OpenFolder; case Glyph.Operator: return KnownMonikers.Operator; case Glyph.PropertyPublic: return KnownMonikers.PropertyPublic; case Glyph.PropertyProtected: return KnownMonikers.PropertyProtected; case Glyph.PropertyPrivate: return KnownMonikers.PropertyPrivate; case Glyph.PropertyInternal: return KnownMonikers.PropertyInternal; case Glyph.RangeVariable: return KnownMonikers.FieldPublic; case Glyph.Reference: return KnownMonikers.Reference; case Glyph.StructurePublic: return KnownMonikers.ValueTypePublic; case Glyph.StructureProtected: return KnownMonikers.ValueTypeProtected; case Glyph.StructurePrivate: return KnownMonikers.ValueTypePrivate; case Glyph.StructureInternal: return KnownMonikers.ValueTypeInternal; case Glyph.TypeParameter: return KnownMonikers.Type; case Glyph.Snippet: return KnownMonikers.Snippet; case Glyph.CompletionWarning: return KnownMonikers.IntellisenseWarning; case Glyph.NuGet: return KnownMonikers.NuGet; default: throw new ArgumentException("glyph"); } } } }
/* * Copyright 2012-2013 DigitasLBi Netherlands B.V. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Xml.Linq; using System.Xml.XPath; namespace LBi.LostDoc.ConsoleApplication { internal class ConsolidatedConsoleTraceListener : TraceListener, IEnumerable<TraceSource> { private readonly List<TraceSource> _sources; private readonly Dictionary<string, string> _aliasMap; private readonly ConcurrentDictionary<string, long> _startedTasks; public ConsolidatedConsoleTraceListener() { this._sources = new List<TraceSource>(); this._aliasMap = new Dictionary<string, string>(); this._startedTasks = new ConcurrentDictionary<string, long>(); } public void Add(TraceSource traceSource, string alias) { _sources.Add(traceSource); this._aliasMap.Add(traceSource.Name, alias); traceSource.Listeners.Add(this); } protected override void Dispose(bool disposing) { if (disposing) { foreach (TraceSource traceSource in this._sources) traceSource.Listeners.Remove(this); } base.Dispose(disposing); } public override void Write(string message) { Console.Write(message); } public override void WriteLine(string message) { Console.WriteLine(message); } public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) { this.TraceData(eventCache, source, eventType, id, new[] { data }); } public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, params object[] data) { if (this.Filter != null && !this.Filter.ShouldTrace(eventCache, source, eventType, id, string.Empty, null, null, null)) return; foreach (object obj in data) { if (obj is XPathNavigator) { using (var reader = ((XPathNavigator)obj).ReadSubtree()) { reader.MoveToContent(); if (reader.IsStartElement()) Console.WriteLine(XElement.ReadFrom(reader).ToString(SaveOptions.OmitDuplicateNamespaces)); else { Console.WriteLine("Unable to write Xml data."); } } } else { Console.WriteLine(obj.ToString()); } } } public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id) { if (this.Filter != null && !this.Filter.ShouldTrace(eventCache, source, eventType, id, string.Empty, null, null, null)) return; this.WriteLine(source, eventType, string.Empty); } public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args) { if (this.Filter != null && !this.Filter.ShouldTrace(eventCache, source, eventType, id, format, args, null, null)) return; this.WriteLine(source, eventType, format, args); } private void WriteLine(string source, TraceEventType eventType, string format, object[] args = null) { string msg; if (args == null || args.Length == 0) msg = format; else msg = string.Format(format, args); string newSrc; if (!this._aliasMap.TryGetValue(source, out newSrc)) newSrc = source; ConsoleColor oldColor = Console.ForegroundColor; switch (eventType) { case TraceEventType.Critical: Console.ForegroundColor = ConsoleColor.Red; break; case TraceEventType.Error: Console.ForegroundColor = ConsoleColor.DarkRed; break; case TraceEventType.Warning: Console.ForegroundColor = ConsoleColor.Yellow; break; case TraceEventType.Information: Console.ForegroundColor = ConsoleColor.White; break; case TraceEventType.Verbose: Console.ForegroundColor = ConsoleColor.Gray; break; case TraceEventType.Start: Console.ForegroundColor = ConsoleColor.DarkGray; this._startedTasks.TryAdd(msg, Stopwatch.GetTimestamp()); msg = "Starting: " + msg; break; case TraceEventType.Stop: Console.ForegroundColor = ConsoleColor.DarkGray; long ts; if (this._startedTasks.TryRemove(msg, out ts)) { double seconds = (Stopwatch.GetTimestamp() - ts)/(double) Stopwatch.Frequency; msg += string.Format(" [{0:N1} seconds]", seconds); } msg = "Finished: " + msg; break; case TraceEventType.Suspend: Console.ForegroundColor = ConsoleColor.DarkGreen; break; case TraceEventType.Resume: Console.ForegroundColor = ConsoleColor.DarkGreen; break; case TraceEventType.Transfer: return; default: throw new ArgumentOutOfRangeException("eventType"); } Console.WriteLine("[{0}] {1}", newSrc, msg); // restore color Console.ForegroundColor = oldColor; } public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { if (this.Filter != null && !this.Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null)) return; this.WriteLine(source, eventType, message); } public IEnumerator<TraceSource> GetEnumerator() { return this._sources.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Text.RegularExpressions; public class Armies { private class Unit : IComparable<Unit> { public int ind, m; public string name; public Unit(string x, int index) { ind = index; string[] sp = x.Split(' '); m = int.Parse(sp[1]); name = sp[0]; } int IComparable<Unit>.CompareTo(Unit obj) { if (this.m == obj.m) return this.ind - obj.ind; else return obj.m - this.m; } } public string[] findOrder(string[] army1, string[] army2) { Unit[] l1 = new Unit[army1.Length]; for (int i = 0; i < army1.Length; i++) { l1[i] = new Unit(army1[i], i); } Unit[] l2 = new Unit[army2.Length]; for (int i = 0; i < army2.Length; i++) { l2[i] = new Unit(army2[i], i); } Array.Sort<Unit>(l1); Array.Sort<Unit>(l2); return merge(l1, l2); } private string[] merge(Unit[] army1, Unit[] army2) { int n = army1.Length; int m = army2.Length; int i = 0, j = 0, k = 0; bool prev = true; string[] ret = new string[n+m]; while (i < n && j < m) { Unit s1 = army1[i]; Unit s2 = army2[j]; int m1 = s1.m; int m2 = s2.m; if (m1 > m2) { ret[k] = s1.name; k++; i++; prev = false; } else if (m2 > m1) { ret[k] = s2.name; k++; j++; prev = true; } else { if (prev) { ret[k] = s1.name; k++; i++; } else { ret[k] = s2.name; k++; j++; } prev = !prev; } } while (i < n) { ret[k] = army1[i].name; k++; i++; } while (j < m) { ret[k] = army2[j].name; k++; j++; } return ret; } // BEGIN KAWIGIEDIT TESTING // Generated by KawigiEdit 2.1.4 (beta) modified by pivanof #region Testing code generated by KawigiEdit [STAThread] private static Boolean KawigiEdit_RunTest(int testNum, string[] p0, string[] p1, Boolean hasAnswer, string[] p2) { Console.Write("Test " + testNum + ": [" + "{"); for (int i = 0; p0.Length > i; ++i) { if (i > 0) { Console.Write(","); } Console.Write("\"" + p0[i] + "\""); } Console.Write("}" + "," + "{"); for (int i = 0; p1.Length > i; ++i) { if (i > 0) { Console.Write(","); } Console.Write("\"" + p1[i] + "\""); } Console.Write("}"); Console.WriteLine("]"); Armies obj; string[] answer; obj = new Armies(); DateTime startTime = DateTime.Now; answer = obj.findOrder(p0, p1); DateTime endTime = DateTime.Now; Boolean res; res = true; Console.WriteLine("Time: " + (endTime - startTime).TotalSeconds + " seconds"); if (hasAnswer) { Console.WriteLine("Desired answer:"); Console.Write("\t" + "{"); for (int i = 0; p2.Length > i; ++i) { if (i > 0) { Console.Write(","); } Console.Write("\"" + p2[i] + "\""); } Console.WriteLine("}"); } Console.WriteLine("Your answer:"); Console.Write("\t" + "{"); for (int i = 0; answer.Length > i; ++i) { if (i > 0) { Console.Write(","); } Console.Write("\"" + answer[i] + "\""); } Console.WriteLine("}"); if (hasAnswer) { if (answer.Length != p2.Length) { res = false; } else { for (int i = 0; answer.Length > i; ++i) { if (answer[i] != p2[i]) { res = false; } } } } if (!res) { Console.WriteLine("DOESN'T MATCH!!!!"); } else if ((endTime - startTime).TotalSeconds >= 2) { Console.WriteLine("FAIL the timeout"); res = false; } else if (hasAnswer) { Console.WriteLine("Match :-)"); } else { Console.WriteLine("OK, but is it right?"); } Console.WriteLine(""); return res; } public static void Main(string[] args) { Boolean all_right; all_right = true; string[] p0; string[] p1; string[] p2; // ----- test 0 ----- p0 = new string[]{"DRAGON 10"}; p1 = new string[]{"BOAR 1","ELF 3"}; p2 = new string[]{"DRAGON","ELF","BOAR"}; all_right = KawigiEdit_RunTest(0, p0, p1, true, p2) && all_right; // ------------------ // ----- test 1 ----- p0 = new string[]{"SWORDSMAN 5","ARCHER 3"}; p1 = new string[]{"CENTAUR 2","ELF 3"}; p2 = new string[]{"SWORDSMAN","ELF","ARCHER","CENTAUR"}; all_right = KawigiEdit_RunTest(1, p0, p1, true, p2) && all_right; // ------------------ // ----- test 2 ----- p0 = new string[]{"ARCHER 5","PIXIE 3"}; p1 = new string[]{"OGRE 10","WOLF 10","GOBLIN 3"}; p2 = new string[]{"OGRE","WOLF","ARCHER","GOBLIN","PIXIE"}; all_right = KawigiEdit_RunTest(2, p0, p1, true, p2) && all_right; // ------------------ // ----- test 3 ----- p0 = new string[]{"A 6","B 7"}; p1 = new string[]{}; p2 = new string[]{"B","A"}; all_right = KawigiEdit_RunTest(3, p0, p1, true, p2) && all_right; // ------------------ if (all_right) { Console.WriteLine("You're a stud (at least on the example cases)!"); } else { Console.WriteLine("Some of the test cases had errors."); } Console.ReadKey(); } #endregion // END KAWIGIEDIT TESTING } //Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
/* * CID0057.cs - kok culture handler. * * Copyright (c) 2003 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "kok.txt". namespace I18N.Other { using System; using System.Globalization; using I18N.Common; public class CID0057 : RootCulture { public CID0057() : base(0x0057) {} public CID0057(int culture) : base(culture) {} public override String Name { get { return "kok"; } } public override String ThreeLetterISOLanguageName { get { return "kok"; } } public override String ThreeLetterWindowsLanguageName { get { return "KNK"; } } public override String TwoLetterISOLanguageName { get { return "kok"; } } public override DateTimeFormatInfo DateTimeFormat { get { DateTimeFormatInfo dfi = base.DateTimeFormat; dfi.AMDesignator = "\u092e.\u092a\u0942."; dfi.PMDesignator = "\u092e.\u0928\u0902."; dfi.AbbreviatedDayNames = new String[] {"\u0930\u0935\u093f", "\u0938\u094b\u092e", "\u092e\u0902\u0917\u0933", "\u092c\u0941\u0927", "\u0917\u0941\u0930\u0941", "\u0936\u0941\u0915\u094d\u0930", "\u0936\u0928\u093f"}; dfi.DayNames = new String[] {"\u0906\u0926\u093f\u0924\u094d\u092f\u0935\u093e\u0930", "\u0938\u094b\u092e\u0935\u093e\u0930", "\u092e\u0902\u0917\u0933\u093e\u0930", "\u092c\u0941\u0927\u0935\u093e\u0930", "\u0917\u0941\u0930\u0941\u0935\u093e\u0930", "\u0936\u0941\u0915\u094d\u0930\u0935\u093e\u0930", "\u0936\u0928\u093f\u0935\u093e\u0930"}; dfi.AbbreviatedMonthNames = new String[] {"\u091c\u093e\u0928\u0947\u0935\u093e\u0930\u0940", "\u092b\u0947\u092c\u0943\u0935\u093e\u0930\u0940", "\u092e\u093e\u0930\u094d\u091a", "\u090f\u092a\u094d\u0930\u093f\u0932", "\u092e\u0947", "\u091c\u0942\u0928", "\u091c\u0941\u0932\u0948", "\u0913\u0917\u0938\u094d\u091f", "\u0938\u0947\u092a\u094d\u091f\u0947\u0902\u092c\u0930", "\u0913\u0915\u094d\u091f\u094b\u092c\u0930", "\u0928\u094b\u0935\u094d\u0939\u0947\u0902\u092c\u0930", "\u0921\u093f\u0938\u0947\u0902\u092c\u0930", ""}; dfi.MonthNames = new String[] {"\u091c\u093e\u0928\u0947\u0935\u093e\u0930\u0940", "\u092b\u0947\u092c\u094d\u0930\u0941\u0935\u093e\u0930\u0940", "\u092e\u093e\u0930\u094d\u091a", "\u090f\u092a\u094d\u0930\u093f\u0932", "\u092e\u0947", "\u091c\u0942\u0928", "\u091c\u0941\u0932\u0948", "\u0913\u0917\u0938\u094d\u091f", "\u0938\u0947\u092a\u094d\u091f\u0947\u0902\u092c\u0930", "\u0913\u0915\u094d\u091f\u094b\u092c\u0930", "\u0928\u094b\u0935\u094d\u0939\u0947\u0902\u092c\u0930", "\u0921\u093f\u0938\u0947\u0902\u092c\u0930", ""}; return dfi; } set { base.DateTimeFormat = value; // not used } } public override String ResolveLanguage(String name) { switch(name) { case "aa": return "\u0905\u092b\u093e\u0930"; case "ab": return "\u0905\u092c\u0916\u0947\u091c\u093c\u093f\u092f\u0928"; case "af": return "\u0905\u092b\u094d\u0930\u093f\u0915\u093e\u0928\u094d\u0938"; case "am": return "\u0905\u092e\u0939\u093e\u0930\u093f\u0915\u094d"; case "ar": return "\u0905\u0930\u0947\u092c\u093f\u0915\u094d"; case "as": return "\u0905\u0938\u093e\u092e\u0940"; case "ay": return "\u0910\u092e\u0930\u093e"; case "az": return "\u0905\u091c\u093c\u0930\u092c\u0948\u091c\u093e\u0928\u0940"; case "ba": return "\u092c\u0937\u094d\u0915\u093f\u0930"; case "be": return "\u092c\u0948\u0932\u094b\u0930\u0941\u0938\u093f\u092f\u0928\u094d"; case "bg": return "\u092c\u0932\u094d\u0917\u0947\u0930\u093f\u092f\u0928"; case "bh": return "\u092c\u0940\u0939\u093e\u0930\u0940"; case "bi": return "\u092c\u093f\u0938\u0932\u092e\u093e"; case "bn": return "\u092c\u0902\u0917\u093e\u0932\u0940"; case "bo": return "\u0924\u093f\u092c\u0947\u0924\u093f\u092f\u0928"; case "br": return "\u092c\u094d\u0930\u0947\u091f\u0928"; case "ca": return "\u0915\u091f\u0932\u093e\u0928"; case "co": return "\u0915\u094b\u0930\u094d\u0936\u093f\u092f\u0928"; case "cs": return "\u091c\u093c\u0947\u0915\u094d"; case "cy": return "\u0935\u0947\u0933\u094d\u0937\u094d"; case "da": return "\u0921\u093e\u0928\u093f\u0937"; case "de": return "\u091c\u0930\u094d\u092e\u0928"; case "dz": return "\u092d\u0942\u091f\u093e\u0928\u0940"; case "el": return "\u0917\u094d\u0930\u0940\u0915\u094d"; case "en": return "\u0906\u0902\u0917\u094d\u0932"; case "eo": return "\u0907\u0938\u094d\u092a\u0930\u093e\u0928\u094d\u091f\u094b"; case "es": return "\u0938\u094d\u092a\u093e\u0928\u093f\u0937"; case "et": return "\u0907\u0938\u094d\u091f\u094b\u0928\u093f\u092f\u0928\u094d"; case "eu": return "\u092c\u093e\u0938\u094d\u0915"; case "fa": return "\u092a\u0930\u094d\u0937\u093f\u092f\u0928\u094d"; case "fi": return "\u092b\u093f\u0928\u094d\u0928\u093f\u0937\u094d"; case "fj": return "\u092b\u093f\u091c\u0940"; case "fo": return "\u092b\u0947\u0930\u094b\u0938\u094d"; case "fr": return "\u092b\u094d\u0930\u0947\u0928\u094d\u091a"; case "fy": return "\u092b\u094d\u0930\u093f\u0936\u093f\u092f\u0928\u094d"; case "ga": return "\u0910\u0930\u093f\u0937"; case "gd": return "\u0938\u094d\u0915\u093e\u091f\u0938\u094d \u0917\u0947\u0932\u093f\u0915\u094d"; case "gl": return "\u0917\u0947\u0932\u0940\u0936\u093f\u092f\u0928"; case "gn": return "\u0917\u094c\u0930\u093e\u0928\u0940"; case "gu": return "\u0917\u0941\u091c\u0930\u093e\u0924\u0940"; case "ha": return "\u0939\u094c\u0938\u093e"; case "he": return "\u0939\u0947\u092c\u094d\u0930\u0941"; case "hi": return "\u0939\u093f\u0928\u094d\u0926\u0940"; case "hr": return "\u0915\u094d\u0930\u094b\u092f\u0947\u0937\u093f\u092f\u0928\u094d"; case "hu": return "\u0939\u0902\u0917\u0947\u0930\u093f\u092f\u0928\u094d"; case "hy": return "\u0906\u0930\u094d\u092e\u0940\u0928\u093f\u092f\u0928\u094d"; case "ia": return "\u0907\u0928\u094d\u091f\u0930\u0932\u093f\u0902\u0917\u094d\u0935\u093e"; case "id": return "\u0907\u0928\u094d\u0921\u094b\u0928\u0947\u0937\u093f\u092f\u0928"; case "ie": return "\u0907\u0928\u094d\u091f\u0930\u0932\u093f\u0902\u0917\u094d"; case "ik": return "\u0907\u0928\u0942\u092a\u0947\u092f\u093e\u0915\u094d"; case "is": return "\u0906\u0908\u0938\u094d\u0932\u093e\u0928\u094d\u0921\u093f\u0915"; case "it": return "\u0907\u091f\u093e\u0932\u093f\u092f\u0928"; case "iu": return "\u0907\u0928\u094d\u092f\u0941\u0915\u091f\u094d\u091f"; case "ja": return "\u091c\u093e\u092a\u0928\u0940\u0938\u094d"; case "jv": return "\u091c\u093e\u0935\u0928\u0940\u0938\u094d"; case "ka": return "\u091c\u093e\u0930\u094d\u091c\u093f\u092f\u0928\u094d"; case "kk": return "\u0915\u091c\u093c\u0916\u094d"; case "kl": return "\u0917\u094d\u0930\u0940\u0928\u0932\u093e\u0928\u094d\u0921\u093f\u0915"; case "km": return "\u0915\u0902\u092c\u094b\u0921\u093f\u092f\u0928"; case "kn": return "\u0915\u0928\u094d\u0928\u0921\u093e"; case "ko": return "\u0915\u094b\u0930\u093f\u092f\u0928\u094d"; case "kok": return "\u0915\u094b\u0902\u0915\u0923\u0940"; case "ks": return "\u0915\u0936\u094d\u092e\u0940\u0930\u0940"; case "ku": return "\u0915\u0941\u0930\u094d\u0926\u093f\u0937"; case "ky": return "\u0915\u093f\u0930\u094d\u0917\u093f\u091c\u093c"; case "la": return "\u0932\u093e\u091f\u093f\u0928"; case "ln": return "\u0932\u093f\u0902\u0917\u093e\u0932\u093e"; case "lo": return "\u0932\u093e\u0913\u0924\u093f\u092f\u0928\u094d"; case "lt": return "\u0932\u093f\u0925\u0941\u0906\u0928\u093f\u092f\u0928\u094d"; case "lv": return "\u0932\u093e\u091f\u094d\u0935\u093f\u092f\u0928\u094d (\u0932\u0947\u091f\u094d\u091f\u093f\u0937\u094d)"; case "mg": return "\u092e\u0932\u093e\u0917\u0938\u0940"; case "mi": return "\u092e\u093e\u0913\u0930\u0940"; case "mk": return "\u092e\u0938\u0940\u0921\u094b\u0928\u093f\u092f\u0928\u094d"; case "ml": return "\u092e\u0933\u093f\u092f\u093e\u0933\u092e"; case "mn": return "\u092e\u0902\u0917\u094b\u0932\u093f\u092f\u0928\u094d"; case "mo": return "\u092e\u094b\u0932\u094d\u0921\u093e\u0935\u093f\u092f\u0928\u094d"; case "mr": return "\u092e\u0930\u093e\u0920\u0940"; case "ms": return "\u092e\u0932\u092f"; case "mt": return "\u092e\u093e\u0932\u0924\u0940\u0938\u094d"; case "my": return "\u092c\u0930\u094d\u092e\u0940\u091c\u093c\u094d"; case "na": return "\u0928\u094c\u0930\u094b"; case "ne": return "\u0928\u0947\u092a\u093e\u0933\u0940"; case "nl": return "\u0921\u091a\u094d"; case "no": return "\u0928\u094b\u0930\u094d\u0935\u0947\u091c\u093f\u092f\u0928"; case "oc": return "\u0913\u0938\u093f\u091f\u093e\u0928\u094d"; case "om": return "\u0913\u0930\u094b\u092e\u094b (\u0905\u092b\u093e\u0928)"; case "or": return "\u0913\u0930\u093f\u092f\u093e"; case "pa": return "\u092a\u0902\u091c\u093e\u092c\u0940"; case "pl": return "\u092a\u094b\u0932\u093f\u0937"; case "ps": return "\u092a\u093e\u0937\u094d\u091f\u094b (\u092a\u0941\u0937\u094d\u091f\u094b)"; case "pt": return "\u092a\u094b\u0930\u094d\u091a\u0941\u0917\u0940\u091c\u093c\u094d"; case "qu": return "\u0915\u094d\u0935\u0947\u091a\u094d\u0935\u093e"; case "rm": return "\u0930\u0939\u091f\u094b-\u0930\u094b\u092e\u093e\u0928\u094d\u0938\u094d"; case "rn": return "\u0915\u093f\u0930\u0941\u0928\u094d\u0926\u0940"; case "ro": return "\u0930\u094b\u092e\u093e\u0928\u093f\u092f\u0928\u094d"; case "ru": return "\u0930\u0937\u094d\u092f\u0928\u094d"; case "rw": return "\u0915\u093f\u0928\u094d\u092f\u093e\u0930\u094d\u0935\u093e\u0928\u094d\u0921\u093e"; case "sa": return "\u0938\u0902\u0938\u094d\u0915\u0943\u0924"; case "sd": return "\u0938\u093f\u0902\u0927\u0940"; case "sg": return "\u0938\u093e\u0902\u0917\u094d\u0930\u094b"; case "sh": return "\u0938\u0947\u0930\u094d\u092c\u094b-\u0915\u094d\u0930\u094b\u092f\u0947\u0937\u093f\u092f\u0928\u094d"; case "si": return "\u0938\u093f\u0928\u094d\u0939\u0932\u0940\u0938\u094d"; case "sk": return "\u0938\u094d\u0932\u094b\u0935\u093e\u0915"; case "sl": return "\u0938\u094d\u0932\u094b\u0935\u0947\u0928\u093f\u092f\u0928\u094d"; case "sm": return "\u0938\u092e\u094b\u0928"; case "sn": return "\u0936\u094b\u0928\u093e"; case "so": return "\u0938\u094b\u092e\u093e\u0933\u0940"; case "sq": return "\u0906\u0932\u094d\u092c\u0947\u0928\u093f\u092f\u0928\u094d"; case "sr": return "\u0938\u0947\u0930\u094d\u092c\u093f\u092f\u0928\u094d"; case "ss": return "\u0938\u093f\u0938\u094d\u0935\u093e\u0924\u0940"; case "st": return "\u0938\u0947\u0938\u094b\u0925\u094b"; case "su": return "\u0938\u0941\u0902\u0926\u0928\u0940\u0938"; case "sv": return "\u0938\u094d\u0935\u0940\u0926\u0940\u0937"; case "sw": return "\u0938\u094d\u0935\u093e\u0939\u093f\u0932\u0940"; case "ta": return "\u0924\u092e\u093f\u0933"; case "te": return "\u0924\u0947\u0932\u0941\u0917\u0942"; case "tg": return "\u0924\u091c\u093f\u0915"; case "th": return "\u0925\u093e\u0908"; case "ti": return "\u0924\u093f\u0917\u094d\u0930\u093f\u0928\u094d\u092f\u093e"; case "tk": return "\u0924\u0941\u0930\u094d\u0915\u092e\u0928"; case "tl": return "\u0924\u0917\u093e\u0932\u094b\u0917"; case "tn": return "\u0938\u0947\u0924\u094d\u0938\u094d\u0935\u093e\u0928\u093e"; case "to": return "\u0924\u094b\u0902\u0917\u093e"; case "tr": return "\u0924\u0941\u0930\u094d\u0915\u093f\u0937"; case "ts": return "\u0924\u094d\u0938\u094b\u0917\u093e"; case "tt": return "\u0924\u091f\u093e\u0930"; case "tw": return "\u0924\u094d\u0935\u093f"; case "ug": return "\u0909\u0927\u0942\u0930"; case "uk": return "\u092f\u0941\u0915\u094d\u0930\u0947\u0928\u093f\u092f\u0928\u094d"; case "ur": return "\u0909\u0930\u094d\u0926\u0942"; case "uz": return "\u0909\u091c\u093c\u092c\u0947\u0915"; case "vi": return "\u0935\u093f\u092f\u0924\u094d\u0928\u093e\u092e\u0940\u091c\u093c"; case "vo": return "\u0913\u0932\u093e\u092a\u0941\u0915"; case "wo": return "\u0909\u0932\u094b\u092b\u093c"; case "xh": return "\u091d\u093c\u094c\u0938\u093e"; case "yi": return "\u0907\u0926\u094d\u0926\u093f\u0937\u094d"; case "yo": return "\u092f\u0942\u0930\u0941\u092c\u093e"; case "za": return "\u091d\u094d\u0939\u0941\u0928\u094d\u0917"; case "zh": return "\u091a\u0940\u0928\u0940\u0938\u094d"; case "zu": return "\u091c\u0941\u0932\u0942"; } return base.ResolveLanguage(name); } public override String ResolveCountry(String name) { switch(name) { case "IN": return "\u092D\u093E\u0930\u0924"; } return base.ResolveCountry(name); } private class PrivateTextInfo : _I18NTextInfo { public PrivateTextInfo(int culture) : base(culture) {} public override int ANSICodePage { get { return 0; } } public override int EBCDICCodePage { get { return 500; } } public override int MacCodePage { get { return 2; } } public override int OEMCodePage { get { return 1; } } }; // class PrivateTextInfo public override TextInfo TextInfo { get { return new PrivateTextInfo(LCID); } } }; // class CID0057 public class CNkok : CID0057 { public CNkok() : base() {} }; // class CNkok }; // namespace I18N.Other
using System; using System.Diagnostics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace CocosSharp { public class CCParticleSystemQuad : CCParticleSystem { // ivars CCRawList<CCV3F_C4B_T2F_Quad> quads; CCPoint currentPosition; #region Properties public override int TotalParticles { set { // If we are setting the total numer of particles to a number higher // than what is allocated, we need to allocate new arrays if (value > AllocatedParticles) { if (EmitterMode == CCEmitterMode.Gravity) { GravityParticles = new CCParticleGravity[value]; if(BatchNode != null) { for (int i = 0; i < value; i++) { GravityParticles[i].AtlasIndex = i; } } } else { RadialParticles = new CCParticleRadial[value]; if(BatchNode != null) { for (int i = 0; i < value; i++) { RadialParticles[i].AtlasIndex = i; } } } if (Quads == null) { Quads = new CCRawList<CCV3F_C4B_T2F_Quad> (value); } else { Quads.Capacity = value; } AllocatedParticles = value; base.TotalParticles = value; } else { base.TotalParticles = value; } } } public override CCTexture2D Texture { set { if (value == null) return; // Only update the texture if is different from the current one if (Texture == null || value.Name != Texture.Name) { base.Texture = value; CCSize s = value.ContentSizeInPixels; TextureRect = new CCRect (0, 0, s.Width, s.Height); } } } public CCRect TextureRect { set { ResetTexCoords(value); } } public override CCParticleBatchNode BatchNode { set { if (BatchNode != value) { CCParticleBatchNode oldBatch = BatchNode; base.BatchNode = value; if (value == null) { Debug.Assert (BatchNode == null, "Memory should not be alloced when not using batchNode"); Debug.Assert ((quads == null), "Memory already alloced"); Quads = new CCRawList<CCV3F_C4B_T2F_Quad> (TotalParticles); Texture = oldBatch.Texture; } else if (oldBatch == null) { var batchQuads = BatchNode.TextureAtlas.Quads.Elements; BatchNode.TextureAtlas.Dirty = true; Array.Copy(quads.Elements, 0, batchQuads, AtlasIndex, TotalParticles); Quads = null; } } } } CCRawList<CCV3F_C4B_T2F_Quad> Quads { get { return quads; } set { CCRawList<CCV3F_C4B_T2F_Quad> oldQuads = quads; quads = value; if (Texture!= null && quads != null && quads != oldQuads && Window != null) { CCSize texSize = Texture.ContentSizeInPixels; // Load the quads with tex coords ResetTexCoords(new CCRect(0.0f, 0.0f, texSize.Width, texSize.Height)); } } } #endregion Properties #region Constructors internal CCParticleSystemQuad() { } public CCParticleSystemQuad(int numberOfParticles, CCEmitterMode emitterMode=CCEmitterMode.Gravity) : base(numberOfParticles, emitterMode) { } public CCParticleSystemQuad(CCParticleSystemConfig config) : base(config) {} public CCParticleSystemQuad(string plistFile, string directoryName = null) : base(plistFile, directoryName) { int totalPart = TotalParticles; } #endregion Constructors protected override void Draw() { Debug.Assert(BatchNode == null, "draw should not be called when added to a particleBatchNode"); Window.DrawManager.BindTexture(Texture); Window.DrawManager.BlendFunc(BlendFunc); Window.DrawManager.DrawQuads(quads, 0, ParticleCount); } #region Updating quads // pointRect should be in Texture coordinates, not pixel coordinates void ResetTexCoords(CCRect texRectInPixels) { float wide = texRectInPixels.Size.Width; float high = texRectInPixels.Size.Height; if (Texture != null) { wide = Texture.PixelsWide; high = Texture.PixelsHigh; } #if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL float left = (texRectInPixels.Origin.X * 2 + 1) / (wide * 2); float bottom = (texRectInPixels.Origin.Y * 2 + 1) / (high * 2); float right = left + (texRectInPixels.Size.Width * 2 - 2) / (wide * 2); float top = bottom + (texRectInPixels.Size.Height * 2 - 2) / (high * 2); #else float left = texRectInPixels.Origin.X / wide; float bottom = texRectInPixels.Origin.Y / high; float right = left + texRectInPixels.Size.Width / wide; float top = bottom + texRectInPixels.Size.Height / high; #endif // ! CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL // Important. Textures in CocosSharp are inverted, so the Y component should be inverted float tmp = top; top = bottom; bottom = tmp; CCV3F_C4B_T2F_Quad[] rawQuads; int start, end; if (BatchNode != null) { rawQuads = BatchNode.TextureAtlas.Quads.Elements; BatchNode.TextureAtlas.Dirty = true; start = AtlasIndex; end = AtlasIndex + TotalParticles; } else { rawQuads = Quads.Elements; start = 0; end = TotalParticles; } for (int i = start; i < end; i++) { rawQuads[i].BottomLeft.TexCoords.U = left; rawQuads[i].BottomLeft.TexCoords.V = bottom; rawQuads[i].BottomRight.TexCoords.U = right; rawQuads[i].BottomRight.TexCoords.V = bottom; rawQuads[i].TopLeft.TexCoords.U = left; rawQuads[i].TopLeft.TexCoords.V = top; rawQuads[i].TopRight.TexCoords.U = right; rawQuads[i].TopRight.TexCoords.V = top; } } void UpdateQuad(ref CCV3F_C4B_T2F_Quad quad, ref CCParticleBase particle) { CCPoint newPosition; if(PositionType == CCPositionType.Free || PositionType == CCPositionType.Relative) { newPosition.X = particle.Position.X - (currentPosition.X - particle.StartPosition.X); newPosition.Y = particle.Position.Y - (currentPosition.Y - particle.StartPosition.Y); } else { newPosition = particle.Position; } // translate newPos to correct position, since matrix transform isn't performed in batchnode // don't update the particle with the new position information, it will interfere with the radius and tangential calculations if(BatchNode != null) { newPosition.X += Position.X; newPosition.Y += Position.Y; } CCColor4B color = new CCColor4B(); if(OpacityModifyRGB) { color.R = (byte) (particle.Color.R * particle.Color.A * 255); color.G = (byte) (particle.Color.G * particle.Color.A * 255); color.B = (byte) (particle.Color.B * particle.Color.A * 255); color.A = (byte)(particle.Color.A * 255); } else { color.R = (byte)(particle.Color.R * 255); color.G = (byte)(particle.Color.G * 255); color.B = (byte)(particle.Color.B * 255); color.A = (byte)(particle.Color.A * 255); } quad.BottomLeft.Colors = color; quad.BottomRight.Colors = color; quad.TopLeft.Colors = color; quad.TopRight.Colors = color; // vertices float size_2 = particle.Size / 2; if (particle.Rotation != 0.0) { float x1 = -size_2; float y1 = -size_2; float x2 = size_2; float y2 = size_2; float x = newPosition.X; float y = newPosition.Y; float r = -CCMathHelper.ToRadians(particle.Rotation); float cr = CCMathHelper.Cos(r); float sr = CCMathHelper.Sin(r); float ax = x1 * cr - y1 * sr + x; float ay = x1 * sr + y1 * cr + y; float bx = x2 * cr - y1 * sr + x; float by = x2 * sr + y1 * cr + y; float cx = x2 * cr - y2 * sr + x; float cy = x2 * sr + y2 * cr + y; float dx = x1 * cr - y2 * sr + x; float dy = x1 * sr + y2 * cr + y; // bottom-left quad.BottomLeft.Vertices.X = ax; quad.BottomLeft.Vertices.Y = ay; // bottom-right vertex: quad.BottomRight.Vertices.X = bx; quad.BottomRight.Vertices.Y = by; // top-left vertex: quad.TopLeft.Vertices.X = dx; quad.TopLeft.Vertices.Y = dy; // top-right vertex: quad.TopRight.Vertices.X = cx; quad.TopRight.Vertices.Y = cy; } else { // bottom-left vertex: quad.BottomLeft.Vertices.X = newPosition.X - size_2; quad.BottomLeft.Vertices.Y = newPosition.Y - size_2; // bottom-right vertex: quad.BottomRight.Vertices.X = newPosition.X + size_2; quad.BottomRight.Vertices.Y = newPosition.Y - size_2; // top-left vertex: quad.TopLeft.Vertices.X = newPosition.X - size_2; quad.TopLeft.Vertices.Y = newPosition.Y + size_2; // top-right vertex: quad.TopRight.Vertices.X = newPosition.X + size_2; quad.TopRight.Vertices.Y = newPosition.Y + size_2; } } public override void UpdateQuads() { if (!Visible || Layer == null) { return; } currentPosition = CCPoint.Zero; if (PositionType == CCPositionType.Free) { currentPosition = Layer.VisibleBoundsWorldspace.Origin; } else if (PositionType == CCPositionType.Relative) { currentPosition = Position; } CCV3F_C4B_T2F_Quad[] rawQuads; if (BatchNode != null) { rawQuads = BatchNode.TextureAtlas.Quads.Elements; BatchNode.TextureAtlas.Dirty = true; } else { rawQuads = Quads.Elements; } if (EmitterMode == CCEmitterMode.Gravity) { UpdateGravityParticleQuads(rawQuads); } else { UpdateRadialParticleQuads(rawQuads); } } void UpdateGravityParticleQuads(CCV3F_C4B_T2F_Quad[] rawQuads) { var count = ParticleCount; if (BatchNode != null) { for (int i = 0; i < count; i++) { UpdateQuad(ref rawQuads[AtlasIndex + GravityParticles[i].AtlasIndex], ref GravityParticles[i].ParticleBase); } } else { for (int i = 0; i < count; i++) { UpdateQuad(ref rawQuads[i], ref GravityParticles[i].ParticleBase); } } } void UpdateRadialParticleQuads(CCV3F_C4B_T2F_Quad[] rawQuads) { var count = ParticleCount; if (BatchNode != null) { for (int i = 0; i < count; i++) { UpdateQuad(ref rawQuads[AtlasIndex + RadialParticles[i].AtlasIndex], ref RadialParticles[i].ParticleBase); } } else { for (int i = 0; i < count; i++) { UpdateQuad(ref rawQuads[i], ref RadialParticles[i].ParticleBase); } } } #endregion Updating quads public CCParticleSystemQuad Clone() { var p = new CCParticleSystemQuad(TotalParticles, EmitterMode); // angle p.Angle = Angle; p.AngleVar = AngleVar; // duration p.Duration = Duration; // blend function p.BlendFunc = BlendFunc; // color p.StartColor = StartColor; p.StartColorVar = StartColorVar; p.EndColor = EndColor; p.EndColorVar = EndColorVar; // particle size p.StartSize = StartSize; p.StartSizeVar = StartSizeVar; p.EndSize = EndSize; p.EndSizeVar = EndSizeVar; // position p.Position = Position; p.PositionVar = PositionVar; // Spinning p.StartSpin = StartSpin; p.StartSpinVar = StartSpinVar; p.EndSpin = EndSpin; p.EndSpinVar = EndSpinVar; p.GravityMode = GravityMode; p.RadialMode = RadialMode; // life span p.Life = Life; p.LifeVar = LifeVar; // emission Rate p.EmissionRate = EmissionRate; p.OpacityModifyRGB = OpacityModifyRGB; p.Texture = Texture; p.AutoRemoveOnFinish = AutoRemoveOnFinish; return p; } } }
using System.Collections; using System.Collections.Generic; using System.Data.Common; using System.Globalization; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.Data.SQLite { public sealed class SQLiteDataReader : DbDataReader { public override void Close() { // NOTE: DbDataReader.Dispose calls Close, so we can't put our logic in Dispose(bool) and call Dispose() from this method. Reset(); Utility.Dispose(ref m_statementPreparer); if (m_behavior.HasFlag(CommandBehavior.CloseConnection)) { var dbConnection = m_command.Connection; m_command.Dispose(); dbConnection.Dispose(); } m_command = null; } public override bool NextResult() => NextResultAsyncCore(CancellationToken.None).Result; public override Task<bool> NextResultAsync(CancellationToken cancellationToken) => NextResultAsyncCore(cancellationToken); private Task<bool> NextResultAsyncCore(CancellationToken cancellationToken) { VerifyNotDisposed(); Reset(); m_currentStatementIndex++; m_currentStatement = m_statementPreparer.Get(m_currentStatementIndex, cancellationToken); if (m_currentStatement is null) return s_falseTask; var success = false; try { for (int i = 0; i < m_command.Parameters.Count; i++) { var parameter = m_command.Parameters[i]; var parameterName = parameter.ParameterName; int index; if (parameterName is not null) { if (parameterName[0] != '@') parameterName = "@" + parameterName; index = NativeMethods.sqlite3_bind_parameter_index(m_currentStatement, SQLiteConnection.ToNullTerminatedUtf8(parameterName)); } else { index = i + 1; } if (index > 0) { object value = parameter.Value; if (value is null || value.Equals(DBNull.Value)) ThrowOnError(NativeMethods.sqlite3_bind_null(m_currentStatement, index)); else if (value is int || (value is Enum && Enum.GetUnderlyingType(value.GetType()) == typeof(int))) ThrowOnError(NativeMethods.sqlite3_bind_int(m_currentStatement, index, (int) value)); else if (value is bool boolValue) ThrowOnError(NativeMethods.sqlite3_bind_int(m_currentStatement, index, boolValue ? 1 : 0)); else if (value is string stringValue) BindText(index, stringValue); else if (value is byte[] byteArrayValue) BindBlob(index, byteArrayValue); else if (value is long longValue) ThrowOnError(NativeMethods.sqlite3_bind_int64(m_currentStatement, index, longValue)); else if (value is float floatValue) ThrowOnError(NativeMethods.sqlite3_bind_double(m_currentStatement, index, floatValue)); else if (value is double doubleValue) ThrowOnError(NativeMethods.sqlite3_bind_double(m_currentStatement, index, doubleValue)); else if (value is DateTime dateTimeValue) BindText(index, ToString(dateTimeValue)); else if (value is Guid guidValue) BindBlob(index, guidValue.ToByteArray()); else if (value is byte byteValue) ThrowOnError(NativeMethods.sqlite3_bind_int(m_currentStatement, index, byteValue)); else if (value is short shortValue) ThrowOnError(NativeMethods.sqlite3_bind_int(m_currentStatement, index, shortValue)); else BindText(index, Convert.ToString(value, CultureInfo.InvariantCulture)); } } success = true; } finally { if (!success) ThrowOnError(NativeMethods.sqlite3_reset(m_currentStatement)); } return s_trueTask; } public override bool Read() { VerifyNotDisposed(); return ReadAsyncCore(CancellationToken.None).Result; } internal static DbDataReader Create(SQLiteCommand command, CommandBehavior behavior) { DbDataReader dataReader = new SQLiteDataReader(command, behavior); dataReader.NextResult(); return dataReader; } internal static async Task<DbDataReader> CreateAsync(SQLiteCommand command, CommandBehavior behavior, CancellationToken cancellationToken) { DbDataReader dataReader = new SQLiteDataReader(command, behavior); await dataReader.NextResultAsync(cancellationToken); return dataReader; } private SQLiteDataReader(SQLiteCommand command, CommandBehavior behavior) { m_command = command; m_behavior = behavior; m_statementPreparer = command.GetStatementPreparer(); m_startingChanges = NativeMethods.sqlite3_total_changes(DatabaseHandle); m_currentStatementIndex = -1; } private Task<bool> ReadAsyncCore(CancellationToken cancellationToken) { using (cancellationToken.Register(s_interrupt, DatabaseHandle, useSynchronizationContext: false)) { while (!cancellationToken.IsCancellationRequested) { var errorCode = NativeMethods.sqlite3_step(m_currentStatement); switch (errorCode) { case SQLiteErrorCode.Done: Reset(); return s_falseTask; case SQLiteErrorCode.Row: m_hasRead = true; if (m_columnType is null) m_columnType = new DbType?[NativeMethods.sqlite3_column_count(m_currentStatement)]; return s_trueTask; case SQLiteErrorCode.Busy: case SQLiteErrorCode.Locked: case SQLiteErrorCode.CantOpen: if (cancellationToken.IsCancellationRequested) return s_canceledTask; Thread.Sleep(20); break; case SQLiteErrorCode.Interrupt: return s_canceledTask; default: throw new SQLiteException(errorCode, DatabaseHandle); } } } return cancellationToken.IsCancellationRequested ? s_canceledTask : s_trueTask; } public override bool IsClosed => m_command is null; public override int RecordsAffected => NativeMethods.sqlite3_total_changes(DatabaseHandle) - m_startingChanges; public override bool GetBoolean(int ordinal) => (bool) GetValue(ordinal); public override byte GetByte(int ordinal) => (byte) GetValue(ordinal); public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length) { var sqliteType = NativeMethods.sqlite3_column_type(m_currentStatement, ordinal); if (sqliteType == SQLiteColumnType.Null) return 0; else if (sqliteType != SQLiteColumnType.Blob) throw new InvalidCastException("Cannot convert '{0}' to bytes.".FormatInvariant(sqliteType)); int availableLength = NativeMethods.sqlite3_column_bytes(m_currentStatement, ordinal); if (buffer is null) { // this isn't required by the DbDataReader.GetBytes API documentation, but is what System.Data.SQLite does // (as does SqlDataReader: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getbytes.aspx) return availableLength; } if (bufferOffset + length > buffer.Length) throw new ArgumentException("bufferOffset + length cannot exceed buffer.Length", "length"); IntPtr ptr = NativeMethods.sqlite3_column_blob(m_currentStatement, ordinal); int lengthToCopy = Math.Min(availableLength - (int) dataOffset, length); Marshal.Copy(new IntPtr(ptr.ToInt64() + dataOffset), buffer, bufferOffset, lengthToCopy); return lengthToCopy; } public override char GetChar(int ordinal) => (char) GetValue(ordinal); public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length) => throw new NotImplementedException(); public override Guid GetGuid(int ordinal) => (Guid) GetValue(ordinal); public override short GetInt16(int ordinal) => (short) GetValue(ordinal); public override int GetInt32(int ordinal) { var value = GetValue(ordinal); return value switch { short shortValue => shortValue, long longValue => checked((int) longValue), _ => (int) value, }; } public override long GetInt64(int ordinal) { var value = GetValue(ordinal); return value switch { short shortValue => shortValue, int intValue => intValue, _ => (long) value }; } public override DateTime GetDateTime(int ordinal) => (DateTime) GetValue(ordinal); public override string GetString(int ordinal) => (string) GetValue(ordinal); public override decimal GetDecimal(int ordinal) => throw new NotImplementedException(); public override double GetDouble(int ordinal) { var value = GetValue(ordinal); return value switch { float floatValue => floatValue, _ => (double) value }; } public override float GetFloat(int ordinal) => (float) GetValue(ordinal); public override string GetName(int ordinal) { VerifyHasResult(); if (ordinal < 0 || ordinal > FieldCount) throw new ArgumentOutOfRangeException("ordinal", "value must be between 0 and {0}.".FormatInvariant(FieldCount - 1)); return SQLiteConnection.FromUtf8(NativeMethods.sqlite3_column_name(m_currentStatement, ordinal)); } public override int GetValues(object[] values) { VerifyRead(); int count = Math.Min(values.Length, FieldCount); for (int i = 0; i < count; i++) values[i] = GetValue(i); return count; } public override bool IsDBNull(int ordinal) { VerifyRead(); return NativeMethods.sqlite3_column_type(m_currentStatement, ordinal) == SQLiteColumnType.Null; } public override int FieldCount { get { VerifyNotDisposed(); return m_hasRead ? m_columnType.Length : NativeMethods.sqlite3_column_count(m_currentStatement); } } public override object this[int ordinal] => GetValue(ordinal); public override object this[string name] => GetValue(GetOrdinal(name)); public override bool HasRows { get { VerifyNotDisposed(); return m_hasRead; } } public override int GetOrdinal(string name) { VerifyHasResult(); if (m_columnNames is null) { var columnNames = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); for (int i = 0; i < FieldCount; i++) { string columnName = SQLiteConnection.FromUtf8(NativeMethods.sqlite3_column_name(m_currentStatement, i)); columnNames[columnName] = i; } m_columnNames = columnNames; } int ordinal; if (!m_columnNames.TryGetValue(name, out ordinal)) throw new IndexOutOfRangeException("The column name '{0}' does not exist in the result set.".FormatInvariant(name)); return ordinal; } public override string GetDataTypeName(int ordinal) => throw new NotSupportedException(); public override Type GetFieldType(int ordinal) => throw new NotSupportedException(); public override object GetValue(int ordinal) { VerifyRead(); if (ordinal < 0 || ordinal > FieldCount) throw new ArgumentOutOfRangeException("ordinal", "value must be between 0 and {0}.".FormatInvariant(FieldCount - 1)); // determine (and cache) the declared type of the column (e.g., from the SQL schema) DbType dbType; if (m_columnType[ordinal].HasValue) { dbType = m_columnType[ordinal].Value; } else { IntPtr declType = NativeMethods.sqlite3_column_decltype(m_currentStatement, ordinal); if (declType != IntPtr.Zero) { string type = SQLiteConnection.FromUtf8(declType); if (!s_sqlTypeToDbType.TryGetValue(type, out dbType)) throw new NotSupportedException("The data type name '{0}' is not supported.".FormatInvariant(type)); } else { dbType = DbType.Object; } m_columnType[ordinal] = dbType; } var sqliteType = NativeMethods.sqlite3_column_type(m_currentStatement, ordinal); if (dbType == DbType.Object) dbType = s_sqliteTypeToDbType[sqliteType]; switch (sqliteType) { case SQLiteColumnType.Null: return DBNull.Value; case SQLiteColumnType.Blob: var byteCount = NativeMethods.sqlite3_column_bytes(m_currentStatement, ordinal); var bytes = new byte[byteCount]; if (byteCount > 0) { var bytePointer = NativeMethods.sqlite3_column_blob(m_currentStatement, ordinal); Marshal.Copy(bytePointer, bytes, 0, byteCount); } return dbType == DbType.Guid && byteCount == 16 ? (object) new Guid(bytes) : (object) bytes; case SQLiteColumnType.Double: var doubleValue = NativeMethods.sqlite3_column_double(m_currentStatement, ordinal); return dbType == DbType.Single ? (object) (float) doubleValue : doubleValue; case SQLiteColumnType.Integer: var integerValue = NativeMethods.sqlite3_column_int64(m_currentStatement, ordinal); return dbType == DbType.Int32 ? (object) (int) integerValue : dbType == DbType.Boolean ? (object) (integerValue != 0) : dbType == DbType.Int16 ? (object) (short) integerValue : dbType == DbType.Byte ? (object) (byte) integerValue : dbType == DbType.Single ? (object) (float) integerValue : dbType == DbType.Double ? (object) (double) integerValue : (object) integerValue; case SQLiteColumnType.Text: int stringLength = NativeMethods.sqlite3_column_bytes(m_currentStatement, ordinal); var stringValue = SQLiteConnection.FromUtf8(NativeMethods.sqlite3_column_text(m_currentStatement, ordinal), stringLength); return dbType == DbType.DateTime ? (object) DateTime.ParseExact(stringValue, s_dateTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal) : (object) stringValue; default: throw new InvalidOperationException(); } } public override IEnumerator GetEnumerator() => throw new NotSupportedException(); public override DataTable GetSchemaTable() => throw new NotSupportedException(); public override int Depth => throw new NotSupportedException(); protected override DbDataReader GetDbDataReader(int ordinal) => throw new NotSupportedException(); public override Type GetProviderSpecificFieldType(int ordinal) => throw new NotSupportedException(); public override object GetProviderSpecificValue(int ordinal) => throw new NotSupportedException(); public override int GetProviderSpecificValues(object[] values) => throw new NotSupportedException(); public override Task<T> GetFieldValueAsync<T>(int ordinal, CancellationToken cancellationToken) => throw new NotSupportedException(); public override Task<bool> IsDBNullAsync(int ordinal, CancellationToken cancellationToken) => throw new NotSupportedException(); public override Task<bool> ReadAsync(CancellationToken cancellationToken) { VerifyNotDisposed(); return ReadAsyncCore(cancellationToken); } public override int VisibleFieldCount => FieldCount; private SqliteDatabaseHandle DatabaseHandle => ((SQLiteConnection) m_command.Connection).Handle; private static readonly Action<object> s_interrupt = obj => NativeMethods.sqlite3_interrupt((SqliteDatabaseHandle) obj); private void Reset() { if (m_currentStatement is not null) NativeMethods.sqlite3_reset(m_currentStatement); m_currentStatement = null; m_columnNames = null; m_columnType = null; m_hasRead = false; } private void VerifyHasResult() { VerifyNotDisposed(); if (m_currentStatement is null) throw new InvalidOperationException("There is no current result set."); } private void VerifyRead() { VerifyHasResult(); if (!m_hasRead) throw new InvalidOperationException("Read must be called first."); } private void VerifyNotDisposed() { if (m_command is null) throw new ObjectDisposedException(GetType().Name); } private void BindBlob(int ordinal, byte[] blob) => ThrowOnError(NativeMethods.sqlite3_bind_blob(m_currentStatement, ordinal, blob, blob.Length, s_sqliteTransient)); private void BindText(int ordinal, string text) { var bytes = SQLiteConnection.ToUtf8(text); ThrowOnError(NativeMethods.sqlite3_bind_text(m_currentStatement, ordinal, bytes, bytes.Length, s_sqliteTransient)); } private void ThrowOnError(SQLiteErrorCode errorCode) { if (errorCode != SQLiteErrorCode.Ok) throw new SQLiteException(errorCode, DatabaseHandle); } private static string ToString(DateTime dateTime) { // these are the System.Data.SQLite default format strings (from SQLiteConvert.cs) var formatString = dateTime.Kind == DateTimeKind.Utc ? "yyyy-MM-dd HH:mm:ss.FFFFFFFK" : "yyyy-MM-dd HH:mm:ss.FFFFFFF"; return dateTime.ToString(formatString, CultureInfo.InvariantCulture); } private static Task<bool> CreateCanceledTask() { var source = new TaskCompletionSource<bool>(); source.SetCanceled(); return source.Task; } static readonly Dictionary<string, DbType> s_sqlTypeToDbType = new Dictionary<string, DbType>(StringComparer.OrdinalIgnoreCase) { { "bigint", DbType.Int64 }, { "bit", DbType.Boolean }, { "blob", DbType.Binary }, { "bool", DbType.Boolean }, { "boolean", DbType.Boolean }, { "datetime", DbType.DateTime }, { "double", DbType.Double }, { "float", DbType.Double }, { "guid", DbType.Guid }, { "int", DbType.Int32 }, { "integer", DbType.Int64 }, { "long", DbType.Int64 }, { "real", DbType.Double }, { "single", DbType.Single}, { "string", DbType.String }, { "text", DbType.String }, }; static readonly Dictionary<SQLiteColumnType, DbType> s_sqliteTypeToDbType = new Dictionary<SQLiteColumnType, DbType>() { { SQLiteColumnType.Integer, DbType.Int64 }, { SQLiteColumnType.Blob, DbType.Binary }, { SQLiteColumnType.Text, DbType.String }, { SQLiteColumnType.Double, DbType.Double }, { SQLiteColumnType.Null, DbType.Object } }; static readonly string[] s_dateTimeFormats = { "THHmmssK", "THHmmK", "HH:mm:ss.FFFFFFFK", "HH:mm:ssK", "HH:mmK", "yyyy-MM-dd HH:mm:ss.FFFFFFFK", "yyyy-MM-dd HH:mm:ssK", "yyyy-MM-dd HH:mmK", "yyyy-MM-ddTHH:mm:ss.FFFFFFFK", "yyyy-MM-ddTHH:mmK", "yyyy-MM-ddTHH:mm:ssK", "yyyyMMddHHmmssK", "yyyyMMddHHmmK", "yyyyMMddTHHmmssFFFFFFFK", "THHmmss", "THHmm", "HH:mm:ss.FFFFFFF", "HH:mm:ss", "HH:mm", "yyyy-MM-dd HH:mm:ss.FFFFFFF", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-ddTHH:mm:ss.FFFFFFF", "yyyy-MM-ddTHH:mm", "yyyy-MM-ddTHH:mm:ss", "yyyyMMddHHmmss", "yyyyMMddHHmm", "yyyyMMddTHHmmssFFFFFFF", "yyyy-MM-dd", "yyyyMMdd", "yy-MM-dd" }; static readonly IntPtr s_sqliteTransient = new IntPtr(-1); static readonly Task<bool> s_canceledTask = CreateCanceledTask(); static readonly Task<bool> s_falseTask = Task.FromResult(false); static readonly Task<bool> s_trueTask = Task.FromResult(true); SQLiteCommand m_command; readonly CommandBehavior m_behavior; readonly int m_startingChanges; SqliteStatementPreparer m_statementPreparer; int m_currentStatementIndex; SqliteStatementHandle m_currentStatement; bool m_hasRead; DbType?[] m_columnType; Dictionary<string, int> m_columnNames; } }
namespace Microsoft.Protocols.TestSuites.MS_ASHTTP { using System; using System.Collections.ObjectModel; using System.Text; using Microsoft.Protocols.TestSuites.Common; using Request = Microsoft.Protocols.TestSuites.Common.Request; using Response = Microsoft.Protocols.TestSuites.Common.Response; /// <summary> /// A class contains all helper methods used in test cases. /// </summary> public static class TestSuiteHelper { /// <summary> /// Get status code from web exception which will be returned by IIS. /// </summary> /// <param name="webException">Web exception</param> /// <returns>Status code</returns> public static string GetStatusCodeFromException(Exception webException) { if (null == webException) { return string.Empty; } string exceptionMessage = webException.Message; string statusCode = string.Empty; if (exceptionMessage.Contains("(") && exceptionMessage.Contains(")")) { int leftParenthesis = exceptionMessage.IndexOf("(", StringComparison.OrdinalIgnoreCase); int rightParenthesis = exceptionMessage.IndexOf(")", StringComparison.OrdinalIgnoreCase); statusCode = exceptionMessage.Substring(leftParenthesis + 1, rightParenthesis - leftParenthesis - 1); } return statusCode; } /// <summary> /// Convert the instance of SendStringResponse to SyncResponse. /// </summary> /// <param name="syncResponseString">The SendStringResponse instance to convert.</param> /// <returns>The instance of SyncResponse.</returns> public static SyncResponse ConvertSyncResponseFromSendString(ActiveSyncResponseBase<object> syncResponseString) { SyncResponse syncResponse = new SyncResponse { ResponseDataXML = syncResponseString.ResponseDataXML, Headers = syncResponseString.Headers }; syncResponse.DeserializeResponseData(); return syncResponse; } /// <summary> /// Get policy key from Provision string response. /// </summary> /// <param name="provisionResponseString">The SendStringResponse instance of Provision command.</param> /// <returns>The policy key of the policy.</returns> public static string GetPolicyKeyFromSendString(ActiveSyncResponseBase<object> provisionResponseString) { ProvisionResponse provisionResponse = new ProvisionResponse { ResponseDataXML = provisionResponseString.ResponseDataXML }; if (!string.IsNullOrEmpty(provisionResponse.ResponseDataXML)) { provisionResponse.DeserializeResponseData(); if (provisionResponse.ResponseData.Policies != null) { Response.ProvisionPoliciesPolicy policyInResponse = provisionResponse.ResponseData.Policies.Policy; if (policyInResponse != null) { return policyInResponse.PolicyKey; } } } return string.Empty; } /// <summary> /// Get the request of Sync command. /// </summary> /// <param name="collectionId">The CollectionId of the folder to sync.</param> /// <param name="syncKey">The SyncKey of the latest sync.</param> /// <returns>The request of Sync command.</returns> public static SyncRequest GetSyncRequest(string collectionId, string syncKey) { // Create the Sync command request. Request.SyncCollection[] synCollections = new Request.SyncCollection[1]; synCollections[0] = new Request.SyncCollection { SyncKey = syncKey, CollectionId = collectionId }; SyncRequest syncRequest = Common.CreateSyncRequest(synCollections); return syncRequest; } /// <summary> /// Load sync response to sync store. /// </summary> /// <param name="response">The response of Sync command.</param> /// <returns>The sync store instance.</returns> public static SyncStore LoadSyncResponse(ActiveSyncResponseBase<Response.Sync> response) { if (response.ResponseData.Item == null) { return null; } SyncStore result = new SyncStore(); Response.SyncCollectionsCollection collection = ((Response.SyncCollections)response.ResponseData.Item).Collection[0]; for (int i = 0; i < collection.ItemsElementName.Length; i++) { switch (collection.ItemsElementName[i]) { case Response.ItemsChoiceType10.CollectionId: result.CollectionId = collection.Items[i].ToString(); break; case Response.ItemsChoiceType10.SyncKey: result.SyncKey = collection.Items[i].ToString(); break; case Response.ItemsChoiceType10.Status: result.Status = Convert.ToByte(collection.Items[i]); break; case Response.ItemsChoiceType10.Commands: Response.SyncCollectionsCollectionCommands commands = collection.Items[i] as Response.SyncCollectionsCollectionCommands; if (commands != null) { foreach (SyncItem item in LoadAddCommands(commands)) { result.AddCommands.Add(item); } } break; case Response.ItemsChoiceType10.Responses: Response.SyncCollectionsCollectionResponses responses = collection.Items[i] as Response.SyncCollectionsCollectionResponses; if (responses != null) { if (responses.Add != null) { foreach (Response.SyncCollectionsCollectionResponsesAdd add in responses.Add) { result.AddResponses.Add(add); } } } break; } } return result; } /// <summary> /// Load add commands in sync response. /// </summary> /// <param name="collectionCommands">The add commands response.</param> /// <returns>The list of SyncItem in add commands.</returns> public static Collection<SyncItem> LoadAddCommands(Response.SyncCollectionsCollectionCommands collectionCommands) { if (collectionCommands.Add != null) { Collection<SyncItem> commands = new Collection<SyncItem>(); if (collectionCommands.Add.Length > 0) { foreach (Response.SyncCollectionsCollectionCommandsAdd addCommand in collectionCommands.Add) { SyncItem syncItem = new SyncItem { ServerId = addCommand.ServerId }; for (int i = 0; i < addCommand.ApplicationData.ItemsElementName.Length; i++) { switch (addCommand.ApplicationData.ItemsElementName[i]) { case Response.ItemsChoiceType8.Subject1: syncItem.Subject = addCommand.ApplicationData.Items[i].ToString(); break; case Response.ItemsChoiceType8.Subject: syncItem.Subject = addCommand.ApplicationData.Items[i].ToString(); break; } } commands.Add(syncItem); } } return commands; } else { return null; } } /// <summary> /// Get ServerId from Sync response. /// </summary> /// <param name="syncResponse">The response of Sync command.</param> /// <param name="subject">The subject of the email to get.</param> /// <returns>The ServerId of the email.</returns> public static string GetServerIdFromSyncResponse(SyncStore syncResponse, string subject) { string itemServerId = null; foreach (SyncItem add in syncResponse.AddCommands) { if (add.Subject == subject) { itemServerId = add.ServerId; break; } } return itemServerId; } /// <summary> /// Verify whether X-MS-RP, MS-ASProtocolCommands and MS-ASProtocolVersions headers all exist in response headers. /// </summary> /// <param name="headers">The headers returned from response.</param> /// <returns>Whether the X-MS-RP, MS-ASProtocolCommands and MS-ASProtocolVersions headers all exist in FolderSync response header.</returns> public static bool VerifySyncRequiredResponseHeaders(string[] headers) { bool headerRP = false; bool headerASProtocolCommands = false; bool headerASProtocolVersions = false; foreach (string header in headers) { if (header == "X-MS-RP") { headerRP = true; } if (header == "MS-ASProtocolCommands") { headerASProtocolCommands = true; } if (header == "MS-ASProtocolVersions") { headerASProtocolVersions = true; } } return headerRP && headerASProtocolCommands && headerASProtocolVersions; } /// <summary> /// Get whether retry is needed when get ServerId. /// </summary> /// <param name="shouldBeGotten">Whether the item should be gotten.</param> /// <returns>If the retry is needed, return true, otherwise, return false.</returns> public static bool IsRetryNeeded(string shouldBeGotten) { if (shouldBeGotten == "T" || shouldBeGotten == "1") { return true; } return false; } /// <summary> /// Get the calendar content string. /// </summary> /// <param name="fromAddress">The email address of the meeting request sender.</param> /// <param name="toAddress">The email address of the meeting request receiver.</param> /// <param name="meetingRequestSubject">The subject of the meeting request.</param> /// <param name="occurrences">The number of occurrences of the meeting request.</param> /// <returns>The created meeting request mime.</returns> public static string CreateCalendarContent(string fromAddress, string toAddress, string meetingRequestSubject, string occurrences) { System.Text.StringBuilder icsBuilder = new System.Text.StringBuilder(); icsBuilder.AppendLine("BEGIN:VCALENDAR"); icsBuilder.AppendLine("PRODID:-//Microsoft Protocols TestSuites"); icsBuilder.AppendLine("VERSION:2.0"); icsBuilder.AppendLine("METHOD:REQUEST"); icsBuilder.AppendLine("X-MS-OLK-FORCEINSPECTOROPEN:TRUE"); icsBuilder.AppendLine("BEGIN:VTIMEZONE"); icsBuilder.AppendLine("TZID:Universal Time"); icsBuilder.AppendLine("BEGIN:STANDARD"); icsBuilder.AppendLine("DTSTART:16011104T020000"); icsBuilder.AppendLine("RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=11"); icsBuilder.AppendLine("TZOFFSETFROM:-0000"); icsBuilder.AppendLine("TZOFFSETTO:+0000"); icsBuilder.AppendLine("END:STANDARD"); icsBuilder.AppendLine("BEGIN:DAYLIGHT"); icsBuilder.AppendLine("DTSTART:16010311T020000"); icsBuilder.AppendLine("RRULE:FREQ=YEARLY;BYDAY=2SU;BYMONTH=3"); icsBuilder.AppendLine("TZOFFSETFROM:-0000"); icsBuilder.AppendLine("TZOFFSETTO:+0000"); icsBuilder.AppendLine("END:DAYLIGHT"); icsBuilder.AppendLine("END:VTIMEZONE"); icsBuilder.AppendLine("BEGIN:VEVENT"); icsBuilder.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHH0000Z}", DateTime.UtcNow.AddHours(1))); icsBuilder.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow)); icsBuilder.AppendLine(string.Format("DTEND:{0:yyyyMMddTHH0000Z}", DateTime.UtcNow.AddHours(2))); icsBuilder.AppendLine(string.Format("LOCATION:{0}", "Meeting room one")); icsBuilder.AppendLine(string.Format("UID:{0}", Guid.NewGuid().ToString())); icsBuilder.AppendLine(string.Format("DESCRIPTION:Meeting Request")); icsBuilder.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:Meeting Request")); icsBuilder.AppendLine(string.Format("SUMMARY:{0}", meetingRequestSubject)); icsBuilder.AppendLine(string.Format("ORGANIZER:MAILTO:{0}", fromAddress)); icsBuilder.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", toAddress.Split('@')[0], toAddress)); if (!string.IsNullOrEmpty(occurrences)) { icsBuilder.AppendLine("RRULE:FREQ=DAILY;COUNT=" + occurrences.ToString()); } icsBuilder.AppendLine("BEGIN:VALARM"); icsBuilder.AppendLine("TRIGGER:-PT15M"); icsBuilder.AppendLine("ACTION:DISPLAY"); icsBuilder.AppendLine("DESCRIPTION:Reminder"); icsBuilder.AppendLine("END:VALARM"); icsBuilder.AppendLine("END:VEVENT"); icsBuilder.AppendLine("END:VCALENDAR"); return icsBuilder.ToString(); } /// <summary> /// Try to parse the no separator time string to DateTime /// </summary> /// <param name="time">The specified DateTime string</param> /// <returns>Return the DateTime with instanceId specified format</returns> public static string ConvertInstanceIdFormat(string time) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(time.Substring(0, 4)); stringBuilder.Append("-"); stringBuilder.Append(time.Substring(4, 2)); stringBuilder.Append("-"); stringBuilder.Append(time.Substring(6, 5)); stringBuilder.Append(":"); stringBuilder.Append(time.Substring(11, 2)); stringBuilder.Append(":"); stringBuilder.Append(time.Substring(13, 2)); stringBuilder.Append(".000"); stringBuilder.Append(time.Substring(15)); return stringBuilder.ToString(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Runtime.CompilerServices; using System.Reflection; namespace System.Linq.Expressions { /// <summary> /// Represents a visitor or rewriter for expression trees. /// </summary> /// <remarks> /// This class is designed to be inherited to create more specialized /// classes whose functionality requires traversing, examining or copying /// an expression tree. /// </remarks> public abstract class ExpressionVisitor { /// <summary> /// Initializes a new instance of <see cref="ExpressionVisitor"/>. /// </summary> protected ExpressionVisitor() { } /// <summary> /// Dispatches the expression to one of the more specialized visit methods in this class. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> public virtual Expression Visit(Expression node) { if (node != null) { return node.Accept(this); } return null; } /// <summary> /// Dispatches the list of expressions to one of the more specialized visit methods in this class. /// </summary> /// <param name="nodes">The expressions to visit.</param> /// <returns>The modified expression list, if any of the elements were modified; /// otherwise, returns the original expression list.</returns> public ReadOnlyCollection<Expression> Visit(ReadOnlyCollection<Expression> nodes) { Expression[] newNodes = null; for (int i = 0, n = nodes.Count; i < n; i++) { Expression node = Visit(nodes[i]); if (newNodes != null) { newNodes[i] = node; } else if (!object.ReferenceEquals(node, nodes[i])) { newNodes = new Expression[n]; for (int j = 0; j < i; j++) { newNodes[j] = nodes[j]; } newNodes[i] = node; } } if (newNodes == null) { return nodes; } return new TrueReadOnlyCollection<Expression>(newNodes); } private Expression[] VisitArguments(IArgumentProvider nodes) { return ExpressionVisitorUtils.VisitArguments(this, nodes); } /// <summary> /// Visits all nodes in the collection using a specified element visitor. /// </summary> /// <typeparam name="T">The type of the nodes.</typeparam> /// <param name="nodes">The nodes to visit.</param> /// <param name="elementVisitor">A delegate that visits a single element, /// optionally replacing it with a new element.</param> /// <returns>The modified node list, if any of the elements were modified; /// otherwise, returns the original node list.</returns> public static ReadOnlyCollection<T> Visit<T>(ReadOnlyCollection<T> nodes, Func<T, T> elementVisitor) { T[] newNodes = null; for (int i = 0, n = nodes.Count; i < n; i++) { T node = elementVisitor(nodes[i]); if (newNodes != null) { newNodes[i] = node; } else if (!object.ReferenceEquals(node, nodes[i])) { newNodes = new T[n]; for (int j = 0; j < i; j++) { newNodes[j] = nodes[j]; } newNodes[i] = node; } } if (newNodes == null) { return nodes; } return new TrueReadOnlyCollection<T>(newNodes); } /// <summary> /// Visits an expression, casting the result back to the original expression type. /// </summary> /// <typeparam name="T">The type of the expression.</typeparam> /// <param name="node">The expression to visit.</param> /// <param name="callerName">The name of the calling method; used to report to report a better error message.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> /// <exception cref="InvalidOperationException">The visit method for this node returned a different type.</exception> public T VisitAndConvert<T>(T node, string callerName) where T : Expression { if (node == null) { return null; } node = Visit(node) as T; if (node == null) { throw Error.MustRewriteToSameNode(callerName, typeof(T), callerName); } return node; } /// <summary> /// Visits an expression, casting the result back to the original expression type. /// </summary> /// <typeparam name="T">The type of the expression.</typeparam> /// <param name="nodes">The expression to visit.</param> /// <param name="callerName">The name of the calling method; used to report to report a better error message.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> /// <exception cref="InvalidOperationException">The visit method for this node returned a different type.</exception> public ReadOnlyCollection<T> VisitAndConvert<T>(ReadOnlyCollection<T> nodes, string callerName) where T : Expression { T[] newNodes = null; for (int i = 0, n = nodes.Count; i < n; i++) { T node = Visit(nodes[i]) as T; if (node == null) { throw Error.MustRewriteToSameNode(callerName, typeof(T), callerName); } if (newNodes != null) { newNodes[i] = node; } else if (!object.ReferenceEquals(node, nodes[i])) { newNodes = new T[n]; for (int j = 0; j < i; j++) { newNodes[j] = nodes[j]; } newNodes[i] = node; } } if (newNodes == null) { return nodes; } return new TrueReadOnlyCollection<T>(newNodes); } /// <summary> /// Visits the children of the <see cref="BinaryExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitBinary(BinaryExpression node) { // Walk children in evaluation order: left, conversion, right return ValidateBinary( node, node.Update( Visit(node.Left), VisitAndConvert(node.Conversion, "VisitBinary"), Visit(node.Right) ) ); } /// <summary> /// Visits the children of the <see cref="BlockExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitBlock(BlockExpression node) { int count = node.ExpressionCount; Expression[] nodes = null; for (int i = 0; i < count; i++) { Expression oldNode = node.GetExpression(i); Expression newNode = Visit(oldNode); if (oldNode != newNode) { if (nodes == null) { nodes = new Expression[count]; } nodes[i] = newNode; } } var v = VisitAndConvert(node.Variables, "VisitBlock"); if (v == node.Variables && nodes == null) { return node; } else { for (int i = 0; i < count; i++) { if (nodes[i] == null) { nodes[i] = node.GetExpression(i); } } } return node.Rewrite(v, nodes); } /// <summary> /// Visits the children of the <see cref="ConditionalExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitConditional(ConditionalExpression node) { return node.Update(Visit(node.Test), Visit(node.IfTrue), Visit(node.IfFalse)); } /// <summary> /// Visits the <see cref="ConstantExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitConstant(ConstantExpression node) { return node; } /// <summary> /// Visits the <see cref="DebugInfoExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitDebugInfo(DebugInfoExpression node) { return node; } /// <summary> /// Visits the <see cref="DefaultExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitDefault(DefaultExpression node) { return node; } /// <summary> /// Visits the children of the extension expression. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> /// <remarks> /// This can be overridden to visit or rewrite specific extension nodes. /// If it is not overridden, this method will call <see cref="Expression.VisitChildren" />, /// which gives the node a chance to walk its children. By default, /// <see cref="Expression.VisitChildren" /> will try to reduce the node. /// </remarks> protected internal virtual Expression VisitExtension(Expression node) { return node.VisitChildren(this); } /// <summary> /// Visits the children of the <see cref="GotoExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitGoto(GotoExpression node) { return node.Update(VisitLabelTarget(node.Target), Visit(node.Value)); } /// <summary> /// Visits the children of the <see cref="InvocationExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitInvocation(InvocationExpression node) { Expression e = Visit(node.Expression); Expression[] a = VisitArguments(node); if (e == node.Expression && a == null) { return node; } return node.Rewrite(e, a); } /// <summary> /// Visits the <see cref="LabelTarget" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected virtual LabelTarget VisitLabelTarget(LabelTarget node) { return node; } /// <summary> /// Visits the children of the <see cref="LabelExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitLabel(LabelExpression node) { return node.Update(VisitLabelTarget(node.Target), Visit(node.DefaultValue)); } /// <summary> /// Visits the children of the <see cref="Expression&lt;T&gt;" />. /// </summary> /// <typeparam name="T">The type of the delegate.</typeparam> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitLambda<T>(Expression<T> node) { return VisitLambda((LambdaExpression)node); } /// <summary> /// Visits the children of the <see cref="LambdaExpression" />. /// </summary> /// <typeparam name="T">The type of the delegate.</typeparam> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitLambda(LambdaExpression node) { return node.Update(Visit(node.Body), VisitAndConvert(node.Parameters, "VisitLambda")); } /// <summary> /// Visits the children of the <see cref="LoopExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitLoop(LoopExpression node) { return node.Update(VisitLabelTarget(node.BreakLabel), VisitLabelTarget(node.ContinueLabel), Visit(node.Body)); } /// <summary> /// Visits the children of the <see cref="MemberExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitMember(MemberExpression node) { return node.Update(Visit(node.Expression)); } /// <summary> /// Visits the children of the <see cref="IndexExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitIndex(IndexExpression node) { Expression o = Visit(node.Object); Expression[] a = VisitArguments(node); if (o == node.Object && a == null) { return node; } return node.Rewrite(o, a); } /// <summary> /// Visits the children of the <see cref="MethodCallExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitMethodCall(MethodCallExpression node) { Expression o = Visit(node.Object); Expression[] a = VisitArguments((IArgumentProvider)node); if (o == node.Object && a == null) { return node; } return node.Rewrite(o, a); } /// <summary> /// Visits the children of the <see cref="NewArrayExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitNewArray(NewArrayExpression node) { return node.Update(Visit(node.Expressions)); } /// <summary> /// Visits the children of the <see cref="NewExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] protected internal virtual Expression VisitNew(NewExpression node) { return node.Update(Visit(node.Arguments)); } /// <summary> /// Visits the <see cref="ParameterExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitParameter(ParameterExpression node) { return node; } /// <summary> /// Visits the children of the <see cref="RuntimeVariablesExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitRuntimeVariables(RuntimeVariablesExpression node) { return node.Update(VisitAndConvert(node.Variables, "VisitRuntimeVariables")); } /// <summary> /// Visits the children of the <see cref="SwitchCase" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected virtual SwitchCase VisitSwitchCase(SwitchCase node) { return node.Update(Visit(node.TestValues), Visit(node.Body)); } /// <summary> /// Visits the children of the <see cref="SwitchExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitSwitch(SwitchExpression node) { return ValidateSwitch( node, node.Update( Visit(node.SwitchValue), Visit(node.Cases, VisitSwitchCase), Visit(node.DefaultBody) ) ); } /// <summary> /// Visits the children of the <see cref="CatchBlock" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected virtual CatchBlock VisitCatchBlock(CatchBlock node) { return node.Update(VisitAndConvert(node.Variable, "VisitCatchBlock"), Visit(node.Filter), Visit(node.Body)); } /// <summary> /// Visits the children of the <see cref="TryExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitTry(TryExpression node) { return node.Update( Visit(node.Body), Visit(node.Handlers, VisitCatchBlock), Visit(node.Finally), Visit(node.Fault) ); } /// <summary> /// Visits the children of the <see cref="TypeBinaryExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitTypeBinary(TypeBinaryExpression node) { return node.Update(Visit(node.Expression)); } /// <summary> /// Visits the children of the <see cref="UnaryExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitUnary(UnaryExpression node) { return ValidateUnary(node, node.Update(Visit(node.Operand))); } /// <summary> /// Visits the children of the <see cref="MemberInitExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitMemberInit(MemberInitExpression node) { return node.Update( VisitAndConvert(node.NewExpression, "VisitMemberInit"), Visit(node.Bindings, VisitMemberBinding) ); } /// <summary> /// Visits the children of the <see cref="ListInitExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitListInit(ListInitExpression node) { return node.Update( VisitAndConvert(node.NewExpression, "VisitListInit"), Visit(node.Initializers, VisitElementInit) ); } /// <summary> /// Visits the children of the <see cref="ElementInit" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected virtual ElementInit VisitElementInit(ElementInit node) { return node.Update(Visit(node.Arguments)); } /// <summary> /// Visits the children of the <see cref="MemberBinding" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected virtual MemberBinding VisitMemberBinding(MemberBinding node) { switch (node.BindingType) { case MemberBindingType.Assignment: return VisitMemberAssignment((MemberAssignment)node); case MemberBindingType.MemberBinding: return VisitMemberMemberBinding((MemberMemberBinding)node); case MemberBindingType.ListBinding: return VisitMemberListBinding((MemberListBinding)node); default: throw Error.UnhandledBindingType(node.BindingType); } } /// <summary> /// Visits the children of the <see cref="MemberAssignment" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected virtual MemberAssignment VisitMemberAssignment(MemberAssignment node) { return node.Update(Visit(node.Expression)); } /// <summary> /// Visits the children of the <see cref="MemberMemberBinding" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding node) { return node.Update(Visit(node.Bindings, VisitMemberBinding)); } /// <summary> /// Visits the children of the <see cref="MemberListBinding" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected virtual MemberListBinding VisitMemberListBinding(MemberListBinding node) { return node.Update(Visit(node.Initializers, VisitElementInit)); } // // Prevent some common cases of invalid rewrites. // // Essentially, we don't want the rewritten node to be semantically // bound by the factory, which may do the wrong thing. Instead we // require derived classes to be explicit about what they want to do if // types change. // private static UnaryExpression ValidateUnary(UnaryExpression before, UnaryExpression after) { if (before != after && before.Method == null) { if (after.Method != null) { throw Error.MustRewriteWithoutMethod(after.Method, "VisitUnary"); } // rethrow has null operand if (before.Operand != null && after.Operand != null) { ValidateChildType(before.Operand.Type, after.Operand.Type, "VisitUnary"); } } return after; } private static BinaryExpression ValidateBinary(BinaryExpression before, BinaryExpression after) { if (before != after && before.Method == null) { if (after.Method != null) { throw Error.MustRewriteWithoutMethod(after.Method, "VisitBinary"); } ValidateChildType(before.Left.Type, after.Left.Type, "VisitBinary"); ValidateChildType(before.Right.Type, after.Right.Type, "VisitBinary"); } return after; } // We wouldn't need this if switch didn't infer the method. private static SwitchExpression ValidateSwitch(SwitchExpression before, SwitchExpression after) { // If we did not have a method, we don't want to bind to one, // it might not be the right thing. if (before.Comparison == null && after.Comparison != null) { throw Error.MustRewriteWithoutMethod(after.Comparison, "VisitSwitch"); } return after; } // Value types must stay as the same type, otherwise it's now a // different operation, e.g. adding two doubles vs adding two ints. private static void ValidateChildType(Type before, Type after, string methodName) { if (before.GetTypeInfo().IsValueType) { if (TypeUtils.AreEquivalent(before, after)) { // types are the same value type return; } } else if (!after.GetTypeInfo().IsValueType) { // both are reference types return; } // Otherwise, it's an invalid type change. throw Error.MustRewriteChildToSameType(before, after, methodName); } } }
//////////////////////////////////////////////////////////////// // // // Neoforce Controls // // // //////////////////////////////////////////////////////////////// // // // File: ComboBox.cs // // // // Version: 0.7 // // // // Date: 11/09/2010 // // // // Author: Tom Shane // // // //////////////////////////////////////////////////////////////// // // // Copyright (c) by Tom Shane // // // //////////////////////////////////////////////////////////////// #region //// Using ///////////// using System.Collections.Generic; //////////////////////////////////////////////////////////////////////////// using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using System; using Microsoft.Xna.Framework.Graphics; //////////////////////////////////////////////////////////////////////////// #endregion namespace TomShane.Neoforce.Controls { public class ComboBox: TextBox { #region //// Fields //////////// //////////////////////////////////////////////////////////////////////////// private Button btnDown = null; private List<object> items = new List<object>(); private ListBox lstCombo = null; private int maxItems = 5; private bool drawSelection = true; //////////////////////////////////////////////////////////////////////////// #endregion #region //// Properties //////// //////////////////////////////////////////////////////////////////////////// public override bool ReadOnly { get { return base.ReadOnly; } set { base.ReadOnly = value; CaretVisible = !value; if (value) { #if (!XBOX && !XBOX_FAKE) Cursor = Manager.Skin.Cursors["Default"].Resource; #endif } else { #if (!XBOX && !XBOX_FAKE) Cursor = Manager.Skin.Cursors["Text"].Resource; #endif } } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public bool DrawSelection { get { return drawSelection; } set { drawSelection = value; } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public override string Text { get { return base.Text; } set { base.Text = value; //if (!items.Contains(value)) --- bug if (!items.ConvertAll(item => item.ToString()).Contains(value)) { ItemIndex = -1; } } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual List<object> Items { get { return items; } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public int MaxItems { get { return maxItems; } set { if (maxItems != value) { maxItems = value; if (!Suspended) OnMaxItemsChanged(new EventArgs()); } } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public int ItemIndex { get { return lstCombo.ItemIndex; } set { if (lstCombo != null) { if (value >= 0 && value < items.Count) { lstCombo.ItemIndex = value; Text = lstCombo.Items[value].ToString(); } else { lstCombo.ItemIndex = -1; } } if (!Suspended) OnItemIndexChanged(new EventArgs()); } } //////////////////////////////////////////////////////////////////////////// #endregion #region //// Events //////////// //////////////////////////////////////////////////////////////////////////// public event EventHandler MaxItemsChanged; public event EventHandler ItemIndexChanged; //////////////////////////////////////////////////////////////////////////// #endregion #region //// Construstors ////// //////////////////////////////////////////////////////////////////////////// public ComboBox(Manager manager): base(manager) { Height = 20; Width = 64; ReadOnly = true; btnDown = new Button(Manager); btnDown.Init(); btnDown.Skin = new SkinControl(Manager.Skin.Controls["ComboBox.Button"]); btnDown.CanFocus = false; btnDown.Click += new EventHandler(btnDown_Click); Add(btnDown, false); lstCombo = new ListBox(Manager); lstCombo.Init(); lstCombo.HotTrack = true; lstCombo.Detached = true; lstCombo.Visible = false; lstCombo.Click += new EventHandler(lstCombo_Click); lstCombo.FocusLost += new EventHandler(lstCombo_FocusLost); lstCombo.Items = items; manager.Input.MouseDown += new MouseEventHandler(Input_MouseDown); } //////////////////////////////////////////////////////////////////////////// #endregion #region //// Destructors /////// //////////////////////////////////////////////////////////////////////////// protected override void Dispose(bool disposing) { if (disposing) { // We added the listbox to another parent than this control, so we dispose it manually if (lstCombo != null) { lstCombo.Dispose(); lstCombo = null; } Manager.Input.MouseDown -= Input_MouseDown; } base.Dispose(disposing); } //////////////////////////////////////////////////////////////////////////// #endregion #region //// Methods /////////// //////////////////////////////////////////////////////////////////////////// public override void Init() { base.Init(); lstCombo.Skin = new SkinControl(Manager.Skin.Controls["ComboBox.ListBox"]); btnDown.Glyph = new Glyph(Manager.Skin.Images["Shared.ArrowDown"].Resource); btnDown.Glyph.Color = Manager.Skin.Controls["ComboBox.Button"].Layers["Control"].Text.Colors.Enabled; btnDown.Glyph.SizeMode = SizeMode.Centered; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected internal override void InitSkin() { base.InitSkin(); Skin = new SkinControl(Manager.Skin.Controls["ComboBox"]); AdjustMargins(); ReadOnly = ReadOnly; // To init the right cursor } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void DrawControl(Renderer renderer, Rectangle rect, GameTime gameTime) { base.DrawControl(renderer, rect, gameTime); if (ReadOnly && (Focused || lstCombo.Focused) && drawSelection) { SkinLayer lr = Skin.Layers[0]; Rectangle rc = new Rectangle(rect.Left + lr.ContentMargins.Left, rect.Top + lr.ContentMargins.Top, Width - lr.ContentMargins.Horizontal - btnDown.Width, Height - lr.ContentMargins.Vertical); renderer.Draw(Manager.Skin.Images["ListBox.Selection"].Resource, rc , Color.FromNonPremultiplied(255, 255, 255, 128)); } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void OnResize(ResizeEventArgs e) { base.OnResize(e); if (btnDown != null) { btnDown.Width = 16; btnDown.Height = Height - Skin.Layers[0].ContentMargins.Vertical; btnDown.Top = Skin.Layers[0].ContentMargins.Top; btnDown.Left = Width - btnDown.Width - 2; } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// void btnDown_Click(object sender, EventArgs e) { if (items != null && items.Count > 0) { if (this.Root != null && this.Root is Container) { (this.Root as Container).Add(lstCombo, false); lstCombo.Alpha = Root.Alpha; lstCombo.Left = AbsoluteLeft - Root.Left; lstCombo.Top = AbsoluteTop - Root.Top + Height + 1; } else { Manager.Add(lstCombo); lstCombo.Alpha = Alpha; lstCombo.Left = AbsoluteLeft; lstCombo.Top = AbsoluteTop + Height + 1; } lstCombo.AutoHeight(maxItems); if (lstCombo.AbsoluteTop + lstCombo.Height > Manager.TargetHeight) { lstCombo.Top = lstCombo.Top - Height - lstCombo.Height - 2; } lstCombo.Visible = !lstCombo.Visible; lstCombo.Focused = true; lstCombo.Width = Width; lstCombo.AutoHeight(maxItems); } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// void Input_MouseDown(object sender, MouseEventArgs e) { if (ReadOnly && (e.Position.X >= AbsoluteLeft && e.Position.X <= AbsoluteLeft + Width && e.Position.Y >= AbsoluteTop && e.Position.Y <= AbsoluteTop + Height)) return; if (lstCombo.Visible && (e.Position.X < lstCombo.AbsoluteLeft || e.Position.X > lstCombo.AbsoluteLeft + lstCombo.Width || e.Position.Y < lstCombo.AbsoluteTop || e.Position.Y > lstCombo.AbsoluteTop + lstCombo.Height) && (e.Position.X < btnDown.AbsoluteLeft || e.Position.X > btnDown.AbsoluteLeft + btnDown.Width || e.Position.Y < btnDown.AbsoluteTop || e.Position.Y > btnDown.AbsoluteTop + btnDown.Height)) { //lstCombo.Visible = false; btnDown_Click(sender, e); } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// void lstCombo_Click(object sender, EventArgs e) { MouseEventArgs ex = (e is MouseEventArgs) ? (MouseEventArgs)e : new MouseEventArgs(); if (ex.Button == MouseButton.Left || ex.Button == MouseButton.None) { lstCombo.Visible = false; if (lstCombo.ItemIndex >= 0) { Text = lstCombo.Items[lstCombo.ItemIndex].ToString(); Focused = true; ItemIndex = lstCombo.ItemIndex; } } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void OnKeyDown(KeyEventArgs e) { if (e.Key == Keys.Down) { e.Handled = true; btnDown_Click(this, new MouseEventArgs()); } base.OnKeyDown(e); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void OnGamePadDown(GamePadEventArgs e) { if (!e.Handled) { if (e.Button == GamePadActions.Click || e.Button == GamePadActions.Press || e.Button == GamePadActions.Down) { e.Handled = true; btnDown_Click(this, new MouseEventArgs()); } } base.OnGamePadDown(e); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (ReadOnly && e.Button == MouseButton.Left) { btnDown_Click(this, new MouseEventArgs()); } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected virtual void OnMaxItemsChanged(EventArgs e) { if (MaxItemsChanged != null) MaxItemsChanged.Invoke(this, e); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected virtual void OnItemIndexChanged(EventArgs e) { if (ItemIndexChanged != null) ItemIndexChanged.Invoke(this, e); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// void lstCombo_FocusLost(object sender, EventArgs e) { //lstCombo.Visible = false; Invalidate(); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void AdjustMargins() { base.AdjustMargins(); ClientMargins = new Margins(ClientMargins.Left, ClientMargins.Top, ClientMargins.Right + 16, ClientMargins.Bottom); } //////////////////////////////////////////////////////////////////////////// #endregion } }
namespace Microsoft.Protocols.TestSuites.MS_ASRM { using System.Collections.Generic; using System.Globalization; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestSuites.Common.DataStructures; using Microsoft.Protocols.TestTools; using Response = Microsoft.Protocols.TestSuites.Common.Response; /// <summary> /// The class provides the methods to write capture code. /// </summary> public partial class MS_ASRMAdapter { #region Verify transport /// <summary> /// This method is used to verify transport related requirement. /// </summary> private void VerifyTransport() { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R2"); // Verify MS-ASRM requirement: MS-ASRM_R2 // ActiveSyncClient encodes XML request into WBXML and decodes WBXML to XML response, capture it directly if server responses succeed. Site.CaptureRequirement( 2, @"[In Transport] The XML markup that constitutes the request body or the response body is transmitted between client and server by using Wireless Application Protocol (WAP) Binary XML (WBXML), as specified in [MS-ASWBXML]."); } #endregion #region Verify requirements about RightsManagementLicense /// <summary> /// Verify requirements about RightsManagementLicense. /// </summary> /// <param name="rightsManagementLicense">The RightsManagementLicense element.</param> private void VerifyRightsManagementLicense(Response.RightsManagementLicense rightsManagementLicense) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R108"); // Verify MS-ASRM requirement: MS-ASRM_R108 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 108, @"[In RightsManagementLicense] The value of this element[RightsManagementLicense] is a container ([MS-ASDTYPE] section 2.2)."); this.VerifyContainer(); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R21"); // Verify MS-ASRM requirement: MS-ASRM_R21 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 21, @"[In ContentExpiryDate] The ContentExpiryDate element is a required child element of the RightsManagementLicense element (section 2.2.2.14)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R284"); // Verify MS-ASRM requirement: MS-ASRM_R284 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 284, @"[In RightsManagementLicense] [The RightsManagementLicense element can only have the following child elements:]ContentExpiryDate (section 2.2.2.1). This element is required."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R27"); // Verify MS-ASRM requirement: MS-ASRM_R27 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 27, @"[In ContentExpiryDate] The value of this element[ContentExpiryDate] is a dateTime ([MS-ASDTYPE] section 2.3)."); this.VerifyDateTime(); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R28"); // Verify MS-ASRM requirement: MS-ASRM_R28 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 28, @"[In ContentExpiryDate] The ContentExpiryDate element has no child elements."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R29"); // Verify MS-ASRM requirement: MS-ASRM_R29 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 29, @"[In ContentOwner] The ContentOwner element is a required child element of the RightsManagementLicense element (section 2.2.2.14)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R285"); // Verify MS-ASRM requirement: MS-ASRM_R285 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 285, @"[In RightsManagementLicense] [The RightsManagementLicense element can only have the following child elements:]ContentOwner (section 2.2.2.2). This element is required."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R32"); // Verify MS-ASRM requirement: MS-ASRM_R32 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 32, @"[In ContentOwner] The value of this element[ContentOwner] is a NonEmptyStringType, as specified in section 2.2."); this.VerifyNonEmptyString(rightsManagementLicense.ContentOwner); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R33"); // Verify MS-ASRM requirement: MS-ASRM_R33 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 33, @"[In ContentOwner] The ContentOwner element has no child elements."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R275, the actual length of ContentOwner element: {0}", rightsManagementLicense.ContentOwner.Length); // Verify MS-ASRM requirement: MS-ASRM_R275 Site.CaptureRequirementIfIsTrue( rightsManagementLicense.ContentOwner.Length < 320, 275, @"[In ContentOwner] The length of the ContentOwner value is less than 320 characters."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R35"); // Verify MS-ASRM requirement: MS-ASRM_R35 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 35, @"[In EditAllowed] The EditAllowed element is a required child element of the RightsManagementLicense element (section 2.2.2.14)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R286"); // Verify MS-ASRM requirement: MS-ASRM_R286 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 286, @"[In RightsManagementLicense] [The RightsManagementLicense element can only have the following child elements:]EditAllowed (section 2.2.2.3). This element is required."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R37"); // Verify MS-ASRM requirement: MS-ASRM_R37 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 37, @"[In EditAllowed] The value of this element[EditAllowed] is a boolean ([MS-ASDTYPE] section 2.1)."); this.VerifyBoolean(); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R43"); // Verify MS-ASRM requirement: MS-ASRM_R43 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 43, @"[In EditAllowed] The EditAllowed element has no child elements."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R45"); // Verify MS-ASRM requirement: MS-ASRM_R45 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 45, @"[In ExportAllowed] The ExportAllowed element is a required child element of the RightsManagementLicense element (section 2.2.2.14)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R287"); // Verify MS-ASRM requirement: MS-ASRM_R287 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 287, @"[In RightsManagementLicense] [The RightsManagementLicense element can only have the following child elements:]ExportAllowed (section 2.2.2.4). This element is required."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R47"); // Verify MS-ASRM requirement: MS-ASRM_R47 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 47, @"[In ExportAllowed] The value of this element[ExportAllowed] is a boolean ([MS-ASDTYPE] section 2.1)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R53"); // Verify MS-ASRM requirement: MS-ASRM_R53 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 53, @"[In ExportAllowed] The ExportAllowed element has no child elements."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R54"); // Verify MS-ASRM requirement: MS-ASRM_R54 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 54, @"[In ExtractAllowed] The ExtractAllowed element is a required child element of the RightsManagementLicense element (section 2.2.2.14)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R288"); // Verify MS-ASRM requirement: MS-ASRM_R288 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 288, @"[In RightsManagementLicense] [The RightsManagementLicense element can only have the following child elements:]ExtractAllowed (section 2.2.2.5). This element is required."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R56"); // Verify MS-ASRM requirement: MS-ASRM_R56 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 56, @"[In ExtractAllowed] The value of this element[ExtractAllowed] is a boolean ([MS-ASDTYPE] section 2.1)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R58"); // Verify MS-ASRM requirement: MS-ASRM_R58 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 58, @"[In ExtractAllowed] The ExtractAllowed element has no child elements."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R59"); // Verify MS-ASRM requirement: MS-ASRM_R59 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 59, @"[In ForwardAllowed] The ForwardAllowed element is a required child element of the RightsManagementLicense element (section 2.2.2.14)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R289"); // Verify MS-ASRM requirement: MS-ASRM_R289 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 289, @"[In RightsManagementLicense] [The RightsManagementLicense element can only have the following child elements:]ForwardAllowed (section 2.2.2.6). This element is required."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R61"); // Verify MS-ASRM requirement: MS-ASRM_R61 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 61, @"[In ForwardAllowed] The value of this element[ForwardAllowed] is a boolean ([MS-ASDTYPE] section 2.1)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R63"); // Verify MS-ASRM requirement: MS-ASRM_R63 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 63, @"[In ForwardAllowed] The ForwardAllowed element has no child elements."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R64"); // Verify MS-ASRM requirement: MS-ASRM_R64 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 64, @"[In ModifyRecipientsAllowed] The ModifyRecipientsAllowed element is a required child element of the RightsManagementLicense element (section 2.2.2.14)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R290"); // Verify MS-ASRM requirement: MS-ASRM_R290 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 290, @"[In RightsManagementLicense] [The RightsManagementLicense element can only have the following child elements:]ModifyRecipientsAllowed (section 2.2.2.7). This element is required."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R66"); // Verify MS-ASRM requirement: MS-ASRM_R66 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 66, @"[In ModifyRecipientsAllowed] The value of this element[ModifyRecipientsAllowed] is a boolean ([MS-ASDTYPE] section 2.1)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R68"); // Verify MS-ASRM requirement: MS-ASRM_R68 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 68, @"[In ModifyRecipientsAllowed] The ModifyRecipientsAllowed element has no child elements."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R69"); // Verify MS-ASRM requirement: MS-ASRM_R69 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 69, @"[In Owner] The Owner element is a required child element of the RightsManagementLicense element (section 2.2.2.14)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R291"); // Verify MS-ASRM requirement: MS-ASRM_R291 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 291, @"[In RightsManagementLicense] [The RightsManagementLicense element can only have the following child elements:]Owner (section 2.2.2.8). This element is required."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R71"); // Verify MS-ASRM requirement: MS-ASRM_R71 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 71, @"[In Owner] The value of this element[Owner] is a boolean ([MS-ASDTYPE] section 2.1)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R76"); // Verify MS-ASRM requirement: MS-ASRM_R76 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 76, @"[In Owner] The Owner element has no child elements."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R77"); // Verify MS-ASRM requirement: MS-ASRM_R77 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 77, @"[In PrintAllowed] The PrintAllowed element is a required child element of the RightsManagementLicense element (section 2.2.2.14)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R292"); // Verify MS-ASRM requirement: MS-ASRM_R292 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 292, @"[In RightsManagementLicense] [The RightsManagementLicense element can only have the following child elements:]PrintAllowed (section 2.2.2.9). This element is required."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R80"); // Verify MS-ASRM requirement: MS-ASRM_R80 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 80, @"[In PrintAllowed] The value of this element[PrintAllowed] is a boolean ([MS-ASDTYPE] section 2.1)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R82"); // Verify MS-ASRM requirement: MS-ASRM_R82 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 82, @"[In PrintAllowed] The PrintAllowed element has no child elements."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R83"); // Verify MS-ASRM requirement: MS-ASRM_R83 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 83, @"[In ProgrammaticAccessAllowed] The ProgrammaticAccessAllowed element is a required child element of the RightsManagementLicense element (section 2.2.2.14)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R293"); // Verify MS-ASRM requirement: MS-ASRM_R293 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 293, @"[In RightsManagementLicense][The RightsManagementLicense element can only have the following child elements:]ProgrammaticAccessAllowed (section 2.2.2.10). This element is required."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R85"); // Verify MS-ASRM requirement: MS-ASRM_R85 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 85, @"[In ProgrammaticAccessAllowed] The value of this element[ProgrammaticAccessAllowed] is a boolean ([MS-ASDTYPE] section 2.1)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R89"); // Verify MS-ASRM requirement: MS-ASRM_R89 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 89, @"[In ProgrammaticAccessAllowed] The ProgrammaticAccessAllowed element has no child elements."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R96"); // Verify MS-ASRM requirement: MS-ASRM_R96 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 96, @"[In ReplyAllAllowed] The ReplyAllAllowed element is a required child element of the RightsManagementLicense element (section 2.2.2.14)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R294"); // Verify MS-ASRM requirement: MS-ASRM_R294 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 294, @"[In RightsManagementLicense][The RightsManagementLicense element can only have the following child elements:]ReplyAllAllowed (section 2.2.2.12). This element is required."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R98"); // Verify MS-ASRM requirement: MS-ASRM_R98 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 98, @"[In ReplyAllAllowed] The value of this element[ReplyAllAllowed] is a boolean ([MS-ASDTYPE] section 2.1)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R100"); // Verify MS-ASRM requirement: MS-ASRM_R100 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 100, @"[In ReplyAllAllowed] The ReplyAllAllowed element has no child elements."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R101"); // Verify MS-ASRM requirement: MS-ASRM_R101 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 101, @"[In ReplyAllowed] The ReplyAllowed element is a required child element of the RightsManagementLicense element (section 2.2.2.14)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R295"); // Verify MS-ASRM requirement: MS-ASRM_R295 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 295, @"[In RightsManagementLicense][The RightsManagementLicense element can only have the following child elements:]ReplyAllowed (section 2.2.2.13). This element is required."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R103"); // Verify MS-ASRM requirement: MS-ASRM_R103 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 103, @"[In ReplyAllowed] The value of this element[ReplyAllowed] is a boolean ([MS-ASDTYPE] section 2.1)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R105"); // Verify MS-ASRM requirement: MS-ASRM_R105 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 105, @"[In ReplyAllowed] The ReplyAllowed element has no child elements."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R143"); // Verify MS-ASRM requirement: MS-ASRM_R143 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 143, @"[In TemplateDescription (RightsManagementLicense)] The TemplateDescription element is a required child element of the RightsManagementLicense element (section 2.2.2.14)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R296"); // Verify MS-ASRM requirement: MS-ASRM_R296 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 296, @"[In RightsManagementLicense] [The RightsManagementLicense element can only have the following child elements:]TemplateDescription (section 2.2.2.18.1). This element is required."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R142"); // Verify MS-ASRM requirement: MS-ASRM_R142 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 142, @"[In TemplateDescription] The value of this element[TemplateDescription] is a NonEmptyStringType, as specified in section 2.2."); this.VerifyNonEmptyString(rightsManagementLicense.TemplateDescription); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R146"); // Verify MS-ASRM requirement: MS-ASRM_R146 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 146, @"[In TemplateDescription (RightsManagementLicense)] The TemplateDescription element has no child elements."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R277, the actual length of TemplateDescription (RightsManagementLicense) element: {0}", rightsManagementLicense.TemplateDescription.Length); // Verify MS-ASRM requirement: MS-ASRM_R277 Site.CaptureRequirementIfIsTrue( rightsManagementLicense.TemplateDescription.Length < 10240, 277, @"[In TemplateDescription (RightsManagementLicense)] The length of the TemplateDescription[RightsManagementLicense] element is less than 10240 characters."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R307"); // Verify MS-ASRM requirement: MS-ASRM_R307 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 307, @"[In TemplateID] The value of this element[TemplateID] is a NonEmptyStringType, as specified in section 2.2."); this.VerifyNonEmptyString(rightsManagementLicense.TemplateID); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R159"); // Verify MS-ASRM requirement: MS-ASRM_R159 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 159, @"[In TemplateID (RightsManagementLicense)] The TemplateID element is a required child element of the RightsManagementLicense element (section 2.2.2.14)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R297"); // Verify MS-ASRM requirement: MS-ASRM_R297 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 297, @"[In RightsManagementLicense] [The RightsManagementLicense element can only have the following child elements:]TemplateID (section 2.2.2.19.1). This element is required."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R160"); // Verify MS-ASRM requirement: MS-ASRM_R160 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 160, @"[In TemplateID (RightsManagementLicense)] It[TemplateID] contains a string that identifies the rights policy template represented by the parent RightsManagementLicense element."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R161"); // Verify MS-ASRM requirement: MS-ASRM_R161 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 161, @"[In TemplateID (RightsManagementLicense)] The TemplateID element[RightsManagementLicense] has no child elements."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R172"); // Verify MS-ASRM requirement: MS-ASRM_R172 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 172, @"[In TemplateName] The value of this element[TemplateName] is a NonEmptyStringType, as specified in section 2.2."); this.VerifyNonEmptyString(rightsManagementLicense.TemplateName); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R173"); // Verify MS-ASRM requirement: MS-ASRM_R173 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 173, @"[In TemplateName (RightsManagementLicense)] The TemplateName element is a required child element of the RightsManagementLicense element (section 2.2.2.14)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R298"); // Verify MS-ASRM requirement: MS-ASRM_R298 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 298, @"[In RightsManagementLicense] [The RightsManagementLicense element can only have the following child elements:]TemplateName (section 2.2.2.20.1). This element is required."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R176"); // Verify MS-ASRM requirement: MS-ASRM_R176 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 176, @"[In TemplateName (RightsManagementLicense)] The TemplateName[RightsManagementLicense] element has no child elements."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R280, the actual length of TemplateName (RightsManagementLicense) element: {0}", rightsManagementLicense.TemplateName.Length); // Verify MS-ASRM requirement: MS-ASRM_R280 Site.CaptureRequirementIfIsTrue( rightsManagementLicense.TemplateName.Length < 256, 280, @"[In TemplateName (RightsManagementLicense)] The length of the TemplateName[RightsManagementLicense] element is less than 256 characters."); } #endregion #region Verify requirements about Settings response /// <summary> /// Verify the rights-managed requirements about Settings response. /// </summary> /// <param name="settingsResponse">The response of Settings command.</param> private void VerifySettingsResponse(SettingsResponse settingsResponse) { // Verify the schema of MS-ASRM. if (settingsResponse.ResponseData.RightsManagementInformation != null) { if (settingsResponse.ResponseData.RightsManagementInformation.Get != null) { this.VerifyRightsManagementTemplates(settingsResponse.ResponseData.RightsManagementInformation.Get); } } } /// <summary> /// Verify requirements about RightsManagementTemplates /// </summary> /// <param name="rightsManagementTemplatesResponse">The context of rights management templates</param> private void VerifyRightsManagementTemplates(Response.SettingsRightsManagementInformationGet rightsManagementTemplatesResponse) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R137"); // Verify MS-ASRM requirement: MS-ASRM_R137 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 137, @"[In RightsManagementTemplates] The value of this element[RightsManagementTemplates] is a container ([MS-ASDTYPE] section 2.2)."); this.VerifyContainer(); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R302"); // Verify MS-ASRM requirement: MS-ASRM_R302 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 302, @"[In RightsManagementTemplates] The RightsManagementTemplates element can only have the following child element: RightsManagementTemplate (section 2.2.2.16). "); int lengthOfArray = rightsManagementTemplatesResponse.RightsManagementTemplates.Length; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R305, the actual number of RightsManagementTemplates element: {0}", lengthOfArray); // Verify MS-ASRM requirement: MS-ASRM_R305 Site.CaptureRequirementIfIsTrue( lengthOfArray < 20, 305, @"[In RightsManagementTemplates] The RightsManagementTemplate elements returned to the client is less than 20."); for (int i = 0; i < lengthOfArray; i++) { this.VerifyRightsManagementTemplate(rightsManagementTemplatesResponse.RightsManagementTemplates[i]); } } #endregion #region Verify requirements about Sync response /// <summary> /// Verify the rights-managed requirements about Sync response. /// </summary> /// <param name="sync">The wrapper class of Sync response.</param> private void VerifySyncResponse(Sync sync) { if (sync != null) { Site.Assert.IsNotNull(sync.Email, "The expected rights-managed e-mail message should not be null."); if (sync.Email.RightsManagementLicense != null) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R208"); // Verify MS-ASRM requirement: MS-ASRM_R208 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 208, @"[In Sending Rights-Managed E-Mail Messages to the Client] To respond to a Sync command request message that includes the RightsManagementSupport element, the server includes the RightsManagementLicense element and its child elements in the Sync command response message."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R209"); // Verify MS-ASRM requirement: MS-ASRM_R209 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 209, @"[In Sending Rights-Managed E-Mail Messages to the Client] In a Sync command response, the RightsManagementLicense element is included as a child of the sync:ApplicationData element ([MS-ASCMD] section 2.2.3.11)."); this.VerifyRightsManagementLicense(sync.Email.RightsManagementLicense); } } } #endregion #region Verify requirements about ItemOperations response /// <summary> /// Verify the rights-managed requirements about ItemOperations response. /// </summary> /// <param name="itemOperationsStore">The wrapper class for the fetched result of ItemOperations command.</param> private void VerifyItemOperationsResponse(ItemOperationsStore itemOperationsStore) { foreach (ItemOperations itemOperations in itemOperationsStore.Items) { if (itemOperations.Email != null) { if (itemOperations.Email.RightsManagementLicense != null) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R210"); // Verify MS-ASRM requirement: MS-ASRM_R210 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 210, @"[In Sending Rights-Managed E-Mail Messages to the Client] In an ItemOperations command response, the RightsManagementLicense element is included as a child of the itemoperations:Properties element ([MS-ASCMD] section 2.2.3.128.1)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R410"); // Verify MS-ASRM requirement: MS-ASRM_R410 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 410, @"[In Sending Rights-Managed E-Mail Messages to the Client] To respond to an ItemOperations command request message that includes the RightsManagementSupport element, the server includes the RightsManagementLicense element and its child elements in the ItemOperations command response message."); this.VerifyRightsManagementLicense(itemOperations.Email.RightsManagementLicense); } } } } #endregion #region Verify requirements about Search response /// <summary> /// Verify the rights-managed requirements about Search response. /// </summary> /// <param name="searchStore">The wrapper class for the result of Search command.</param> private void VerifySearchResponse(SearchStore searchStore) { foreach (Search search in searchStore.Results) { if (search.Email != null) { if (search.Email.RightsManagementLicense != null) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R211"); // Verify MS-ASRM requirement: MS-ASRM_R211 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 211, @"[In Sending Rights-Managed E-Mail Messages to the Client] In a Search command response, the RightsManagementLicense element is included as a child of the search:Properties element ([MS-ASCMD] section 2.2.3.128.2)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R411"); // Verify MS-ASRM requirement: MS-ASRM_R411 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 411, @"[In Sending Rights-Managed E-Mail Messages to the Client] To respond to a Search command request message that includes the RightsManagementSupport element, the server includes the RightsManagementLicense element and its child elements in the Search command response message."); this.VerifyRightsManagementLicense(search.Email.RightsManagementLicense); } } } } #endregion #region Verify requirements about RightsManagementTemplate /// <summary> /// Verify requirements about RightsManagementTemplate included in RightsManagementTemplates. /// </summary> /// <param name="rightsManagementTemplate">The context of rights management template in RightsManagementTemplates element.</param> private void VerifyRightsManagementTemplate(Response.RightsManagementTemplatesRightsManagementTemplate rightsManagementTemplate) { if (rightsManagementTemplate != null) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R132"); // Verify MS-ASRM requirement: MS-ASRM_R132 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 132, @"[In RightsManagementTemplate] The value of this element[RightsManagementTemplate] is a container ([MS-ASDTYPE] section 2.2)."); this.VerifyContainer(); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R148"); // Verify MS-ASRM requirement: MS-ASRM_R148 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 148, @"[In TemplateDescription (RightsManagementTemplate)] The TemplateDescription element is a required child element of the RightsManagementTemplate element (section 2.2.2.16)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R133"); // Verify MS-ASRM requirement: MS-ASRM_R133 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 133, @"[In RightsManagementTemplate] [The RightsManagementTemplate element can have only one of each of the following child elements:] TemplateDescription (section 2.2.2.18.2). This element is required."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R151"); // Verify MS-ASRM requirement: MS-ASRM_R151 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 151, @"[In TemplateDescription (RightsManagementTemplate)] The TemplateDescription element has no child elements."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R278, the actual length of TemplateDescription element: {0}", rightsManagementTemplate.TemplateDescription.Length); // Verify MS-ASRM requirement: MS-ASRM_R278 Site.CaptureRequirementIfIsTrue( rightsManagementTemplate.TemplateDescription.Length < 10240, 278, @"[In TemplateDescription (RightsManagementTemplate)] The length of the TemplateDescription[RightsManagementTemplate] element is less than 10240 characters."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R162"); // Verify MS-ASRM requirement: MS-ASRM_R162 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 162, @"[In TemplateID (RightsManagementTemplate)] The TemplateID element is a required child element of the RightsManagementTemplate element (section 2.2.2.16)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R163"); // Verify MS-ASRM requirement: MS-ASRM_R163 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 163, @"[In TemplateID (RightsManagementTemplate)] It[TemplateID] contains a string that identifies the rights policy template represented by the parent RightsManagementTempalte element."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R164"); // Verify MS-ASRM requirement: MS-ASRM_R164 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 164, @"[In TemplateID (RightsManagementTemplate)] The TemplateID[RightsManagementTemplate] element has no child elements."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R134"); // Verify MS-ASRM requirement: MS-ASRM_R134 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 134, @"[In RightsManagementTemplate] [The RightsManagementTemplate element can have only one of each of the following child elements:]TemplateID (section 2.2.2.19.2). This element is required."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R178"); // Verify MS-ASRM requirement: MS-ASRM_R178 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 178, @"[In TemplateName (RightsManagementTemplate)] The TemplateName element is a required child element of the RightsManagementTemplate element (section 2.2.2.16)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R181"); // Verify MS-ASRM requirement: MS-ASRM_R181 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 181, @"[In TemplateName (RightsManagementTemplate)] The TemplateName[RightsManagementTemplate] element has no child elements."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R135"); // Verify MS-ASRM requirement: MS-ASRM_R135 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 135, @"[In RightsManagementTemplate] [The RightsManagementTemplate element can have only one of each of the following child elements:] TemplateName (section 2.2.2.20.2). This element is required."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R279, the actual length of TemplateName element: {0}", rightsManagementTemplate.TemplateName.Length); // Verify MS-ASRM requirement: MS-ASRM_R279 Site.CaptureRequirementIfIsTrue( rightsManagementTemplate.TemplateName.Length < 256, 279, @"[In TemplateName (RightsManagementTemplate)] The length of the TemplateName[RightsManagementTemplate] element is less than 256 characters."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASRM_R317"); // Verify MS-ASRM requirement: MS-ASRM_R317 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, 317, @"[In RightsManagementTemplate] The RightsManagementTemplate element can have only one of each of the following child elements[TemplateDescription, TemplateID, TemplateName]"); } } #endregion #region Verify requirements in MS-ASDTYPE /// <summary> /// This method is used to verify the boolean related requirements. /// </summary> private void VerifyBoolean() { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASDTYPE_R4"); // If the validation is successful, then MS-ASDTYPE_R4 can be captured. Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, "MS-ASDTYPE", 4, @"[In boolean Data Type] It [a boolean] is declared as an element with a type attribute of ""boolean""."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASDTYPE_R5"); // When the boolean type element successfully passed schema validation, // it is proved that the lower layer EAS client stack library did the WBXML decoding successfully,then MS-ASDTYPE_R5 can be captured. Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, "MS-ASDTYPE", 5, @"[In boolean Data Type] The value of a boolean element is an integer whose only valid values are 1 (TRUE) or 0 (FALSE)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASDTYPE_R7"); // ActiveSyncClient encodes boolean data as inline strings, so if response is successfully returned this requirement can be verified. // Verify MS-ASDTYPE requirement: MS-ASDTYPE_R7 Site.CaptureRequirement( "MS-ASDTYPE", 7, @"[In boolean Data Type] Elements with a boolean data type MUST be encoded and transmitted as [WBXML1.2] inline strings."); } /// <summary> /// This method is used to verify the container related requirements. /// </summary> private void VerifyContainer() { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASDTYPE_R8"); // Verify MS-ASDTYPE requirement: MS-ASDTYPE_R8 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, "MS-ASDTYPE", 8, @"[In container Data Type] A container is an XML element that encloses other elements but has no value of its own."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASDTYPE_R9"); // Verify MS-ASDTYPE requirement: MS-ASDTYPE_R9 Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, "MS-ASDTYPE", 9, @"[In container Data Type] It [container] is a complex type with complex content, as specified in [XMLSCHEMA1/2] section 3.4.2."); } /// <summary> /// This method is used to verify the datetime related requirements. /// </summary> private void VerifyDateTime() { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASDTYPE_R12"); // If the validation is successful, then MS-ASDTYPE_R12 can be captured. Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, "MS-ASDTYPE", 12, @"[In dateTime Data Type] It [dateTime]is declared as an element whose type attribute is set to ""dateTime""."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASDTYPE_R15"); // When the dateTime type element successfully passed schema validation, // it is proved that the lower layer EAS client stack library did the WBXML decoding successfully, then MS-ASDTYPE_R15 can be captured. Site.CaptureRequirementIfIsTrue( this.activeSyncClient.ValidationResult, "MS-ASDTYPE", 15, @"[In dateTime Data Type] All dates are given in Coordinated Universal Time (UTC) and are represented as a string in the following format. YYYY-MM-DDTHH:MM:SS.MSSZ where YYYY = Year (Gregorian calendar year) MM = Month (01 - 12) DD = Day (01 - 31) HH = Number of complete hours since midnight (00 - 24) MM = Number of complete minutes since start of hour (00 - 59) SS = Number of seconds since start of minute (00 - 59) MSS = Number of milliseconds"); // If MS-ASDTYPE_R15 can be captured successfully, then MS-ASDTYPE_R16 can be captured directly. // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASDTYPE_R16"); // Verify MS-ASDTYPE requirement: MS-ASDTYPE_R16 Site.CaptureRequirement( "MS-ASDTYPE", 16, @"[In dateTime Data Type][in YYYY-MM-DDTHH:MM:SS.MSSZ ]The T serves as a separator, and the Z indicates that this time is in UTC."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASDTYPE_R20"); // ActiveSyncClient encoded dateTime data as inline strings, so if response is successfully returned this requirement can be verified. // Verify MS-ASDTYPE requirement: MS-ASDTYPE_R20 Site.CaptureRequirement( "MS-ASDTYPE", 20, @"[In dateTime Data Type] Elements with a dateTime data type MUST be encoded and transmitted as [WBXML1.2] inline strings."); } /// <summary> /// This method is used to verify whether the string is a non-empty string. /// </summary> /// <param name="value">The string value</param> private void VerifyNonEmptyString(string value) { // Check the string length Site.Assert.IsTrue(value.Length >= 1, "The length of the string should be at least equal or greater than 1, actual length: {0}.", value.Length); } #endregion #region Verify MS-ASWBXML requirements /// <summary> /// This method is used to verify MS-ASWBXML related requirements. /// </summary> private void VerifyWBXMLCapture() { // Get decoded data and capture requirement for decode processing Dictionary<string, int> decodedData = this.activeSyncClient.GetMSASWBXMLImplementationInstance().DecodeDataCollection; if (decodedData != null) { // Check out all tag-token foreach (KeyValuePair<string, int> decodeDataItem in decodedData) { byte token; string tagName = Common.GetTagName(decodeDataItem.Key, out token); int codepage = decodeDataItem.Value; string codePageName = Common.GetCodePageName(decodeDataItem.Key); Site.Assert.IsTrue(codepage >= 0 && codepage <= 24, "Code page value should between 0-24, the actual value is :{0}", codepage); // Capture the requirements in RightsManagement namespace if (24 == codepage) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASWBXML_R34"); // Verify MS-ASWBXML requirement: MS-ASWBXML_R34 Site.CaptureRequirementIfAreEqual<string>( "rightsmanagement", codePageName.ToLower(CultureInfo.CurrentCulture), "MS-ASWBXML", 34, @"[In Code Pages] [This algorithm supports] [Code page] 24[that indicates] [XML namespace] RightsManagement"); this.VerifyRequirementsRelateToCodePage24(codepage, tagName, token); } } } } /// <summary> /// Verify the tags and tokens in WBXML code page 24. /// </summary> /// <param name="codePageNumber">The code page number.</param> /// <param name="tagName">The tag name that needs to be verified.</param> /// <param name="token">The token that needs to be verified.</param> private void VerifyRequirementsRelateToCodePage24(int codePageNumber, string tagName, byte token) { switch (tagName) { case "RightsManagementTemplates": { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASWBXML_R633"); // Verify MS-ASWBXML requirement: MS-ASWBXML_R633 Site.CaptureRequirementIfAreEqual<byte>( 0x06, token, "MS-ASWBXML", 633, @"[In Code Page 24: RightsManagement] [Tag name] RightsManagementTemplates [Token] 0x06 [supports protocol versions] 14.1, 16.0"); break; } case "RightsManagementTemplate": { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASWBXML_R634"); // Verify MS-ASWBXML requirement: MS-ASWBXML_R634 Site.CaptureRequirementIfAreEqual<byte>( 0x07, token, "MS-ASWBXML", 634, @"[In Code Page 24: RightsManagement] [Tag name] RightsManagementTemplate [Token] 0x07 [supports protocol versions] 14.1, 16.0"); break; } case "RightsManagementLicense": { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASWBXML_R635"); // Verify MS-ASWBXML requirement: MS-ASWBXML_R635 Site.CaptureRequirementIfAreEqual<byte>( 0x08, token, "MS-ASWBXML", 635, @"[In Code Page 24: RightsManagement] [Tag name] RightsManagementLicense [Token] 0x08 [supports protocol versions] 14.1, 16.0"); break; } case "EditAllowed": { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASWBXML_R636"); // Verify MS-ASWBXML requirement: MS-ASWBXML_R636 Site.CaptureRequirementIfAreEqual<byte>( 0x09, token, "MS-ASWBXML", 636, @"[In Code Page 24: RightsManagement] [Tag name] EditAllowed [Token] 0x09 [supports protocol versions] 14.1, 16.0"); break; } case "ReplyAllowed": { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASWBXML_R637"); // Verify MS-ASWBXML requirement: MS-ASWBXML_R637 Site.CaptureRequirementIfAreEqual<byte>( 0x0A, token, "MS-ASWBXML", 637, @"[In Code Page 24: RightsManagement] [Tag name] ReplyAllowed [Token] 0x0A [supports protocol versions] 14.1, 16.0"); break; } case "ReplyAllAllowed": { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASWBXML_R638"); // Verify MS-ASWBXML requirement: MS-ASWBXML_R638 Site.CaptureRequirementIfAreEqual<byte>( 0x0B, token, "MS-ASWBXML", 638, @"[In Code Page 24: RightsManagement] [Tag name] ReplyAllAllowed [Token] 0x0B [supports protocol versions] 14.1, 16.0"); break; } case "ForwardAllowed": { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASWBXML_R639"); // Verify MS-ASWBXML requirement: MS-ASWBXML_R639 Site.CaptureRequirementIfAreEqual<byte>( 0x0C, token, "MS-ASWBXML", 639, @"[In Code Page 24: RightsManagement] [Tag name] ForwardAllowed [Token] 0x0C [supports protocol versions] 14.1, 16.0"); break; } case "ModifyRecipientsAllowed": { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASWBXML_R640"); // Verify MS-ASWBXML requirement: MS-ASWBXML_R640 Site.CaptureRequirementIfAreEqual<byte>( 0x0D, token, "MS-ASWBXML", 640, @"[In Code Page 24: RightsManagement] [Tag name] ModifyRecipientsAllowed [Token] 0x0D [supports protocol versions] 14.1, 16.0"); break; } case "ExtractAllowed": { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASWBXML_R641"); // Verify MS-ASWBXML requirement: MS-ASWBXML_R641 Site.CaptureRequirementIfAreEqual<byte>( 0x0E, token, "MS-ASWBXML", 641, @"[In Code Page 24: RightsManagement] [Tag name] ExtractAllowed [Token] 0x0E [supports protocol versions] 14.1, 16.0"); break; } case "PrintAllowed": { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASWBXML_R642"); // Verify MS-ASWBXML requirement: MS-ASWBXML_R642 Site.CaptureRequirementIfAreEqual<byte>( 0x0F, token, "MS-ASWBXML", 642, @"[In Code Page 24: RightsManagement] [Tag name] PrintAllowed [Token] 0x0F [supports protocol versions] 14.1, 16.0"); break; } case "ExportAllowed": { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASWBXML_R643"); // Verify MS-ASWBXML requirement: MS-ASWBXML_R643 Site.CaptureRequirementIfAreEqual<byte>( 0x10, token, "MS-ASWBXML", 643, @"[In Code Page 24: RightsManagement] [Tag name] ExportAllowed [Token] 0x10 [supports protocol versions] 14.1, 16.0"); break; } case "ProgrammaticAccessAllowed": { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASWBXML_R644"); // Verify MS-ASWBXML requirement: MS-ASWBXML_R644 Site.CaptureRequirementIfAreEqual<byte>( 0x11, token, "MS-ASWBXML", 644, @"[In Code Page 24: RightsManagement] [Tag name] ProgrammaticAccessAllowed [Token] 0x11 [supports protocol versions] 14.1, 16.0"); break; } case "Owner": { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASWBXML_R645"); // Verify MS-ASWBXML requirement: MS-ASWBXML_R645 Site.CaptureRequirementIfAreEqual<byte>( 0x12, token, "MS-ASWBXML", 645, @"[In Code Page 24: RightsManagement] [Tag name] Owner [Token] 0x12 [supports protocol versions] 14.1, 16.0"); break; } case "ContentExpiryDate": { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASWBXML_R646"); // Verify MS-ASWBXML requirement: MS-ASWBXML_R646 Site.CaptureRequirementIfAreEqual<byte>( 0x13, token, "MS-ASWBXML", 646, @"[In Code Page 24: RightsManagement] [Tag name] ContentExpiryDate [Token] 0x13 [supports protocol versions] 14.1, 16.0"); break; } case "TemplateID": { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASWBXML_R647"); // Verify MS-ASWBXML requirement: MS-ASWBXML_R647 Site.CaptureRequirementIfAreEqual<byte>( 0x14, token, "MS-ASWBXML", 647, @"[In Code Page 24: RightsManagement] [Tag name] TemplateID [Token] 0x14 [supports protocol versions] 14.1, 16.0"); break; } case "TemplateName": { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASWBXML_R648"); // Verify MS-ASWBXML requirement: MS-ASWBXML_R648 Site.CaptureRequirementIfAreEqual<byte>( 0x15, token, "MS-ASWBXML", 648, @"[In Code Page 24: RightsManagement] [Tag name] TemplateName [Token] 0x15 [supports protocol versions] 14.1, 16.0"); break; } case "TemplateDescription": { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASWBXML_R649"); // Verify MS-ASWBXML requirement: MS-ASWBXML_R649 Site.CaptureRequirementIfAreEqual<byte>( 0x16, token, "MS-ASWBXML", 649, @"[In Code Page 24: RightsManagement] [Tag name] TemplateDescription [Token] 0x16 [supports protocol versions] 14.1, 16.0"); break; } case "ContentOwner": { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASWBXML_R650"); // Verify MS-ASWBXML requirement: MS-ASWBXML_R650 Site.CaptureRequirementIfAreEqual<byte>( 0x17, token, "MS-ASWBXML", 650, @"[In Code Page 24: RightsManagement] [Tag name] ContentOwner [Token] 0x17 [supports protocol versions] 14.1, 16.0"); break; } default: { Site.Assert.Fail("There exists unexpected Tag in wbxml processing\r\n CodePage[{0}]:TagName[{1}]-Token[0x{2:X}]", codePageNumber, tagName, token); break; } } } #endregion } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * 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 OpenSim 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. */ // #define TESTING_OFFLINES #if TESTING_OFFLINES using System.IO; using System.Text; using System.Xml; using System.Xml.Serialization; #endif using System; using System.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework.Client; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System.Threading; namespace OpenSim.Region.CoreModules.Avatar.InstantMessage { public class OfflineMessageModule : IRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private bool enabled = true; private List<Scene> m_SceneList = new List<Scene>(); private string m_RestURL = String.Empty; public void Initialize(Scene scene, IConfigSource config) { if (!enabled) return; IConfig cnf = config.Configs["Messaging"]; if (cnf == null) { enabled = false; return; } if (cnf != null && cnf.GetString( "OfflineMessageModule", "None") != "OfflineMessageModule") { enabled = false; return; } lock (m_SceneList) { if (m_SceneList.Count == 0) { m_RestURL = cnf.GetString("OfflineMessageURL", String.Empty); if (String.IsNullOrEmpty(m_RestURL)) { m_log.Error("[OFFLINE MESSAGING]: Module was enabled, but no URL is given, disabling"); enabled = false; return; } } if (!m_SceneList.Contains(scene)) m_SceneList.Add(scene); scene.EventManager.OnNewClient += OnNewClient; } } public void PostInitialize() { if (!enabled) return; if (m_SceneList.Count == 0) return; IMessageTransferModule trans = m_SceneList[0].RequestModuleInterface<IMessageTransferModule>(); if (trans == null) { enabled = false; lock (m_SceneList) { foreach (Scene s in m_SceneList) s.EventManager.OnNewClient -= OnNewClient; m_SceneList.Clear(); } m_log.Error("[OFFLINE MESSAGING]: No message transfer module is enabled. Diabling offline messages"); return; } trans.OnUndeliveredMessage += UndeliveredMessage; m_log.Debug("[OFFLINE MESSAGING]: Offline messages enabled"); } public string Name { get { return "OfflineMessageModule"; } } public bool IsSharedModule { get { return true; } } public void Close() { } private Scene FindScene(UUID agentID) { foreach (Scene s in m_SceneList) { ScenePresence presence = s.GetScenePresence(agentID); if (presence != null && !presence.IsChildAgent) return s; } return null; } private IClientAPI FindClient(UUID agentID) { foreach (Scene s in m_SceneList) { ScenePresence presence = s.GetScenePresence(agentID); if (presence != null && !presence.IsChildAgent) return presence.ControllingClient; } return null; } private void OnNewClient(IClientAPI client) { client.OnRetrieveInstantMessages += RetrieveInstantMessages; } #if TESTING_OFFLINES // This test code just tests the handling of offline IMs and group notices, in the absence of a web server and offline.php script. // It stores the most recent (only) offline message, and where it goes to many recipients, it only stores the last recipient added. private List<MemoryStream> m_DummyOfflines = new List<MemoryStream>(); private void DebugStoreIM(GridInstantMessage im) { MemoryStream buffer = new MemoryStream(); Type type = typeof(GridInstantMessage); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; using (XmlWriter writer = XmlWriter.Create(buffer, settings)) { XmlSerializer serializer = new XmlSerializer(type); serializer.Serialize(writer, im); writer.Flush(); } lock(m_DummyOfflines) { m_DummyOfflines.Add(buffer); } // string debug = buffer.ToString(); } private List<GridInstantMessage> DebugFetchIMs() { List<GridInstantMessage> offlines = new List<GridInstantMessage>(); lock (m_DummyOfflines) { foreach (MemoryStream offline in m_DummyOfflines) { XmlSerializer deserializer = new XmlSerializer(typeof(GridInstantMessage)); offline.Seek(0, SeekOrigin.Begin); // we should check im.toAgentID here but for this testing, it will return the last one to anybody. offlines.Add((GridInstantMessage)deserializer.Deserialize(offline)); } m_DummyOfflines.Clear(); // we've fetched these } return offlines; } #endif private void RetrieveInstantMessages(IClientAPI client) { m_log.DebugFormat("[OFFLINE MESSAGING]: Retrieving stored messages for {0}", client.AgentId); List<GridInstantMessage> msglist = null; try { #if TESTING_OFFLINES msglist = DebugFetchIMs(); #else msglist = SynchronousRestObjectPoster.BeginPostObject<UUID, List<GridInstantMessage>>( "POST", m_RestURL + "/RetrieveMessages/", client.AgentId); #endif if (msglist == null) return; } catch (Exception e) { m_log.ErrorFormat("[OFFLINE MESSAGING]: Exception fetching offline IMs for {0}: {1}", client.AgentId.ToString(), e.ToString()); return; } //I believe the reason some people are not getting offlines or all //offlines is because they are not yet a root agent when this module //is called into by the client. What we should do in this case //is hook into onmakerootagent and send the messages then. //for now a workaround is to loop until we get a scene Thread.Sleep(2000); const int MAX_SCENE_RETRIES = 10; int i = 0; Scene s = null; for (i = 0; i < MAX_SCENE_RETRIES; i++) { s = FindScene(client.AgentId); if (s != null) { break; } else { Thread.Sleep(1000); } } if (s == null) { m_log.ErrorFormat("[OFFLINE MESSAGING]: Didnt find active scene for user in {0} s", MAX_SCENE_RETRIES); return; } foreach (GridInstantMessage im in msglist) { // Send through scene event manager so all modules get a chance // to look at this message before it gets delivered. // // Needed for proper state management for stored group // invitations // try { s.EventManager.TriggerIncomingInstantMessage(im); } catch (Exception e) { m_log.ErrorFormat("[OFFLINE MESSAGING]: Exception sending offline IM for {0}: {1}", client.AgentId.ToString(), e); m_log.ErrorFormat("[OFFLINE MESSAGING]: Problem offline IM was type {0} from {1} to group {2}:\n{3}", im.dialog.ToString(), im.fromAgentName, im.fromGroup.ToString(), im.message); } } } private void UndeliveredMessage(GridInstantMessage im) { //this does not appear to mean what the coders here thought. //it appears to be the type of message this is, online meaning //it is coming from an online agent and headed to an online, or //not known to not be online agent /*if (im.offline != 0) {*/ if ( //not an im from the group and not start typing, stoptyping, or request tp ((!im.fromGroup) && im.dialog != (byte)InstantMessageDialog.StartTyping && im.dialog != (byte)InstantMessageDialog.StopTyping && im.dialog != (byte) InstantMessageDialog.RequestTeleport) || //im from the group and invitation or notice may go through (im.fromGroup && (im.dialog == (byte)InstantMessageDialog.GroupInvitation || im.dialog == (byte)InstantMessageDialog.GroupNotice)) ) { #if TESTING_OFFLINES bool success = true; DebugStoreIM(im); #else bool success = SynchronousRestObjectPoster.BeginPostObject<GridInstantMessage, bool>( "POST", m_RestURL + "/SaveMessage/", im); #endif if (im.dialog == (byte)InstantMessageDialog.MessageFromAgent) { IClientAPI client = FindClient(new UUID(im.fromAgentID)); if (client == null) return; client.SendInstantMessage(new GridInstantMessage( null, new UUID(im.toAgentID), "System", new UUID(im.fromAgentID), (byte)InstantMessageDialog.MessageFromAgent, "User is not logged in. " + (success ? "Message saved." : "Message not saved"), false, new Vector3())); } } //} } } }
using System; using System.Collections.Generic; using NUnit.Framework; using SIL.Data; using SIL.DictionaryServices.Model; using SIL.Lift; using SIL.Lift.Options; using SIL.TestUtilities; using SIL.Text; using SIL.WritingSystems; namespace SIL.DictionaryServices.Tests { [TestFixture] public class LiftLexEntryRepositoryTests { private class TestEnvironment : IDisposable { private readonly TemporaryFolder _temporaryFolder; private readonly LiftLexEntryRepository _repository; private readonly WritingSystemDefinition _headwordWritingSystem; public TestEnvironment() { _temporaryFolder = new TemporaryFolder("LiftLexEntryRepositoryTests"); string filePath = _temporaryFolder.GetTemporaryFile(); _repository = new LiftLexEntryRepository(filePath); _headwordWritingSystem = new WritingSystemDefinition("th") {DefaultCollation = new IcuRulesCollationDefinition("standard")}; } public LiftLexEntryRepository Repository { get { return _repository; } } public WritingSystemDefinition HeadwordWritingSystem { get { return _headwordWritingSystem; } } public void CreateThreeDifferentLexEntries(GetMultiTextFromLexEntryDelegate getMultiTextFromLexEntryDelegate) { LexEntry[] lexEntriesToSort = new LexEntry[3]; MultiText[] propertyOfLexentry = new MultiText[3]; lexEntriesToSort[0] = _repository.CreateItem(); propertyOfLexentry[0] = getMultiTextFromLexEntryDelegate(lexEntriesToSort[0]); propertyOfLexentry[0].SetAlternative("de", "de Word2"); lexEntriesToSort[1] = _repository.CreateItem(); propertyOfLexentry[1] = getMultiTextFromLexEntryDelegate(lexEntriesToSort[1]); propertyOfLexentry[1].SetAlternative("de", "de Word3"); lexEntriesToSort[2] = _repository.CreateItem(); propertyOfLexentry[2] = getMultiTextFromLexEntryDelegate(lexEntriesToSort[2]); propertyOfLexentry[2].SetAlternative("de", "de Word1"); _repository.SaveItem(lexEntriesToSort[0]); _repository.SaveItem(lexEntriesToSort[1]); _repository.SaveItem(lexEntriesToSort[2]); } public LexEntry CreateLexEntryWithSemanticDomain(string semanticDomain) { LexEntry lexEntryWithSemanticDomain = _repository.CreateItem(); lexEntryWithSemanticDomain.Senses.Add(new LexSense()); OptionRefCollection o = lexEntryWithSemanticDomain.Senses[0].GetOrCreateProperty<OptionRefCollection>( LexSense.WellKnownProperties.SemanticDomainDdp4); o.Add(semanticDomain); _repository.SaveItem(lexEntryWithSemanticDomain); return lexEntryWithSemanticDomain; } public void AddSenseWithSemanticDomainToLexEntry(LexEntry entry, string semanticDomain) { entry.Senses.Add(new LexSense()); OptionRefCollection o = entry.Senses[1].GetOrCreateProperty<OptionRefCollection>( LexSense.WellKnownProperties.SemanticDomainDdp4); o.Add(semanticDomain); _repository.SaveItem(entry); } public void CreateLexEntryWithLexicalForm(string lexicalForm) { LexEntry lexEntryWithLexicalForm = _repository.CreateItem(); lexEntryWithLexicalForm.LexicalForm["de"] = lexicalForm; _repository.SaveItem(lexEntryWithLexicalForm); } public void CreateEntryWithLexicalFormAndGloss(LanguageForm glossToMatch, string lexicalFormWritingSystem, string lexicalForm) { LexEntry entryWithGlossAndLexicalForm = _repository.CreateItem(); entryWithGlossAndLexicalForm.Senses.Add(new LexSense()); entryWithGlossAndLexicalForm.Senses[0].Gloss.SetAlternative(glossToMatch.WritingSystemId, glossToMatch.Form); entryWithGlossAndLexicalForm.LexicalForm.SetAlternative(lexicalFormWritingSystem, lexicalForm); } public void AddEntryWithGloss(string gloss) { LexEntry entry = _repository.CreateItem(); LexSense sense = new LexSense(); entry.Senses.Add(sense); sense.Gloss["en"] = gloss; _repository.SaveItem(entry); } public LexEntry MakeEntryWithLexemeForm(string writingSystemId, string lexicalUnit) { LexEntry entry = _repository.CreateItem(); entry.LexicalForm.SetAlternative(writingSystemId, lexicalUnit); _repository.SaveItem(entry); return entry; } public void Dispose() { _repository.Dispose(); _temporaryFolder.Dispose(); } } private delegate MultiText GetMultiTextFromLexEntryDelegate(LexEntry entry); private static WritingSystemDefinition WritingSystemDefinitionForTest(string languageISO) { var retval = new WritingSystemDefinition(); retval.Language = languageISO; retval.DefaultCollation = new IcuRulesCollationDefinition("standard"); return retval; } private static WritingSystemDefinition WritingSystemDefinitionForTest() { return WritingSystemDefinitionForTest("th"); } [Test] public void GetAllEntriesSortedByHeadword_RepositoryIsEmpty_ReturnsEmptyList() { using (var env = new TestEnvironment()) { Assert.AreEqual(0, env.Repository.GetAllEntriesSortedByHeadword(WritingSystemDefinitionForTest()).Count); } } [Test] public void GetAllEntriesSortedByHeadword_Null_Throws() { using (var env = new TestEnvironment()) { Assert.Throws<ArgumentNullException>(() => env.Repository.GetAllEntriesSortedByHeadword(null)); } } [Test] public void GetAllEntriesSortedByHeadword_CitationFormExistsInWritingSystemForAllEntries_ReturnsListSortedByCitationForm() { using (var env = new TestEnvironment()) { env.CreateThreeDifferentLexEntries(delegate(LexEntry e) { return e.CitationForm; }); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByHeadWord = env.Repository.GetAllEntriesSortedByHeadword(german); Assert.AreEqual("de Word1", listOfLexEntriesSortedByHeadWord[0]["Form"]); Assert.AreEqual("de Word2", listOfLexEntriesSortedByHeadWord[1]["Form"]); Assert.AreEqual("de Word3", listOfLexEntriesSortedByHeadWord[2]["Form"]); } } [Test] public void GetAllEntriesSortedByHeadword_CitationAndLexicalFormInWritingSystemDoNotExist_ReturnsNullForThatEntry() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithOutFrenchHeadWord = env.Repository.CreateItem(); lexEntryWithOutFrenchHeadWord.LexicalForm.SetAlternative("de", "de Word1"); lexEntryWithOutFrenchHeadWord.CitationForm.SetAlternative("de", "de Word1"); var french = WritingSystemDefinitionForTest("fr"); ResultSet<LexEntry> listOfLexEntriesSortedByHeadWord = env.Repository.GetAllEntriesSortedByHeadword(french); Assert.AreEqual(null, listOfLexEntriesSortedByHeadWord[0]["Form"]); } } [Test] public void GetAllEntriesSortedByHeadword_CitationFormInWritingSystemDoesNotExistButLexicalFormDoes_SortsByLexicalFormForThatEntry() { using (var env = new TestEnvironment()) { env.CreateThreeDifferentLexEntries(delegate(LexEntry e) { return e.CitationForm; }); LexEntry lexEntryWithOutGermanCitationForm = env.Repository.CreateItem(); lexEntryWithOutGermanCitationForm.CitationForm.SetAlternative("fr", "fr Word4"); lexEntryWithOutGermanCitationForm.LexicalForm.SetAlternative("de", "de Word0"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByHeadWord = env.Repository.GetAllEntriesSortedByHeadword(german); Assert.AreEqual(4, listOfLexEntriesSortedByHeadWord.Count); Assert.AreEqual("de Word0", listOfLexEntriesSortedByHeadWord[0]["Form"]); Assert.AreEqual("de Word1", listOfLexEntriesSortedByHeadWord[1]["Form"]); Assert.AreEqual("de Word2", listOfLexEntriesSortedByHeadWord[2]["Form"]); Assert.AreEqual("de Word3", listOfLexEntriesSortedByHeadWord[3]["Form"]); } } [Test] public void GetAllEntriesSortedByHeadword_CitationFormAndLexicalFormAreIdenticalInAnEntry_EntryOnlyApearsOnce() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithIdenticalCitationandLexicalForm = env.Repository.CreateItem(); lexEntryWithIdenticalCitationandLexicalForm.CitationForm.SetAlternative("de", "de Word1"); lexEntryWithIdenticalCitationandLexicalForm.LexicalForm.SetAlternative("de", "de Word1"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByHeadWord = env.Repository.GetAllEntriesSortedByHeadword(german); Assert.AreEqual(1, listOfLexEntriesSortedByHeadWord.Count); } } [Test] public void GetAllEntriesSortedByLexicalFormOrAlternative_RepositoryIsEmpty_ReturnsEmptyList() { using (var env = new TestEnvironment()) { Assert.AreEqual(0, env.Repository.GetAllEntriesSortedByLexicalFormOrAlternative(WritingSystemDefinitionForTest()).Count); } } [Test] public void GetAllEntriesSortedByLexicalFormOrAlternative_Null_Throws() { using (var env = new TestEnvironment()) { Assert.Throws<ArgumentNullException>(() => env.Repository.GetAllEntriesSortedByLexicalFormOrAlternative(null)); } } [Test] public void GetAllEntriesSortedByLexicalFormOrAlternative_LexicalFormExistsInWritingSystemForAllEntries_ReturnsListSortedByLexicalForm() { using (var env = new TestEnvironment()) { env.CreateThreeDifferentLexEntries(delegate(LexEntry e) { return e.LexicalForm; }); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByLexicalForm = env.Repository.GetAllEntriesSortedByLexicalFormOrAlternative(german); Assert.AreEqual("de Word1", listOfLexEntriesSortedByLexicalForm[0]["Form"]); Assert.AreEqual("de Word2", listOfLexEntriesSortedByLexicalForm[1]["Form"]); Assert.AreEqual("de Word3", listOfLexEntriesSortedByLexicalForm[2]["Form"]); } } [Test] public void GetAllEntriesSortedByLexicalFormOrAlternative_LexicalFormDoesNotExistInAnyWritingSystem_ReturnsNullForThatEntry() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithOutFrenchHeadWord = env.Repository.CreateItem(); env.Repository.SaveItem(lexEntryWithOutFrenchHeadWord); var french = WritingSystemDefinitionForTest("fr"); ResultSet<LexEntry> listOfLexEntriesSortedByLexicalForm = env.Repository.GetAllEntriesSortedByLexicalFormOrAlternative(french); Assert.AreEqual(null, listOfLexEntriesSortedByLexicalForm[0]["Form"]); } } [Test] public void GetAllEntriesSortedByLexicalFormOrAlternative_LexicalFormDoesNotExistInPrimaryWritingSystemButDoesInAnother_ReturnsAlternativeThatEntry() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithOutFrenchHeadWord = env.Repository.CreateItem(); lexEntryWithOutFrenchHeadWord.LexicalForm.SetAlternative("de", "de word1"); env.Repository.SaveItem(lexEntryWithOutFrenchHeadWord); var french = WritingSystemDefinitionForTest("fr"); ResultSet<LexEntry> listOfLexEntriesSortedByLexicalForm = env.Repository.GetAllEntriesSortedByLexicalFormOrAlternative(french); Assert.AreEqual("de word1", listOfLexEntriesSortedByLexicalForm[0]["Form"]); } } [Test] public void GetAllEntriesSortedByLexicalFormOrAlternative_LexicalFormExistsInWritingSystem_ReturnsWritingSystem() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithOutFrenchHeadWord = env.Repository.CreateItem(); lexEntryWithOutFrenchHeadWord.LexicalForm.SetAlternative("fr", "fr word1"); env.Repository.SaveItem(lexEntryWithOutFrenchHeadWord); var french = WritingSystemDefinitionForTest("fr"); ResultSet<LexEntry> listOfLexEntriesSortedByLexicalForm = env.Repository.GetAllEntriesSortedByLexicalFormOrAlternative(french); Assert.AreEqual("fr", listOfLexEntriesSortedByLexicalForm[0]["WritingSystem"]); } } [Test] public void GetAllEntriesSortedByLexicalFormOrAlternative_LexicalFormDoesNotExistInPrimaryWritingSystemButDoesInAnother_ReturnsWritingSystem() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithOutFrenchHeadWord = env.Repository.CreateItem(); lexEntryWithOutFrenchHeadWord.LexicalForm.SetAlternative("de", "de word1"); env.Repository.SaveItem(lexEntryWithOutFrenchHeadWord); var french = WritingSystemDefinitionForTest("fr"); ResultSet<LexEntry> listOfLexEntriesSortedByLexicalForm = env.Repository.GetAllEntriesSortedByLexicalFormOrAlternative(french); Assert.AreEqual("de", listOfLexEntriesSortedByLexicalForm[0]["WritingSystem"]); } } [Test] public void GetAllEntriesSortedByDefinition_RepositoryIsEmpty_ReturnsEmptyList() { using (var env = new TestEnvironment()) { Assert.AreEqual(0, env.Repository.GetAllEntriesSortedByDefinitionOrGloss(WritingSystemDefinitionForTest()).Count); } } [Test] public void GetAllEntriesSortedByDefinition_Null_Throws() { using (var env = new TestEnvironment()) { Assert.Throws<ArgumentNullException>(() => env.Repository.GetAllEntriesSortedByDefinitionOrGloss(null)); } } [Test] public void GetAllEntriesSortedByDefinition_DefinitionExistsInWritingSystemForAllEntries_ReturnsListSortedByDefinition() { using (var env = new TestEnvironment()) { env.CreateThreeDifferentLexEntries(delegate(LexEntry e) { e.Senses.Add(new LexSense()); return e.Senses[0].Definition; }); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(3, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[0]["Form"]); Assert.AreEqual("de Word2", listOfLexEntriesSortedByDefinition[1]["Form"]); Assert.AreEqual("de Word3", listOfLexEntriesSortedByDefinition[2]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_DefinitionsDoesNotExistInWritingSystemButGlossDoesForAllEntries_ReturnsListSortedByGloss() { using (var env = new TestEnvironment()) { env.CreateThreeDifferentLexEntries(delegate(LexEntry e) { e.Senses.Add(new LexSense()); return e.Senses[0].Gloss; }); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByGloss = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(3, listOfLexEntriesSortedByGloss.Count); Assert.AreEqual("de Word1", listOfLexEntriesSortedByGloss[0]["Form"]); Assert.AreEqual("de Word2", listOfLexEntriesSortedByGloss[1]["Form"]); Assert.AreEqual("de Word3", listOfLexEntriesSortedByGloss[2]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_DefinitionAndGlossExistInWritingSystem_ReturnsSortedListWithBothDefinitionAndGloss() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithBothDefinitionAndAGloss = env.Repository.CreateItem(); lexEntryWithBothDefinitionAndAGloss.Senses.Add(new LexSense()); lexEntryWithBothDefinitionAndAGloss.Senses[0].Definition.SetAlternative("de", "de Word2"); lexEntryWithBothDefinitionAndAGloss.Senses[0].Gloss.SetAlternative("de", "de Word1"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[0]["Form"]); Assert.AreEqual("de Word2", listOfLexEntriesSortedByDefinition[1]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_DefinitionIsIdenticalInWritingSystemInMultipleSenses_ReturnsSortedListWithBothDefinitions() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithBothDefinitionAndAGloss = env.Repository.CreateItem(); lexEntryWithBothDefinitionAndAGloss.Senses.Add(new LexSense()); lexEntryWithBothDefinitionAndAGloss.Senses.Add(new LexSense()); lexEntryWithBothDefinitionAndAGloss.Senses[0].Definition.SetAlternative("de", "de Word1"); lexEntryWithBothDefinitionAndAGloss.Senses[1].Definition.SetAlternative("de", "de Word1"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(2, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[0]["Form"]); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[1]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_GlossIsIdenticalInWritingSystemInMultipleSenses_ReturnsSortedListWithBothDefinitions() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithBothDefinitionAndAGloss = env.Repository.CreateItem(); lexEntryWithBothDefinitionAndAGloss.Senses.Add(new LexSense()); lexEntryWithBothDefinitionAndAGloss.Senses.Add(new LexSense()); lexEntryWithBothDefinitionAndAGloss.Senses[0].Gloss.SetAlternative("de", "de Word1"); lexEntryWithBothDefinitionAndAGloss.Senses[1].Gloss.SetAlternative("de", "de Word1"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(2, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[0]["Form"]); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[1]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_DefinitionAndGlossAreNullInWritingSystemInMultipleSenses_ReturnsSortedListWithBothDefinitions() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithBothDefinitionAndAGloss = env.Repository.CreateItem(); lexEntryWithBothDefinitionAndAGloss.Senses.Add(new LexSense()); lexEntryWithBothDefinitionAndAGloss.Senses.Add(new LexSense()); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(2, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual(null, listOfLexEntriesSortedByDefinition[0]["Form"]); Assert.AreEqual(null, listOfLexEntriesSortedByDefinition[1]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_DefinitionAndGlossAreIdenticalInWritingSystemInMultipleSenses_ReturnsSortedListWithBothDefinitions() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithBothDefinitionAndAGloss = env.Repository.CreateItem(); lexEntryWithBothDefinitionAndAGloss.Senses.Add(new LexSense()); lexEntryWithBothDefinitionAndAGloss.Senses.Add(new LexSense()); lexEntryWithBothDefinitionAndAGloss.Senses[0].Definition.SetAlternative("de", "de Word1"); lexEntryWithBothDefinitionAndAGloss.Senses[0].Gloss.SetAlternative("de", "de Word1"); lexEntryWithBothDefinitionAndAGloss.Senses[1].Definition.SetAlternative("de", "de Word1"); lexEntryWithBothDefinitionAndAGloss.Senses[1].Gloss.SetAlternative("de", "de Word1"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(2, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[0]["Form"]); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[1]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_DefinitionContainsOnlySemiColon_ReturnsListWithNullRecord() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithDefinition = env.Repository.CreateItem(); lexEntryWithDefinition.Senses.Add(new LexSense()); lexEntryWithDefinition.Senses[0].Definition.SetAlternative("de", ";"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(1, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual(null, listOfLexEntriesSortedByDefinition[0]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_GlossContainsOnlySemiColon_ReturnsListWithNullRecord() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithGloss = env.Repository.CreateItem(); lexEntryWithGloss.Senses.Add(new LexSense()); lexEntryWithGloss.Senses[0].Gloss.SetAlternative("de", ";"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(1, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual(null, listOfLexEntriesSortedByDefinition[0]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_DefinitionAndGlossAreIdenticalContainsOnlySemiColon_ReturnsListWithOneNullRecord() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithGloss = env.Repository.CreateItem(); lexEntryWithGloss.Senses.Add(new LexSense()); lexEntryWithGloss.Senses[0].Definition.SetAlternative("de", ";"); lexEntryWithGloss.Senses[0].Gloss.SetAlternative("de", ";"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(1, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual(null, listOfLexEntriesSortedByDefinition[0]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_DefinitionAndGlossAreIdenticalAndHaveTwoIdenticalWordsSeperatedBySemiColon_ReturnsListWithOneNullRecord() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithGloss = env.Repository.CreateItem(); lexEntryWithGloss.Senses.Add(new LexSense()); lexEntryWithGloss.Senses[0].Definition.SetAlternative("de", "de Word1;de Word2"); lexEntryWithGloss.Senses[0].Gloss.SetAlternative("de", "de Word1;de Word2"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(2, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[0]["Form"]); Assert.AreEqual("de Word2", listOfLexEntriesSortedByDefinition[1]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_DefinitionHasTwoIdenticalWordsSeperatedBySemiColon_ReturnsListWithOnlyOneRecord() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithDefinition = env.Repository.CreateItem(); lexEntryWithDefinition.Senses.Add(new LexSense()); lexEntryWithDefinition.Senses[0].Definition.SetAlternative("de", "de Word1;de Word1"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(1, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[0]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_GlossHasTwoIdenticalWordsSeperatedBySemiColon_ReturnsListWithOnlyOneRecord() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithGloss = env.Repository.CreateItem(); lexEntryWithGloss.Senses.Add(new LexSense()); lexEntryWithGloss.Senses[0].Gloss.SetAlternative("de", "de Word1;de Word1"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(1, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[0]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_DefinitionContainsSemiColon_DefinitionIsSplitAtSemiColonAndEachPartReturned() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithBothDefinitionAndAGloss = env.Repository.CreateItem(); lexEntryWithBothDefinitionAndAGloss.Senses.Add(new LexSense()); lexEntryWithBothDefinitionAndAGloss.Senses[0].Definition.SetAlternative("de", "de Word2;de Word1"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(2, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[0]["Form"]); Assert.AreEqual("de Word2", listOfLexEntriesSortedByDefinition[1]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_GlossContainsSemiColon_GlossIsSplitAtSemiColonAndEachPartReturned() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithBothDefinitionAndAGloss = env.Repository.CreateItem(); lexEntryWithBothDefinitionAndAGloss.Senses.Add(new LexSense()); lexEntryWithBothDefinitionAndAGloss.Senses[0].Gloss.SetAlternative("de", "de Word2;de Word1"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(2, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[0]["Form"]); Assert.AreEqual("de Word2", listOfLexEntriesSortedByDefinition[1]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_DefinitionContainsSemiColon_DefinitionIsSplitAtSemiColonAndExtraWhiteSpaceStrippedAndEachPartReturned() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithBothDefinitionAndAGloss = env.Repository.CreateItem(); lexEntryWithBothDefinitionAndAGloss.Senses.Add(new LexSense()); lexEntryWithBothDefinitionAndAGloss.Senses[0].Definition.SetAlternative("de", "de Word2; de Word1"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(2, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[0]["Form"]); Assert.AreEqual("de Word2", listOfLexEntriesSortedByDefinition[1]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_GlossContainsSemiColon_GlossIsSplitAtSemiColonAndExtraWhiteSpaceStrippedAndEachPartReturned() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithBothDefinitionAndAGloss = env.Repository.CreateItem(); lexEntryWithBothDefinitionAndAGloss.Senses.Add(new LexSense()); lexEntryWithBothDefinitionAndAGloss.Senses[0].Gloss.SetAlternative("de", "de Word1; de Word2"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(2, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[0]["Form"]); Assert.AreEqual("de Word2", listOfLexEntriesSortedByDefinition[1]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_DefinitionAndGlossAreIdenticalAndContainSemiColon_DefinitionIsSplitAtSemiColonAndExtraWhiteSpaceStrippedAndEachPartReturned() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithBothDefinitionAndAGloss = env.Repository.CreateItem(); lexEntryWithBothDefinitionAndAGloss.Senses.Add(new LexSense()); lexEntryWithBothDefinitionAndAGloss.Senses[0].Definition.SetAlternative("de", "de Word1; de Word2"); lexEntryWithBothDefinitionAndAGloss.Senses[0].Gloss.SetAlternative("de", "de Word1; de Word2"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(2, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[0]["Form"]); Assert.AreEqual("de Word2", listOfLexEntriesSortedByDefinition[1]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_DefinitionAndGlossAreIdenticalAndContainSemiColon_DefinitionIsSplitAtSemiColonAndEachPartReturned() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithBothDefinitionAndAGloss = env.Repository.CreateItem(); lexEntryWithBothDefinitionAndAGloss.Senses.Add(new LexSense()); lexEntryWithBothDefinitionAndAGloss.Senses[0].Definition.SetAlternative("de", "de Word1; de Word2"); lexEntryWithBothDefinitionAndAGloss.Senses[0].Gloss.SetAlternative("de", "de Word1; de Word2"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(2, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[0]["Form"]); Assert.AreEqual("de Word2", listOfLexEntriesSortedByDefinition[1]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_DefinitionContainSemiColonAndOneElementIsIdenticalToGloss_IdenticalElementIsReturnedOnlyOnce() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithBothDefinitionAndAGloss = env.Repository.CreateItem(); lexEntryWithBothDefinitionAndAGloss.Senses.Add(new LexSense()); lexEntryWithBothDefinitionAndAGloss.Senses[0].Definition.SetAlternative("de", "de Word1; de Word2"); lexEntryWithBothDefinitionAndAGloss.Senses[0].Gloss.SetAlternative("de", "de Word1"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(2, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[0]["Form"]); Assert.AreEqual("de Word2", listOfLexEntriesSortedByDefinition[1]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_GlossContainSemiColonAndOneElementIsIdenticalToDefinition_IdenticalElementIsReturnedOnlyOnce() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithBothDefinitionAndAGloss = env.Repository.CreateItem(); lexEntryWithBothDefinitionAndAGloss.Senses.Add(new LexSense()); lexEntryWithBothDefinitionAndAGloss.Senses[0].Definition.SetAlternative("de", "de Word1"); lexEntryWithBothDefinitionAndAGloss.Senses[0].Gloss.SetAlternative("de", "de Word1; de Word2"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(2, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[0]["Form"]); Assert.AreEqual("de Word2", listOfLexEntriesSortedByDefinition[1]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_DefinitionAndGlossContainSemiColonAndSomeElementsAreIdentical_IdenticalElementsAreReturnedOnlyOnce() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithBothDefinitionAndAGloss = env.Repository.CreateItem(); lexEntryWithBothDefinitionAndAGloss.Senses.Add(new LexSense()); lexEntryWithBothDefinitionAndAGloss.Senses[0].Definition.SetAlternative("de", "de Word1;de Word2; de Word3"); lexEntryWithBothDefinitionAndAGloss.Senses[0].Gloss.SetAlternative("de", "de Word1; de Word3; de Word4"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(4, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[0]["Form"]); Assert.AreEqual("de Word2", listOfLexEntriesSortedByDefinition[1]["Form"]); Assert.AreEqual("de Word3", listOfLexEntriesSortedByDefinition[2]["Form"]); Assert.AreEqual("de Word4", listOfLexEntriesSortedByDefinition[3]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_DefinitionAndGlossInWritingSystemDoNotExist_ReturnsNullForThatEntry() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithOutFrenchGloss = env.Repository.CreateItem(); lexEntryWithOutFrenchGloss.Senses.Add(new LexSense()); lexEntryWithOutFrenchGloss.Senses[0].Definition.SetAlternative("de", "de Word1"); var french = WritingSystemDefinitionForTest("fr"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(french); Assert.AreEqual(1, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual(null, listOfLexEntriesSortedByDefinition[0]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_DefinitionAndGlossOfOneEntryAreIdentical_ReturnsOnlyOneRecordToken() { using (var env = new TestEnvironment()) { env.CreateThreeDifferentLexEntries(delegate(LexEntry e) { e.Senses.Add(new LexSense()); return e.Senses[0].Definition; }); LexEntry lexEntryWithBothDefinitionAndAGloss = env.Repository.CreateItem(); lexEntryWithBothDefinitionAndAGloss.Senses.Add(new LexSense()); lexEntryWithBothDefinitionAndAGloss.Senses[0].Definition.SetAlternative("de", "de Word4"); lexEntryWithBothDefinitionAndAGloss.Senses[0].Gloss.SetAlternative("de", "de Word4"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(4, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[0]["Form"]); Assert.AreEqual("de Word2", listOfLexEntriesSortedByDefinition[1]["Form"]); Assert.AreEqual("de Word3", listOfLexEntriesSortedByDefinition[2]["Form"]); Assert.AreEqual("de Word4", listOfLexEntriesSortedByDefinition[3]["Form"]); } } [Test] public void GetAllEntriesSortedByDefinition_DefinitionOfTwoEntriesAreIdentical_ReturnsTwoRecordTokens() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithBothDefinition = env.Repository.CreateItem(); lexEntryWithBothDefinition.Senses.Add(new LexSense()); lexEntryWithBothDefinition.Senses[0].Definition.SetAlternative("de", "de Word1"); LexEntry lexEntryTwoWithBothDefinition = env.Repository.CreateItem(); lexEntryTwoWithBothDefinition.Senses.Add(new LexSense()); lexEntryTwoWithBothDefinition.Senses[0].Definition.SetAlternative("de", "de Word1"); var german = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> listOfLexEntriesSortedByDefinition = env.Repository.GetAllEntriesSortedByDefinitionOrGloss(german); Assert.AreEqual(2, listOfLexEntriesSortedByDefinition.Count); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[0]["Form"]); Assert.AreEqual("de Word1", listOfLexEntriesSortedByDefinition[1]["Form"]); } } [Test] public void GetEntriesWithSemanticDomainSortedBySemanticDomain_EntriesWithDifferingSemanticDomains_EntriesAreSortedBySemanticDomain() { using (var env = new TestEnvironment()) { env.CreateLexEntryWithSemanticDomain("SemanticDomain2"); env.CreateLexEntryWithSemanticDomain("SemanticDomain1"); ResultSet<LexEntry> sortedResults = env.Repository.GetEntriesWithSemanticDomainSortedBySemanticDomain(LexSense.WellKnownProperties.SemanticDomainDdp4); Assert.AreEqual(2, sortedResults.Count); Assert.AreEqual("SemanticDomain1", sortedResults[0]["SemanticDomain"]); Assert.AreEqual("SemanticDomain2", sortedResults[1]["SemanticDomain"]); } } [Test] public void GetEntriesWithSemanticDomainSortedBySemanticDomain_OneEntryWithTwoSensesThatHaveIdenticalSemanticDomains_OnlyOneTokenIsReturned() { using (var env = new TestEnvironment()) { LexEntry entryWithTwoIdenticalSenses = env.CreateLexEntryWithSemanticDomain("SemanticDomain1"); env.AddSenseWithSemanticDomainToLexEntry(entryWithTwoIdenticalSenses, "SemanticDomain1"); ResultSet<LexEntry> sortedResults = env.Repository.GetEntriesWithSemanticDomainSortedBySemanticDomain(LexSense.WellKnownProperties.SemanticDomainDdp4); Assert.AreEqual(1, sortedResults.Count); Assert.AreEqual("SemanticDomain1", sortedResults[0]["SemanticDomain"]); } } [Test] public void GetEntriesWithSemanticDomainSortedBySemanticDomain_EntryWithoutSemanticDomain_ReturnEmpty() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithoutSemanticDomain = env.Repository.CreateItem(); ResultSet<LexEntry> sortedResults = env.Repository.GetEntriesWithSemanticDomainSortedBySemanticDomain(LexSense.WellKnownProperties.SemanticDomainDdp4); Assert.AreEqual(0, sortedResults.Count); } } [Test] public void GetEntriesWithSimilarLexicalForm_WritingSystemNull_Throws() { using (var env = new TestEnvironment()) { WritingSystemDefinition ws = null; Assert.Throws<ArgumentNullException>(() => env.Repository.GetEntriesWithSimilarLexicalForm( "", ws, ApproximateMatcherOptions.IncludePrefixedForms)); } } [Test] public void GetEntriesWithSimilarLexicalForm_MultipleEntriesWithEqualAndLowestMatchingDistance_ReturnsThoseEntries() { using (var env = new TestEnvironment()) { env.CreateThreeDifferentLexEntries(delegate(LexEntry e) { return e.LexicalForm; }); var ws = WritingSystemDefinitionForTest("de"); var matches = env.Repository.GetEntriesWithSimilarLexicalForm( "", ws, ApproximateMatcherOptions.IncludePrefixedForms); Assert.AreEqual(3, matches.Count); } } [Test] public void GetEntriesWithSimilarLexicalForm_MultipleEntriesWithDifferentMatchingDistanceAndAnyEntriesBeginningWithWhatWeAreMatchingHaveZeroDistance_ReturnsAllEntriesBeginningWithTheFormToMatch() { using (var env = new TestEnvironment()) { //Matching distance as compared to Empty string LexEntry lexEntryWithMatchingDistance1 = env.Repository.CreateItem(); lexEntryWithMatchingDistance1.LexicalForm.SetAlternative("de", "d"); LexEntry lexEntryWithMatchingDistance2 = env.Repository.CreateItem(); lexEntryWithMatchingDistance2.LexicalForm.SetAlternative("de", "de"); LexEntry lexEntryWithMatchingDistance3 = env.Repository.CreateItem(); lexEntryWithMatchingDistance3.LexicalForm.SetAlternative("de", "de_"); var ws = WritingSystemDefinitionForTest("de"); ResultSet<LexEntry> matches = env.Repository.GetEntriesWithSimilarLexicalForm( "", ws, ApproximateMatcherOptions.IncludePrefixedForms); Assert.AreEqual(3, matches.Count); Assert.AreEqual("d", matches[0]["Form"]); Assert.AreEqual("de", matches[1]["Form"]); Assert.AreEqual("de_", matches[2]["Form"]); } } [Test] public void GetEntriesWithSimilarLexicalForm_MultipleEntriesWithDifferentMatchingDistanceAndAnyEntriesBeginningWithWhatWeAreMatchingHaveZeroDistanceAndWeWantTheTwoClosestMatches_ReturnsAllEntriesBeginningWithTheFormToMatchAsWellAsTheNextClosestMatch() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithMatchingDistance0 = env.Repository.CreateItem(); lexEntryWithMatchingDistance0.LexicalForm.SetAlternative("de", "de Word1"); LexEntry lexEntryWithMatchingDistance1 = env.Repository.CreateItem(); lexEntryWithMatchingDistance1.LexicalForm.SetAlternative("de", "fe"); LexEntry lexEntryWithMatchingDistance2 = env.Repository.CreateItem(); lexEntryWithMatchingDistance2.LexicalForm.SetAlternative("de", "ft"); var ws = WritingSystemDefinitionForTest("de"); var matches = env.Repository.GetEntriesWithSimilarLexicalForm( "de", ws, ApproximateMatcherOptions.IncludePrefixedAndNextClosestForms); Assert.AreEqual(2, matches.Count); Assert.AreEqual("de Word1", matches[0]["Form"]); Assert.AreEqual("fe", matches[1]["Form"]); } } [Test] public void GetEntriesWithSimilarLexicalForm_MultipleEntriesWithDifferentMatchingDistanceAndWeWantTheTwoClosestForms_ReturnsTwoEntriesWithLowestMatchingDistance() { using (var env = new TestEnvironment()) { //Matching distance as compared to Empty string LexEntry lexEntryWithMatchingDistance1 = env.Repository.CreateItem(); lexEntryWithMatchingDistance1.LexicalForm.SetAlternative("de", "d"); LexEntry lexEntryWithMatchingDistance2 = env.Repository.CreateItem(); lexEntryWithMatchingDistance2.LexicalForm.SetAlternative("de", "de"); LexEntry lexEntryWithMatchingDistance3 = env.Repository.CreateItem(); lexEntryWithMatchingDistance3.LexicalForm.SetAlternative("de", "de_"); var ws = WritingSystemDefinitionForTest("de"); var matches = env.Repository.GetEntriesWithSimilarLexicalForm( "", ws, ApproximateMatcherOptions.IncludeNextClosestForms); Assert.AreEqual(2, matches.Count); Assert.AreEqual("d", matches[0]["Form"]); Assert.AreEqual("de", matches[1]["Form"]); } } [Test] public void GetEntriesWithSimilarLexicalForm_EntriesWithDifferingWritingSystems_OnlyFindEntriesMatchingTheGivenWritingSystem() { using (var env = new TestEnvironment()) { env.CreateThreeDifferentLexEntries(delegate(LexEntry e) { return e.LexicalForm; }); LexEntry lexEntryWithFrenchLexicalForm = env.Repository.CreateItem(); lexEntryWithFrenchLexicalForm.LexicalForm.SetAlternative("fr", "de Word2"); var ws = WritingSystemDefinitionForTest("de"); var matches = env.Repository.GetEntriesWithSimilarLexicalForm( "de Wor", ws, ApproximateMatcherOptions.IncludePrefixedForms); Assert.AreEqual(3, matches.Count); Assert.AreEqual("de Word1", matches[0]["Form"]); Assert.AreEqual("de Word2", matches[1]["Form"]); Assert.AreEqual("de Word3", matches[2]["Form"]); } } [Test] public void GetEntriesWithMatchingLexicalForm_RepositoryContainsTwoEntriesWithDifferingLexicalForms_OnlyEntryWithmatchingLexicalFormIsFound() { using (var env = new TestEnvironment()) { LexEntry entryToFind = env.Repository.CreateItem(); entryToFind.LexicalForm["en"] = "find me"; env.Repository.SaveItem(entryToFind); //don't want to find this one LexEntry entryToIgnore = env.Repository.CreateItem(); entryToIgnore.LexicalForm["en"] = "don't find me"; env.Repository.SaveItem(entryToIgnore); var writingSystem = WritingSystemDefinitionForTest("en"); var list = env.Repository.GetEntriesWithMatchingLexicalForm("find me", writingSystem); Assert.AreEqual(1, list.Count); } } [Test] public void GetEntriesWithMatchingLexicalForm_WritingSystemNull_Throws() { using (var env = new TestEnvironment()) { WritingSystemDefinition lexicalFormWritingSystem = null; Assert.Throws<ArgumentNullException>(() => env.Repository.GetEntriesWithMatchingLexicalForm("de Word1", lexicalFormWritingSystem)); } } [Test] public void GetEntriesWithMatchingLexicalForm_MultipleMatchingEntries_ReturnsMatchingEntries() { using (var env = new TestEnvironment()) { env.CreateLexEntryWithLexicalForm("de Word1"); env.CreateLexEntryWithLexicalForm("de Word1"); var lexicalFormWritingSystem = WritingSystemDefinitionForTest("de"); var matches = env.Repository.GetEntriesWithMatchingLexicalForm("de Word1", lexicalFormWritingSystem); Assert.AreEqual(2, matches.Count); } } [Test] public void GetEntriesWithMatchingLexicalForm_NoMatchingEntries_ReturnsEmpty() { using (var env = new TestEnvironment()) { env.CreateLexEntryWithLexicalForm("de Word1"); env.CreateLexEntryWithLexicalForm("de Word1"); var lexicalFormWritingSystem = WritingSystemDefinitionForTest("de"); var matches = env.Repository.GetEntriesWithMatchingLexicalForm("de Word2", lexicalFormWritingSystem); Assert.AreEqual(0, matches.Count); } } [Test] public void GetEntriesWithMatchingLexicalForm_NoMatchesInWritingSystem_ReturnsEmpty() { using (var env = new TestEnvironment()) { env.CreateLexEntryWithLexicalForm("de Word1"); env.CreateLexEntryWithLexicalForm("de Word1"); var lexicalFormWritingSystem = WritingSystemDefinitionForTest("fr"); var matches = env.Repository.GetEntriesWithMatchingLexicalForm("de Word2", lexicalFormWritingSystem); Assert.AreEqual(0, matches.Count); } } [Test] public void GetLexEntryWithMatchingGuid_GuidIsEmpty_Throws() { using (var env = new TestEnvironment()) { Assert.Throws<ArgumentOutOfRangeException>(() => env.Repository.GetLexEntryWithMatchingGuid(Guid.Empty)); } } [Test] public void GetLexEntryWithMatchingGuid_GuidExists_ReturnsEntryWithGuid() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithGuid = env.Repository.CreateItem(); Guid guidToFind = Guid.NewGuid(); lexEntryWithGuid.Guid = guidToFind; LexEntry found = env.Repository.GetLexEntryWithMatchingGuid(guidToFind); Assert.AreSame(lexEntryWithGuid, found); } } [Test] public void GetLexEntryWithMatchingGuid_GuidDoesNotExist_ReturnsNull() { using (var env = new TestEnvironment()) { LexEntry found = env.Repository.GetLexEntryWithMatchingGuid(Guid.NewGuid()); Assert.IsNull(found); } } [Test] public void GetLexEntryWithMatchingGuid_MultipleGuidMatchesInRepo_Throws() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithGuid = env.Repository.CreateItem(); Guid guidToFind = Guid.NewGuid(); lexEntryWithGuid.Guid = guidToFind; LexEntry lexEntryWithConflictingGuid = env.Repository.CreateItem(); lexEntryWithConflictingGuid.Guid = guidToFind; Assert.Throws<ApplicationException>(() => env.Repository.GetLexEntryWithMatchingGuid(guidToFind)); } } [Test] public void GetLexEntryWithMatchingId_IdIsEmpty_Throws() { using (var env = new TestEnvironment()) { Assert.Throws<ArgumentOutOfRangeException>(() => env.Repository.GetLexEntryWithMatchingId("")); } } [Test] public void GetLexEntryWithMatchingId_IdExists_ReturnsEntryWithId() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithId = env.Repository.CreateItem(); string idToFind = "This is the id."; lexEntryWithId.Id = idToFind; LexEntry found = env.Repository.GetLexEntryWithMatchingId(idToFind); Assert.AreSame(lexEntryWithId, found); } } [Test] public void GetLexEntryWithMatchingId_IdDoesNotExist_ReturnsNull() { using (var env = new TestEnvironment()) { LexEntry found = env.Repository.GetLexEntryWithMatchingId("This is a nonexistent Id."); Assert.IsNull(found); } } [Test] public void GetLexEntryWithMatchingId_MultipleIdMatchesInRepo_Throws() { using (var env = new TestEnvironment()) { LexEntry lexEntryWithId = env.Repository.CreateItem(); string idToFind = "This is an id"; lexEntryWithId.Id = idToFind; LexEntry lexEntryWithConflictingId = env.Repository.CreateItem(); lexEntryWithConflictingId.Id = idToFind; Assert.Throws<ApplicationException>(() => env.Repository.GetLexEntryWithMatchingId(idToFind)); } } [Test] public void GetEntriesWithMatchingGlossSortedByLexicalForm_WritingSystemNull_Throws() { using (var env = new TestEnvironment()) { var writingSystem = WritingSystemDefinitionForTest("en"); Assert.Throws<ArgumentNullException>(() => env.Repository.GetEntriesWithMatchingGlossSortedByLexicalForm(null, writingSystem)); } } [Test] public void GetEntriesWithMatchingGlossSortedByLexicalForm_LanguageFormNull_Throws() { using (var env = new TestEnvironment()) { var glossLanguageForm = new LanguageForm("en", "en Gloss", new MultiText()); Assert.Throws<ArgumentNullException>(() => env.Repository.GetEntriesWithMatchingGlossSortedByLexicalForm( glossLanguageForm, null )); } } [Test] public void GetEntriesWithMatchingGlossSortedByLexicalForm_TwoEntriesWithDifferingGlosses_OnlyEntryWithmatchingGlossIsFound() { using (var env = new TestEnvironment()) { const string glossToFind = "Gloss To Find."; env.AddEntryWithGloss(glossToFind); env.AddEntryWithGloss("Gloss Not To Find."); LanguageForm glossLanguageForm = new LanguageForm("en", glossToFind, new MultiText()); var writingSystem = WritingSystemDefinitionForTest("en"); var list = env.Repository.GetEntriesWithMatchingGlossSortedByLexicalForm( glossLanguageForm, writingSystem ); Assert.AreEqual(1, list.Count); Assert.AreSame(glossToFind, list[0].RealObject.Senses[0].Gloss["en"]); } } [Test] public void GetEntriesWithMatchingGlossSortedByLexicalForm_GlossDoesNotExist_ReturnsEmpty() { using (var env = new TestEnvironment()) { var ws = WritingSystemDefinitionForTest("en"); LanguageForm glossThatDoesNotExist = new LanguageForm("en", "I don't exist!", new MultiText()); var matches = env.Repository.GetEntriesWithMatchingGlossSortedByLexicalForm(glossThatDoesNotExist, ws); Assert.AreEqual(0, matches.Count); } } [Test] public void GetEntriesWithMatchingGlossSortedByLexicalForm_TwoEntriesWithSameGlossButDifferentLexicalForms_ReturnsListSortedByLexicalForm() { using (var env = new TestEnvironment()) { LanguageForm glossToMatch = new LanguageForm("de", "de Gloss", new MultiText()); env.CreateEntryWithLexicalFormAndGloss(glossToMatch, "en", "en LexicalForm2"); env.CreateEntryWithLexicalFormAndGloss(glossToMatch, "en", "en LexicalForm1"); var lexicalFormWritingSystem = WritingSystemDefinitionForTest("en"); var matches = env.Repository.GetEntriesWithMatchingGlossSortedByLexicalForm(glossToMatch, lexicalFormWritingSystem); Assert.AreEqual("en LexicalForm1", matches[0]["Form"]); Assert.AreEqual("en LexicalForm2", matches[1]["Form"]); } } [Test] public void GetEntriesWithMatchingGlossSortedByLexicalForm_EntryHasNoLexicalFormInWritingSystem_ReturnsNullForThatEntry() { using (var env = new TestEnvironment()) { LanguageForm glossToMatch = new LanguageForm("de", "de Gloss", new MultiText()); env.CreateEntryWithLexicalFormAndGloss(glossToMatch, "en", "en LexicalForm2"); var lexicalFormWritingSystem = WritingSystemDefinitionForTest("fr"); var matches = env.Repository.GetEntriesWithMatchingGlossSortedByLexicalForm(glossToMatch, lexicalFormWritingSystem); Assert.AreEqual(null, matches[0]["Form"]); } } [Test] public void GetEntriesWithMatchingGlossSortedByLexicalForm_EntryHasIdenticalSenses_ReturnsBoth() { using (var env = new TestEnvironment()) { LanguageForm identicalGloss = new LanguageForm("de", "de Gloss", new MultiText()); LexEntry entryWithGlossAndLexicalForm = env.Repository.CreateItem(); entryWithGlossAndLexicalForm.LexicalForm.SetAlternative("en", "en Word1"); entryWithGlossAndLexicalForm.Senses.Add(new LexSense()); entryWithGlossAndLexicalForm.Senses[0].Gloss.SetAlternative(identicalGloss.WritingSystemId, identicalGloss.Form); entryWithGlossAndLexicalForm.Senses.Add(new LexSense()); entryWithGlossAndLexicalForm.Senses[1].Gloss.SetAlternative(identicalGloss.WritingSystemId, identicalGloss.Form); var lexicalFormWritingSystem = WritingSystemDefinitionForTest("en"); var matches = env.Repository.GetEntriesWithMatchingGlossSortedByLexicalForm(identicalGloss, lexicalFormWritingSystem); Assert.AreEqual(2, matches.Count); Assert.AreEqual("en Word1", matches[0]["Form"]); Assert.AreEqual("en Word1", matches[1]["Form"]); } } [Test] public void GetHomographNumber_OnlyOneEntry_Returns0() { using (var env = new TestEnvironment()) { LexEntry entry1 = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue"); Assert.AreEqual(0, env.Repository.GetHomographNumber(entry1, env.HeadwordWritingSystem)); } } [Test] public void GetHomographNumber_FirstEntryWithFollowingHomograph_Returns1() { using (var env = new TestEnvironment()) { LexEntry entry1 = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue"); env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue"); Assert.AreEqual(1, env.Repository.GetHomographNumber(entry1, env.HeadwordWritingSystem)); } } [Test] public void GetHomographNumber_SecondEntry_Returns2() { using (var env = new TestEnvironment()) { env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue"); LexEntry entry2 = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue"); Assert.AreEqual(2, env.Repository.GetHomographNumber(entry2, env.HeadwordWritingSystem)); } } [Test] public void GetHomographNumber_AssignesUniqueNumbers() { using (var env = new TestEnvironment()) { LexEntry entryOther = env.MakeEntryWithLexemeForm("en", "blue"); Assert.AreNotEqual("en", env.HeadwordWritingSystem.LanguageTag); LexEntry[] entries = new LexEntry[3]; entries[0] = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue"); entries[1] = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue"); entries[2] = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue"); List<int> ids = new List<int>(entries.Length); foreach (LexEntry entry in entries) { int homographNumber = env.Repository.GetHomographNumber(entry, env.HeadwordWritingSystem); Assert.IsFalse(ids.Contains(homographNumber)); ids.Add(homographNumber); } } } [Test] public void GetHomographNumber_ThirdEntry_Returns3() { using (var env = new TestEnvironment()) { LexEntry entryOther = env.MakeEntryWithLexemeForm("en", "blue"); Assert.AreNotEqual("en", env.HeadwordWritingSystem.LanguageTag); LexEntry entry1 = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue"); LexEntry entry2 = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue"); LexEntry entry3 = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue"); Assert.AreEqual(3, env.Repository.GetHomographNumber(entry3, env.HeadwordWritingSystem)); Assert.AreEqual(2, env.Repository.GetHomographNumber(entry2, env.HeadwordWritingSystem)); Assert.AreEqual(1, env.Repository.GetHomographNumber(entry1, env.HeadwordWritingSystem)); } } [Test] public void GetHomographNumber_3SameLexicalForms_Returns123() { using (var env = new TestEnvironment()) { LexEntry entry1 = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue"); LexEntry entry2 = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue"); LexEntry entry3 = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue"); Assert.AreEqual(1, env.Repository.GetHomographNumber(entry1, env.HeadwordWritingSystem)); Assert.AreEqual(3, env.Repository.GetHomographNumber(entry3, env.HeadwordWritingSystem)); Assert.AreEqual(2, env.Repository.GetHomographNumber(entry2, env.HeadwordWritingSystem)); } } [Test] public void GetHomographNumber_3SameLexicalFormsAnd3OtherLexicalForms_Returns123() { using (var env = new TestEnvironment()) { LexEntry red1 = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "red"); LexEntry blue1 = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue"); LexEntry red2 = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "red"); LexEntry blue2 = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue"); LexEntry red3 = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "red"); LexEntry blue3 = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue"); Assert.AreEqual(1, env.Repository.GetHomographNumber(blue1, env.HeadwordWritingSystem)); Assert.AreEqual(3, env.Repository.GetHomographNumber(blue3, env.HeadwordWritingSystem)); Assert.AreEqual(2, env.Repository.GetHomographNumber(blue2, env.HeadwordWritingSystem)); Assert.AreEqual(1, env.Repository.GetHomographNumber(red1, env.HeadwordWritingSystem)); Assert.AreEqual(3, env.Repository.GetHomographNumber(red3, env.HeadwordWritingSystem)); Assert.AreEqual(2, env.Repository.GetHomographNumber(red2, env.HeadwordWritingSystem)); } } [Test] [Ignore("not implemented")] public void GetHomographNumber_HonorsOrderAttribute() { } [Test] public void GetAllEntriesSortedByHeadword_3EntriesWithLexemeForms_TokensAreSorted() { using (var env = new TestEnvironment()) { LexEntry e1 = env.Repository.CreateItem(); e1.LexicalForm.SetAlternative(env.HeadwordWritingSystem.LanguageTag, "bank"); env.Repository.SaveItem(e1); RepositoryId bankId = env.Repository.GetId(e1); LexEntry e2 = env.Repository.CreateItem(); e2.LexicalForm.SetAlternative(env.HeadwordWritingSystem.LanguageTag, "apple"); env.Repository.SaveItem(e2); RepositoryId appleId = env.Repository.GetId(e2); LexEntry e3 = env.Repository.CreateItem(); e3.LexicalForm.SetAlternative(env.HeadwordWritingSystem.LanguageTag, "xa"); //has to be something low in the alphabet to test a bug we had env.Repository.SaveItem(e3); RepositoryId xaId = env.Repository.GetId(e3); ResultSet<LexEntry> list = env.Repository.GetAllEntriesSortedByHeadword(env.HeadwordWritingSystem); Assert.AreEqual(3, list.Count); Assert.AreEqual(appleId, list[0].Id); Assert.AreEqual(bankId, list[1].Id); Assert.AreEqual(xaId, list[2].Id); } } } }
#region MigraDoc - Creating Documents on the Fly // // Authors: // Klaus Potzesny (mailto:Klaus.Potzesny@pdfsharp.com) // // Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://www.migradoc.com // http://sourceforge.net/projects/pdfsharp // // 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; using System.Diagnostics; using System.Globalization; using MigraDoc.DocumentObjectModel; using MigraDoc.DocumentObjectModel.IO; using MigraDoc.DocumentObjectModel.Tables; using MigraDoc.DocumentObjectModel.Shapes; using MigraDoc.DocumentObjectModel.Internals; namespace MigraDoc.RtfRendering { /// <summary> /// This class is a base for all renderers. /// </summary> public abstract class RendererBase { /// <summary> /// Indicates whether the container contains an element /// that is of one of the specified types or inherited. /// </summary> /// <param name="coll">The collection to search.</param> /// <param name="types">The types to find within the collection.</param> /// <returns>True, if an object of one of the given types is found within the collection.</returns> internal static bool CollectionContainsObjectAssignableTo(DocumentObjectCollection coll, params Type[] types) { foreach (object obj in coll) { foreach (Type type in types) { if (type.IsAssignableFrom(obj.GetType())) return true; } } return false; } /// <summary> /// Initializes a new instance of the RendererBase class. /// </summary> internal RendererBase() { } /// <summary> /// Initializes a new instance of the RendererBase class. /// </summary> internal RendererBase(DocumentObject domObj, RtfDocumentRenderer docRenderer) { if (enumTranslationTable == null) CreateEnumTranslationTable(); this.docObject = domObj; this.docRenderer = docRenderer; if (docRenderer != null) this.rtfWriter = docRenderer.RtfWriter; this.useEffectiveValue = false; } /// <summary> /// Helps translating MigraDoc DOM enumerations to an RTF control word. /// </summary> private static void CreateEnumTranslationTable() { enumTranslationTable = new Hashtable(); //ParagraphAlignment enumTranslationTable.Add(ParagraphAlignment.Left, "l"); enumTranslationTable.Add(ParagraphAlignment.Right, "r"); enumTranslationTable.Add(ParagraphAlignment.Center, "c"); enumTranslationTable.Add(ParagraphAlignment.Justify, "j"); //LineSpacingRule enumTranslationTable.Add(LineSpacingRule.AtLeast, 0); enumTranslationTable.Add(LineSpacingRule.Exactly, 0); enumTranslationTable.Add(LineSpacingRule.Double, 1); enumTranslationTable.Add(LineSpacingRule.OnePtFive, 1); enumTranslationTable.Add(LineSpacingRule.Multiple, 1); enumTranslationTable.Add(LineSpacingRule.Single, 1); //OutLineLevel //BodyText rendered by leaving away rtf control word. enumTranslationTable.Add(OutlineLevel.Level1, 0); enumTranslationTable.Add(OutlineLevel.Level2, 1); enumTranslationTable.Add(OutlineLevel.Level3, 2); enumTranslationTable.Add(OutlineLevel.Level4, 3); enumTranslationTable.Add(OutlineLevel.Level5, 4); enumTranslationTable.Add(OutlineLevel.Level6, 5); enumTranslationTable.Add(OutlineLevel.Level7, 6); enumTranslationTable.Add(OutlineLevel.Level8, 7); enumTranslationTable.Add(OutlineLevel.Level9, 8); //UnderlineType enumTranslationTable.Add(Underline.Dash, "dash"); enumTranslationTable.Add(Underline.DotDash, "dashd"); enumTranslationTable.Add(Underline.DotDotDash, "dashdd"); enumTranslationTable.Add(Underline.Dotted, "d"); enumTranslationTable.Add(Underline.None, "none"); enumTranslationTable.Add(Underline.Single, ""); enumTranslationTable.Add(Underline.Words, "w"); //BorderStyle enumTranslationTable.Add(BorderStyle.DashDot, "dashd"); enumTranslationTable.Add(BorderStyle.DashDotDot, "dashdd"); enumTranslationTable.Add(BorderStyle.DashLargeGap, "dash"); enumTranslationTable.Add(BorderStyle.DashSmallGap, "dashsm"); enumTranslationTable.Add(BorderStyle.Dot, "dot"); enumTranslationTable.Add(BorderStyle.Single, "s"); //BorderType.None simply not rendered. //TabLeader enumTranslationTable.Add(TabLeader.Dashes, "hyph"); enumTranslationTable.Add(TabLeader.Dots, "dot"); enumTranslationTable.Add(TabLeader.Heavy, "th"); enumTranslationTable.Add(TabLeader.Lines, "ul"); enumTranslationTable.Add(TabLeader.MiddleDot, "mdot"); //TabLeader.Spaces rendered by leaving away the tab leader control //TabAlignment enumTranslationTable.Add(TabAlignment.Center, "c"); enumTranslationTable.Add(TabAlignment.Decimal, "dec"); enumTranslationTable.Add(TabAlignment.Right, "r"); enumTranslationTable.Add(TabAlignment.Left, "l"); //FootnoteNumberStyle enumTranslationTable.Add(FootnoteNumberStyle.Arabic, "ar"); enumTranslationTable.Add(FootnoteNumberStyle.LowercaseLetter, "alc"); enumTranslationTable.Add(FootnoteNumberStyle.LowercaseRoman, "rlc"); enumTranslationTable.Add(FootnoteNumberStyle.UppercaseLetter, "auc"); enumTranslationTable.Add(FootnoteNumberStyle.UppercaseRoman, "ruc"); //FootnoteNumberingRule enumTranslationTable.Add(FootnoteNumberingRule.RestartContinuous, "rstcont"); enumTranslationTable.Add(FootnoteNumberingRule.RestartPage, "rstpg"); enumTranslationTable.Add(FootnoteNumberingRule.RestartSection, "restart"); //FootnoteLocation enumTranslationTable.Add(FootnoteLocation.BeneathText, "tj"); enumTranslationTable.Add(FootnoteLocation.BottomOfPage, "bj"); //(Section) BreakType enumTranslationTable.Add(BreakType.BreakEvenPage, "even"); enumTranslationTable.Add(BreakType.BreakOddPage, "odd"); enumTranslationTable.Add(BreakType.BreakNextPage, "page"); //TODO: ListType under construction. enumTranslationTable.Add(ListType.BulletList1, 23); enumTranslationTable.Add(ListType.BulletList2, 23); enumTranslationTable.Add(ListType.BulletList3, 23); enumTranslationTable.Add(ListType.NumberList1, 0); enumTranslationTable.Add(ListType.NumberList2, 0); enumTranslationTable.Add(ListType.NumberList3, 4); //RowAlignment enumTranslationTable.Add(RowAlignment.Center, "c"); enumTranslationTable.Add(RowAlignment.Left, "l"); enumTranslationTable.Add(RowAlignment.Right, "r"); //VerticalAlignment enumTranslationTable.Add(VerticalAlignment.Top, "t"); enumTranslationTable.Add(VerticalAlignment.Center, "c"); enumTranslationTable.Add(VerticalAlignment.Bottom, "b"); //RelativeHorizontal enumTranslationTable.Add(RelativeHorizontal.Character, "margin"); enumTranslationTable.Add(RelativeHorizontal.Column, "margin"); enumTranslationTable.Add(RelativeHorizontal.Margin, "margin"); enumTranslationTable.Add(RelativeHorizontal.Page, "page"); //RelativeVertical enumTranslationTable.Add(RelativeVertical.Line, "para"); enumTranslationTable.Add(RelativeVertical.Margin, "margin"); enumTranslationTable.Add(RelativeVertical.Page, "page"); enumTranslationTable.Add(RelativeVertical.Paragraph, "para"); //WrapStyle enumTranslationTable.Add(WrapStyle.None, 3); //Caution: Word imterpretates "Through" (in rtf value "5") slightly different! enumTranslationTable.Add(WrapStyle.Through, 3); enumTranslationTable.Add(WrapStyle.TopBottom, 1); //LineStyle enumTranslationTable.Add(LineStyle.Single, 0); //DashStyle enumTranslationTable.Add(DashStyle.Solid, 0); enumTranslationTable.Add(DashStyle.Dash, 1); enumTranslationTable.Add(DashStyle.SquareDot, 2); enumTranslationTable.Add(DashStyle.DashDot, 3); enumTranslationTable.Add(DashStyle.DashDotDot, 4); //DashStyle enumTranslationTable.Add(TextOrientation.Downward, 3); enumTranslationTable.Add(TextOrientation.Horizontal, 0); enumTranslationTable.Add(TextOrientation.HorizontalRotatedFarEast, 0); enumTranslationTable.Add(TextOrientation.Upward, 2); enumTranslationTable.Add(TextOrientation.Vertical, 3); enumTranslationTable.Add(TextOrientation.VerticalFarEast, 3); } /// <summary> /// Translates the given Unit to an RTF unit. /// </summary> /// <param name="unit"></param> /// <param name="rtfUnit"></param> /// <returns></returns> internal static int ToRtfUnit(Unit unit, RtfUnit rtfUnit) { switch (rtfUnit) { case RtfUnit.HalfPts: return (int)(Math.Round(unit.Point * 2)); case RtfUnit.Twips: return (int)(Math.Round(unit.Point * 20)); case RtfUnit.Lines: return (int)(Math.Round(unit.Point * 12 * 20)); case RtfUnit.EMU: return (int)(Math.Round(unit.Point * 12700)); case RtfUnit.CharUnit100: return (int)(Math.Round(unit.Pica * 100)); } return (int)unit.Point; } /// <summary> /// Translates a value named 'valueName' to a Rtf Control word that specifies a Unit, Enum, Bool, Int or Color. /// </summary> protected void Translate(string valueName, string rtfCtrl, RtfUnit unit, string defaultValue, bool withStar) { object val = GetValueAsIntended(valueName); if (val == null) { if (defaultValue != null) this.rtfWriter.WriteControl(rtfCtrl, defaultValue); return; } else { if (val is Unit) { this.rtfWriter.WriteControl(rtfCtrl, ToRtfUnit((Unit)val, unit), withStar); } else if (val is bool) { if ((bool)val) this.rtfWriter.WriteControl(rtfCtrl, withStar); } else if (val is Color) { int idx = this.docRenderer.GetColorIndex((Color)val); this.rtfWriter.WriteControl(rtfCtrl, idx, withStar); } else if (val is Enum) { this.rtfWriter.WriteControl(rtfCtrl, enumTranslationTable[val].ToString(), withStar); } else if (val is int) { this.rtfWriter.WriteControl(rtfCtrl, (int)val, withStar); } else Debug.Assert(false, "Invalid use of Translate"); } } /// <summary> /// Translates a value named 'valueName' to a Rtf Control word that specifies a unit, enum, bool, int or color. /// </summary> protected void Translate(string valueName, string rtfCtrl, RtfUnit unit, Unit val, bool withStar) { Translate(valueName, rtfCtrl, unit, ToRtfUnit(val, RtfUnit.Twips).ToString(CultureInfo.InvariantCulture), withStar); } /// <summary> /// Translates a value named 'valueName' to a Rtf Control word that specifies a unit, enum, bool or color. /// If it is a unit, twips are assumed as RtfUnit. /// </summary> protected void Translate(string valueName, string rtfCtrl) { Translate(valueName, rtfCtrl, RtfUnit.Twips, null, false); } /// <summary> /// Translates a value named 'valueName' to a Rtf Control word that specifies a Boolean and devides in two control words. /// If the control word in false case is simply left away, you can also use the Translate function as well. /// </summary> protected void TranslateBool(string valueName, string rtfTrueCtrl, string rtfFalseCtrl, bool withStar) { object val = GetValueAsIntended(valueName); if (val == null) return; else { if ((bool)(val)) this.rtfWriter.WriteControl(rtfTrueCtrl, withStar); else if (rtfFalseCtrl != null) this.rtfWriter.WriteControl(rtfFalseCtrl, withStar); } } /// <summary> /// Gets the specified value either as effective value if useEffectiveValue is set to true, /// otherwise returns the usual GetValue or null if IsNull evaluates to true. /// </summary> protected virtual object GetValueAsIntended(string valueName) { return this.docObject.GetValue(valueName, GV.GetNull); } /// <summary> /// Renders the given unit as control / value pair in Twips. /// </summary> protected void RenderUnit(string rtfControl, Unit value) { RenderUnit(rtfControl, value, RtfUnit.Twips, false); } /// <summary> /// Renders the given unit as control / value pair in the given RTF unit. /// </summary> protected void RenderUnit(string rtfControl, Unit value, RtfUnit rtfUnit) { RenderUnit(rtfControl, value, rtfUnit, false); } /// <summary> /// Renders the given Unit as control / value pair of the given RTF control in the given RTF unit, optionally with a star. /// </summary> protected void RenderUnit(string rtfControl, Unit value, RtfUnit rtfUnit, bool withStar) { this.rtfWriter.WriteControl(rtfControl, ToRtfUnit(value, rtfUnit), withStar); } /// <summary> /// Converts the given Unit to Twips /// </summary> internal static int ToTwips(Unit unit) { return ToRtfUnit(unit, RtfUnit.Twips); } /// <summary> /// Converts the given Unit to EMU /// </summary> internal static int ToEmu(Unit unit) { return ToRtfUnit(unit, RtfUnit.EMU); } /// <summary> /// Renders the given object to rtf, _docObj must be of type DocumentObject or DocumentObjectContainer. /// </summary> internal abstract void Render(); /// <summary> /// Returns GetValueAsIntended if this evaluates non-null, otherwise the given default value. /// </summary> protected object GetValueOrDefault(string valName, object valDefault) { object obj = GetValueAsIntended(valName); if (obj == null) return valDefault; return obj; } /// <summary> /// Renders a trailing standard paragraph in case the last element in elements isn't a paragraph. /// (Some RTF elements need to close with a paragraph.) /// </summary> protected void RenderTrailingParagraph(DocumentElements elements) { if (elements == null || !(elements.LastObject is Paragraph)) { //At least one paragra needs to be written at the end of the document. //Otherwise, word cannot read the resulting rtf file. this.rtfWriter.WriteControl("pard"); this.rtfWriter.WriteControl("s", this.docRenderer.GetStyleIndex("Normal")); new ParagraphFormatRenderer(this.docRenderer.Document.Styles["Normal"].ParagraphFormat, this.docRenderer).Render(); this.rtfWriter.WriteControl("par"); } } protected DocumentObject docObject; protected RtfDocumentRenderer docRenderer; internal RtfWriter rtfWriter; protected static Hashtable enumTranslationTable = null; protected bool useEffectiveValue; } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Diagnostics; using Axiom.Core; namespace Multiverse.Tools.WorldEditor { public delegate void SubMeshChangeEventHandler(object sender, EventArgs args); public class SubMeshInfo { private string name; private string materialName; private bool show; private SubMeshCollection parent; public SubMeshInfo(SubMeshCollection parent, string name, string materialName, bool show) { this.parent = parent; this.name = name; this.materialName = materialName; this.show = show; } public string Name { get { return name; } set { name = value; parent.OnChange(); } } public string MaterialName { get { return materialName; } set { materialName = value; parent.OnChange(); } } public bool Show { get { return show; } set { show = value; parent.OnChange(); } } } public class SubMeshCollection : IEnumerable<SubMeshInfo> { private List<SubMeshInfo> subMeshList; public event SubMeshChangeEventHandler Changed; /// <summary> /// Standard Constructor /// </summary> /// <param name="meshName"></param> public SubMeshCollection(string meshName) { subMeshList = buildSubMeshList(meshName); } /// <summary> /// Copy constructor /// </summary> /// <param name="srcCollection"></param> public SubMeshCollection(SubMeshCollection srcCollection) { this.subMeshList = new List<SubMeshInfo>(); foreach ( SubMeshInfo srcInfo in srcCollection ) { SubMeshInfo subMeshInfo = new SubMeshInfo(this, srcInfo.Name, srcInfo.MaterialName, srcInfo.Show); this.subMeshList.Add(subMeshInfo); } } public SubMeshCollection(XmlReader r) { this.subMeshList = new List<SubMeshInfo>(); while (r.Read()) { // look for the start of an element if (r.NodeType == XmlNodeType.Whitespace) { continue; } if (r.NodeType == XmlNodeType.EndElement) { break; } if (r.NodeType == XmlNodeType.Element) { if (String.Equals(r.Name, "SubMeshInfo")) { subMeshList.Add(parseSubMeshInfo(r)); } } } } private SubMeshInfo parseSubMeshInfo(XmlReader r) { string namein = ""; string materialNamein= ""; bool showin = false; for (int i = 0; i < r.AttributeCount; i++) { r.MoveToAttribute(i); switch (r.Name) { case "Name": namein = r.Value; break; case "MaterialName": materialNamein = r.Value; break; case "Show": if (String.Equals(r.Value, "True")) { showin = true; } else { showin = false; } break; } } SubMeshInfo info = new SubMeshInfo(this, namein, materialNamein, showin); r.MoveToElement(); return info; } /// <summary> /// This method builds a list of submeshes, which is used by the application to /// control which submeshes are displayed. /// </summary> private List<SubMeshInfo> buildSubMeshList(string meshName) { List<SubMeshInfo> list = new List<SubMeshInfo>(); Mesh mesh = MeshManager.Instance.Load(meshName); for (int i = 0; i < mesh.SubMeshCount; i++) { SubMesh subMesh = mesh.GetSubMesh(i); SubMeshInfo subMeshInfo = new SubMeshInfo(this, subMesh.Name, subMesh.MaterialName, true); list.Add(subMeshInfo); } return list; } public bool CheckValid(WorldEditor app, string meshName) { // get the list from the mesh List<SubMeshInfo> listFromMesh; if ( app.CheckAssetFileExists(meshName) ) { listFromMesh = buildSubMeshList(meshName); } else { // if we can't find the mesh, then log it and say its ok, since we have no idea if the submeshes are right. app.AddMissingAsset(meshName); return true; } // counts differ, check fails if (subMeshList.Count != listFromMesh.Count) { return false; } bool foundSubMesh = false; foreach (SubMeshInfo info in subMeshList) { foundSubMesh = false; for (int i = 0; i < listFromMesh.Count; i++) { SubMeshInfo infoFromMesh = listFromMesh[i]; if (infoFromMesh.Name == info.Name) { // name is the same, so we found it and its ok foundSubMesh = true; // remove the submesh info from consideration in future iterations listFromMesh.Remove(infoFromMesh); break; } } // we didn't find the submesh, so the check fails if (!foundSubMesh) { return false; } } // the temporary list should be empty at this point Debug.Assert(listFromMesh.Count == 0); // if we get this far, all the checks passed return true; } public void ToManifest(System.IO.StreamWriter w, string meshName) { // get the list from the mesh List<SubMeshInfo> listFromMesh = buildSubMeshList(meshName); // bool foundSubMesh = false; foreach (SubMeshInfo info in subMeshList) { // foundSubMesh = false; for (int i = 0; i < listFromMesh.Count; i++) { SubMeshInfo infoFromMesh = listFromMesh[i]; if (infoFromMesh.Name == info.Name) { // name is the same, so we found it and its ok // foundSubMesh = true; if (infoFromMesh.MaterialName != info.MaterialName) { // material names differ. output the material w.WriteLine("Material:{0}", info.MaterialName); } // remove the submesh info from consideration in future iterations listFromMesh.Remove(infoFromMesh); break; } } } // the temporary list should be empty at this point Debug.Assert(listFromMesh.Count == 0); } /// <summary> /// Raise an event when the submesh changes /// </summary> public void OnChange() { SubMeshChangeEventHandler e = Changed; if (e != null) { e(null, new EventArgs()); } } /// <summary> /// Look up subMeshInfo by name in the SubMeshList /// </summary> /// <param name="name"></param> /// <returns></returns> public SubMeshInfo FindSubMeshInfo(string name) { foreach (SubMeshInfo subMeshInfo in subMeshList) { if (subMeshInfo.Name == name) { return subMeshInfo; } } return null; } /// <summary> /// Set the material for a subMesh /// </summary> /// <param name="name"></param> /// <param name="materialName"></param> public void SetSubMeshMaterial(string name, string materialName) { SubMeshInfo subMeshInfo = FindSubMeshInfo(name); if (subMeshInfo != null) { subMeshInfo.MaterialName = materialName; } } public void ShowSubMesh(string name, bool show) { SubMeshInfo subMeshInfo = FindSubMeshInfo(name); if (subMeshInfo != null) { subMeshInfo.Show = show; } } public SubMeshInfo this[int i] { get { return subMeshList[i]; } } public void ToXml(XmlWriter w) { w.WriteStartElement("SubMeshes"); foreach (SubMeshInfo info in subMeshList) { w.WriteStartElement("SubMeshInfo"); w.WriteAttributeString("Name", info.Name); w.WriteAttributeString("MaterialName", info.MaterialName); w.WriteAttributeString("Show", info.Show.ToString()); w.WriteEndElement(); } w.WriteEndElement(); } #region IEnumerable<SubMeshInfo> Members public IEnumerator<SubMeshInfo> GetEnumerator() { return subMeshList.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return subMeshList.GetEnumerator(); } #endregion } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.TeamFoundation.DistributedTask.Expressions; using System.Text; namespace Microsoft.VisualStudio.Services.Agent.Worker { [ServiceLocator(Default = typeof(ExpressionManager))] public interface IExpressionManager : IAgentService { IExpressionNode Parse(IExecutionContext context, string condition); ConditionResult Evaluate(IExecutionContext context, IExpressionNode tree, bool hostTracingOnly = false); } public sealed class ExpressionManager : AgentService, IExpressionManager { public static IExpressionNode Always = new AlwaysNode(); public static IExpressionNode Succeeded = new SucceededNode(); public static IExpressionNode SucceededOrFailed = new SucceededOrFailedNode(); public IExpressionNode Parse(IExecutionContext executionContext, string condition) { ArgUtil.NotNull(executionContext, nameof(executionContext)); var expressionTrace = new TraceWriter(Trace, executionContext); var parser = new ExpressionParser(); var namedValues = new INamedValueInfo[] { new NamedValueInfo<VariablesNode>(name: Constants.Expressions.Variables), }; var functions = new IFunctionInfo[] { new FunctionInfo<AlwaysNode>(name: Constants.Expressions.Always, minParameters: 0, maxParameters: 0), new FunctionInfo<CanceledNode>(name: Constants.Expressions.Canceled, minParameters: 0, maxParameters: 0), new FunctionInfo<FailedNode>(name: Constants.Expressions.Failed, minParameters: 0, maxParameters: 0), new FunctionInfo<SucceededNode>(name: Constants.Expressions.Succeeded, minParameters: 0, maxParameters: 0), new FunctionInfo<SucceededOrFailedNode>(name: Constants.Expressions.SucceededOrFailed, minParameters: 0, maxParameters: 0), }; return parser.CreateTree(condition, expressionTrace, namedValues, functions) ?? new SucceededNode(); } public ConditionResult Evaluate(IExecutionContext executionContext, IExpressionNode tree, bool hostTracingOnly = false) { ArgUtil.NotNull(executionContext, nameof(executionContext)); ArgUtil.NotNull(tree, nameof(tree)); ConditionResult result = new ConditionResult(); var expressionTrace = new TraceWriter(Trace, hostTracingOnly ? null : executionContext); result.Value = tree.Evaluate<bool>(trace: expressionTrace, secretMasker: HostContext.SecretMasker, state: executionContext); result.Trace = expressionTrace.Trace; return result; } private sealed class TraceWriter : ITraceWriter { private readonly IExecutionContext _executionContext; private readonly Tracing _trace; private readonly StringBuilder _traceBuilder = new StringBuilder(); public string Trace => _traceBuilder.ToString(); public TraceWriter(Tracing trace, IExecutionContext executionContext) { ArgUtil.NotNull(trace, nameof(trace)); _trace = trace; _executionContext = executionContext; } public void Info(string message) { _trace.Info(message); _executionContext?.Debug(message); _traceBuilder.AppendLine(message); } public void Verbose(string message) { _trace.Verbose(message); _executionContext?.Debug(message); } } private sealed class AlwaysNode : FunctionNode { protected override Object EvaluateCore(EvaluationContext context) { return true; } } private sealed class CanceledNode : FunctionNode { protected sealed override object EvaluateCore(EvaluationContext evaluationContext) { var executionContext = evaluationContext.State as IExecutionContext; ArgUtil.NotNull(executionContext, nameof(executionContext)); TaskResult jobStatus = executionContext.Variables.Agent_JobStatus ?? TaskResult.Succeeded; return jobStatus == TaskResult.Canceled; } } private sealed class FailedNode : FunctionNode { protected sealed override object EvaluateCore(EvaluationContext evaluationContext) { var executionContext = evaluationContext.State as IExecutionContext; ArgUtil.NotNull(executionContext, nameof(executionContext)); TaskResult jobStatus = executionContext.Variables.Agent_JobStatus ?? TaskResult.Succeeded; return jobStatus == TaskResult.Failed; } } private sealed class SucceededNode : FunctionNode { protected sealed override object EvaluateCore(EvaluationContext evaluationContext) { var executionContext = evaluationContext.State as IExecutionContext; ArgUtil.NotNull(executionContext, nameof(executionContext)); TaskResult jobStatus = executionContext.Variables.Agent_JobStatus ?? TaskResult.Succeeded; return jobStatus == TaskResult.Succeeded || jobStatus == TaskResult.SucceededWithIssues; } } private sealed class SucceededOrFailedNode : FunctionNode { protected sealed override object EvaluateCore(EvaluationContext evaluationContext) { var executionContext = evaluationContext.State as IExecutionContext; ArgUtil.NotNull(executionContext, nameof(executionContext)); TaskResult jobStatus = executionContext.Variables.Agent_JobStatus ?? TaskResult.Succeeded; return jobStatus == TaskResult.Succeeded || jobStatus == TaskResult.SucceededWithIssues || jobStatus == TaskResult.Failed; } } private sealed class VariablesNode : NamedValueNode { protected sealed override object EvaluateCore(EvaluationContext evaluationContext) { var jobContext = evaluationContext.State as IExecutionContext; ArgUtil.NotNull(jobContext, nameof(jobContext)); return new VariablesDictionary(jobContext.Variables); } } private sealed class VariablesDictionary : IReadOnlyDictionary<string, object> { private readonly Variables _variables; public VariablesDictionary(Variables variables) { _variables = variables; } // IReadOnlyDictionary<string object> members public object this[string key] => _variables.Get(key); public IEnumerable<string> Keys => throw new NotSupportedException(); public IEnumerable<object> Values => throw new NotSupportedException(); public bool ContainsKey(string key) { string val; return _variables.TryGetValue(key, out val); } public bool TryGetValue(string key, out object value) { string s; bool found = _variables.TryGetValue(key, out s); value = s; return found; } // IReadOnlyCollection<KeyValuePair<string, object>> members public int Count => throw new NotSupportedException(); // IEnumerable<KeyValuePair<string, object>> members IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator() => throw new NotSupportedException(); // IEnumerable members IEnumerator IEnumerable.GetEnumerator() => throw new NotSupportedException(); } } public class ConditionResult { public ConditionResult(bool value = false, string trace = null) { this.Value = value; this.Trace = trace; } public bool Value { get; set; } public string Trace { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2225: Operator overloads have named")] public static implicit operator ConditionResult(bool value) { return new ConditionResult(value); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using DemoGame.DbObjs; using DemoGame.Server.DbObjs; using DemoGame.Server.Queries; using log4net; using NetGore; using NetGore.Db; using NetGore.Network; using NetGore.Stats; namespace DemoGame.Server { /// <summary> /// Base class for a <see cref="EquippedBase{T}"/> for any kind of <see cref="Character"/>. /// </summary> public abstract class CharacterEquipped : EquippedBase<ItemEntity>, IModStatContainer<StatType> { static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); readonly Character _character; readonly EquippedPaperDoll _paperDoll; /// <summary> /// When true, the <see cref="OnEquipped"/> and <see cref="OnUnequipped"/> methods will be ignored. /// </summary> bool _ignoreEquippedBaseEvents = false; /// <summary> /// Initializes a new instance of the <see cref="CharacterEquipped"/> class. /// </summary> /// <param name="character">The <see cref="Character"/> the instance is for.</param> /// <exception cref="ArgumentNullException"><paramref name="character" /> is <c>null</c>.</exception> protected CharacterEquipped(Character character) { if (character == null) throw new ArgumentNullException("character"); _character = character; _paperDoll = new EquippedPaperDoll(Character); } /// <summary> /// Gets the Character that this UserEquipped belongs to. /// </summary> public Character Character { get { return _character; } } public IDbController DbController { get { return Character.DbController; } } /// <summary> /// Gets if the state of this <see cref="CharacterEquipped"/> is persistent. /// </summary> public bool IsPersistent { get { return Character.IsPersistent; } } /// <summary> /// When overridden in the derived class, checks if the given <paramref name="item"/> can be /// equipped at all by the owner of this EquippedBase. /// </summary> /// <param name="item">Item to check if able be equip.</param> /// <returns>True if the <paramref name="item"/> can be equipped, else false.</returns> public override bool CanEquip(ItemEntity item) { return true; } /// <summary> /// When overridden in the derived class, checks if the item in the given <paramref name="slot"/> /// can be removed properly. /// </summary> /// <param name="slot">Slot of the item to be removed.</param> /// <returns>True if the item can be properly removed, else false.</returns> protected override bool CanRemove(EquipmentSlot slot) { var item = this[slot]; if (item == null) return true; return Character.Inventory.CanAdd(item); } /// <summary> /// When overridden in the derived class, handles when this object is disposed. /// </summary> /// <param name="disposeManaged">True if dispose was called directly; false if this object was garbage collected.</param> protected override void Dispose(bool disposeManaged) { base.Dispose(disposeManaged); // If not persistent, destroy every item in the collection if (!IsPersistent) RemoveAll(true); } /// <summary> /// Equips an <paramref name="item"/>, automatically choosing the EquipmentSlot to use. /// </summary> /// <param name="item">Item to be equipped.</param> /// <returns>True if the item was successfully equipped, else false.</returns> public bool Equip(ItemEntity item) { // Do not equip invalid items if (item == null) return false; // Check that the item can be equipped at all if (!CanEquip(item)) return false; // Get the possible slots var slots = GetPossibleSlots(item).ToImmutable(); // Check for valid slots if (slots == null) return false; switch (slots.Count()) { case 0: // If there are no slots, abort return false; case 1: // If there is just one slot, try only that slot return TrySetSlot(slots.First(), item, false); default: // There are multiple slots, so first try on empty slots var emptySlots = slots.Where(index => this[index] == null); foreach (var slot in emptySlots) { if (TrySetSlot(slot, item, false)) return true; } // Couldn't set on an empty slot, or there was no empty slots, so try all the non-empty slots foreach (var slot in slots.Except(emptySlots)) { if (TrySetSlot(slot, item, false)) return true; } // Couldn't set in any slots return false; } } /// <summary> /// Gets an IEnumerable of EquipmentSlots possible for a given item. /// </summary> /// <param name="item">Item to get the possible EquipmentSlots for.</param> /// <returns>An IEnumerable of EquipmentSlots possible for the <paramref name="item"/>.</returns> protected virtual IEnumerable<EquipmentSlot> GetPossibleSlots(ItemEntity item) { return item.Type.GetPossibleSlots(); } /// <summary> /// Loads the Character's equipped items. The Character that this CharacterEquipped belongs to /// must be persistent since there is nothing for a non-persistent Character to load. /// </summary> public void Load() { if (!IsPersistent) { const string errmsg = "Don't call Load() when the Character's state is not persistent!"; if (log.IsErrorEnabled) log.Error(errmsg); Debug.Fail(errmsg); return; } var items = DbController.GetQuery<SelectCharacterEquippedItemsQuery>().Execute(Character.ID); // Remove the listeners since we don't want to update the database when loading _ignoreEquippedBaseEvents = true; // Load all the items foreach (var item in items) { var itemEntity = new ItemEntity(item.Value); if (TrySetSlot(item.Key, itemEntity)) { SendSlotUpdate(item.Key, itemEntity.GraphicIndex); _paperDoll.NotifyAdded(item.Key, itemEntity); } else Debug.Fail("Uhm, the Character couldn't load their equipped item. What should we do...?"); } _ignoreEquippedBaseEvents = false; } /// <summary> /// When overridden in the derived class, handles when an item has been equipped. /// </summary> /// <param name="item">The item the event is related to.</param> /// <param name="slot">The slot of the item the event is related to.</param> protected override void OnEquipped(ItemEntity item, EquipmentSlot slot) { if (_ignoreEquippedBaseEvents) return; Debug.Assert(item != null); item.IsPersistent = IsPersistent; if (IsPersistent) { var values = new CharacterEquippedTable(Character.ID, item.ID, slot); DbController.GetQuery<InsertCharacterEquippedItemQuery>().Execute(values); } SendSlotUpdate(slot, item.GraphicIndex); _paperDoll.NotifyAdded(slot, item); } /// <summary> /// When overridden in the derived class, handles when an item has been removed. /// </summary> /// <param name="item">The item the event is related to.</param> /// <param name="slot">The slot of the item the event is related to.</param> protected override void OnUnequipped(ItemEntity item, EquipmentSlot slot) { if (_ignoreEquippedBaseEvents) return; Debug.Assert(item != null); if (IsPersistent) DbController.GetQuery<DeleteCharacterEquippedItemQuery>().Execute(Character.ID, slot); SendSlotUpdate(slot, null); // Do not try working with a disposed ItemEntity! Instead, just let it die off. if (item.IsDisposed) return; var remainder = Character.Inventory.TryAdd(item); if (remainder != null) { const string errmsg = "Character `{0}` removed equipped item `{1}` from slot `{2}`, " + "but not all could be added back to their Inventory."; if (log.IsWarnEnabled) log.WarnFormat(errmsg, Character, item, slot); // Make the Character drop the remainder Character.DropItem(remainder); } _paperDoll.NotifyRemoved(slot); // Make sure we dispose of items where the amount hit 0 if (item.Amount == 0) item.Destroy(); } /// <summary> /// When overridden in the derived class, notifies the owner of this object instance /// that an equipment slot has changed. /// </summary> /// <param name="slot">The slot that changed.</param> /// <param name="graphicIndex">The new graphic index of the slot.</param> protected virtual void SendSlotUpdate(EquipmentSlot slot, GrhIndex? graphicIndex) { } /// <summary> /// Sends the paper-doll information for this <see cref="Character"/> to a specific client. /// </summary> /// <param name="client">The client to send this <see cref="Character"/>'s paper-doll information to.</param> public void SynchronizePaperdollTo(INetworkSender client) { _paperDoll.SynchronizeBodyLayersTo(client); } #region IModStatContainer<StatType> Members /// <summary> /// Gets the modifier value for the given <paramref name="statType"/>, where a positive value adds to the /// mod stat value, a negative value subtracts from the mod stat value, and a value of 0 does not modify /// the mod stat value. /// </summary> /// <param name="statType">The <see cref="StatType"/> to get the modifier value for.</param> /// <returns> /// The modifier value for the given <paramref name="statType"/>. /// </returns> public int GetStatModBonus(StatType statType) { var sum = 0; foreach (var item in Items) { sum += item.BaseStats[statType]; } return sum; } #endregion /// <summary> /// Handles the synchronization of a <see cref="Character"/>'s paper-doll layers. /// </summary> class EquippedPaperDoll { static readonly int _maxSlotValue = EnumHelper<EquipmentSlot>.MaxValue + 1; readonly string[] _bodies; readonly Character _character; /// <summary> /// Initializes a new instance of the <see cref="EquippedPaperDoll"/> class. /// </summary> /// <param name="character">The <see cref="Character"/>.</param> public EquippedPaperDoll(Character character) { _bodies = new string[_maxSlotValue]; _character = character; } /// <summary> /// Notifies this object when an item has been added into an <see cref="EquipmentSlot"/>. /// </summary> /// <param name="slot">The <see cref="EquipmentSlot"/> the item was added to.</param> /// <param name="item">The item.</param> public void NotifyAdded(EquipmentSlot slot, IItemTable item) { // Get the ID of the slot var slotID = slot.GetValue(); // Check if there is a paper-doll item in the slot already. If so, remove it. if (_bodies[slotID] != null) NotifyRemoved(slot); // Check that the new item has a paper-doll value if (string.IsNullOrEmpty(item.EquippedBody)) return; // The new item has a paper-doll value, so add it and synchronize _bodies[slotID] = item.EquippedBody; SynchronizeBodyLayers(); } /// <summary> /// Notifies this object when an item has been removed from an <see cref="EquipmentSlot"/>. /// </summary> /// <param name="slot">The <see cref="EquipmentSlot"/> the item was removed from.</param> public void NotifyRemoved(EquipmentSlot slot) { // Get the ID of the slot var slotID = slot.GetValue(); // Check if there was a paper-doll item in the slot if (_bodies[slotID] == null) return; // There was a paper-doll item in the slot, so remove it and synchronize _bodies[slotID] = null; SynchronizeBodyLayers(); } /// <summary> /// Handles synchronizing the paper-doll information to other clients. /// </summary> void SynchronizeBodyLayers() { // Get the map var map = _character.Map; if (map == null) return; // Send the list of set paper-doll values using (var pw = ServerPacket.SetCharacterPaperDoll(_character.MapEntityIndex, _bodies.Where(x => x != null))) { _character.Map.Send(pw, ServerMessageType.MapDynamicEntityProperty); } } /// <summary> /// Handles synchronizing the paper-doll information to a single client. /// </summary> /// <param name="client">The client to send the information to</param> internal void SynchronizeBodyLayersTo(INetworkSender client) { // Get the values to send var bodiesToSend = _bodies.Where(x => x != null); if (bodiesToSend.IsEmpty()) return; // Send the paper-doll information using (var pw = ServerPacket.SetCharacterPaperDoll(_character.MapEntityIndex, bodiesToSend)) { client.Send(pw, ServerMessageType.MapDynamicEntityProperty); } } } } }
using System; using CoreGraphics; using Foundation; using UIKit; using CoreAnimation; namespace Curse { public class CRSAlertView : UIView { #region Properties const float AnimationDuration = 0.15f; const float pad = 20.0f; bool _displayOverAlert = true; // UI UIView _alertContainer; UIView _bottomSeparator; UIImageView _image; UILabel _title; UILabel _message; // Colors public static UIColor Tint = UIColor.FromRGB (3, 127, 241); public static UIColor Background = UIColor.FromRGB(0xf3, 0xf3, 0xf3); public static UIColor TitleTextColor = UIColor.Black; public static UIColor MessageTextColor = UIColor.Black; public static UIColor InputTextColor = UIColor.Black; public static UIColor ButtonBackground = UIColor.FromRGB (228, 228, 228); public static UIColor ButtonHighlighted = UIColor.FromRGB (210, 210, 210); public static UIColor SeparatorColor = UIColor.FromRGB( 212, 212, 212 ); // Fonts public static UIFont TitleFont = UIFont.BoldSystemFontOfSize (18f); public static UIFont MessageFont = UIFont.SystemFontOfSize (14f); public static UIFont InputFont = UIFont.SystemFontOfSize(14f); public static UIFont AlertButtonHighlightedFont = UIFont.BoldSystemFontOfSize(16f); public static UIFont AlertButtonNormalFont = UIFont.SystemFontOfSize(16f); // Input UILabel _inputLabel; UITextField _inputTextField; UIImageView _inputImage; UIButton _inputButton; string _t; public string Title { get { return _t; } set { _t = value; if (_title != null) { _title.Text = value; } } } string _m; public string Message { get { return _m; } set { _m = value; if (_message != null) { _message.Text = value; } } } public UIImage Image { get; set; } public CRSAlertInput Input { get; set; } public CRSAlertAction[] Actions { get; set; } public bool IsShowing { get { return Superview != null; } } public static UIWindow AlertWindow; static UIWindow PreviousKeyWindow; static int AlertsDisplayed; #endregion #region Constructors public CRSAlertView() { NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillHideNotification, OnKeyboardNotification); NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillShowNotification, OnKeyboardNotification); } public static CRSAlertView Error(string title, string message, UIImage image = null, string buttonTitle = "Ok") { var action = new CRSAlertAction { Text = buttonTitle, Highlighted = true, TintColor = Tint }; return new CRSAlertView { Title = title, Message = message, Image = image != null ? image : UIImage.FromBundle(""), Actions = new CRSAlertAction[] { action }, }; } #endregion #region UI void CreateAlertWindow() { if (CRSAlertView.AlertWindow == null) { CRSAlertView.AlertWindow = new UIWindow (UIScreen.MainScreen.Bounds) { BackgroundColor = UIColor.Clear }; } } private void MakeUI() { CreateAlertWindow (); // Needs these parameters if (CRSAlertView.AlertWindow == null || Title == null || Actions == null || Actions.Length == 0) { throw new ModelNotImplementedException(); } // Build Main View Alpha = 0f; BackgroundColor = UIColor.Black.ColorWithAlpha (0.75f); Frame = CRSAlertView.AlertWindow.Bounds; // Build Container nfloat imageWidth = 40f; nfloat buttonWidth = (CRSAlertView.AlertWindow.Frame.Width - 2 * pad) / Actions.Length; nfloat buttonHeight = 60f; _alertContainer = new UIView { Frame = new CGRect (pad, 0, CRSAlertView.AlertWindow.Frame.Width - 2 * pad, pad), BackgroundColor = Background, Alpha = 0f }; _alertContainer.Layer.CornerRadius = 10.0f; _alertContainer.Layer.MasksToBounds = true; _image = new UIImageView { Frame = new CGRect (_alertContainer.Frame.Width/2 - imageWidth/2, pad, Image != null ? imageWidth : 0, Image != null ? imageWidth : 0), BackgroundColor = UIColor.Clear, TintColor = TitleTextColor, Image = Image ?? new UIImage(), ContentMode = UIViewContentMode.ScaleAspectFit }; _title = new UILabel { Frame = new CGRect( pad/2, _image.Frame.Width > 0 ? _image.Frame.Bottom + 5 : pad, _alertContainer.Frame.Width - pad, 24.0f), Text = Title, TextColor = TitleTextColor, Font = TitleFont, Lines = 1, AdjustsFontSizeToFitWidth = true, MinimumScaleFactor = 0.5f, TextAlignment = UITextAlignment.Center }; _message = new UILabel { Frame = new CGRect( pad/2, _title.Frame.Bottom + 2, _alertContainer.Frame.Width - pad, 20.0f), Text = Message, TextColor = MessageTextColor, Font = MessageFont, Lines = 0, TextAlignment = UITextAlignment.Center }; _message.SizeToFit (); _message.Center = new CGPoint (_title.Center.X, _message.Center.Y); if (Input != null) { _inputImage = new UIImageView { Frame = new CGRect(pad/2, _message.Frame.Bottom + pad/2, Input.Image != null ? 20 : 0, Input.Image != null ? 20 : 0), Image = Input.Image ?? new UIImage(), TintColor = Input.TintColor != null ? Input.TintColor : Tint }; var startX = Input.Image != null ? pad / 2 + 30 : pad / 2; _inputTextField = new UITextField { Frame = new CGRect(startX, _message.Frame.Bottom + pad/2, _alertContainer.Frame.Width - _inputImage.Frame.Right - 20, 30), BackgroundColor = UIColor.White, Placeholder = Input.Placeholder != null ? Input.Placeholder : "", Text = Input.Text != null ? Input.Text : "", TextColor = InputTextColor, Font = InputFont, BorderStyle = UITextBorderStyle.None, Alpha = 0f, Delegate = new InputSource(), ReturnKeyType = UIReturnKeyType.Done, KeyboardAppearance = UIKeyboardAppearance.Dark }; _inputTextField.Layer.SublayerTransform = CATransform3D.MakeTranslation (5.0f, 0.0f, 0.0f); _inputLabel = new UILabel { Frame = new CGRect(startX, _message.Frame.Bottom + pad/2, _alertContainer.Frame.Width - _inputImage.Frame.Right + 20, 30), TextColor = Input.TintColor != null ? Input.TintColor : Tint, Text = Input.Placeholder != null ? Input.Placeholder : "", Alpha = 0, Font = InputFont }; _inputButton = new UIButton { BackgroundColor = UIColor.Clear }; _inputButton.TouchUpInside += (sender, e) => { ShowInputTextField(); }; _alertContainer.AddSubviews (new UIView[] { _inputImage, _inputLabel, _inputButton, _inputTextField }); if (Input.OpenAutomatically) { _inputButton.Hidden = true; _inputTextField.Alpha = 1f; _inputImage.Center = new CGPoint (_inputImage.Center.X, _inputTextField.Center.Y); } else { _inputLabel.SizeToFit (); _inputLabel.Alpha = 1f; nfloat width = _inputImage.Frame.Width + 10 + _inputLabel.Frame.Width; _inputImage.Frame = new CGRect (_alertContainer.Frame.Width / 2 - width / 2, _inputImage.Frame.Top, _inputImage.Frame.Width, _inputImage.Frame.Height); _inputLabel.Frame = new CGRect (_inputImage.Frame.Right + 10, _inputLabel.Frame.Top, _inputLabel.Frame.Width, _inputLabel.Frame.Height); _inputImage.Center = new CGPoint (_inputImage.Center.X, _inputLabel.Center.Y); _inputButton.Frame = new CGRect (_inputImage.Frame.Left, _inputLabel.Frame.Top, width, 44); _inputButton.Center = new CGPoint (_inputButton.Center.X, _inputLabel.Center.Y); } } _bottomSeparator = new UIView { Frame = new CGRect(0, Input == null ? _message.Frame.Bottom + pad : _inputLabel.Frame.Bottom + pad, _alertContainer.Frame.Width, 1), BackgroundColor = SeparatorColor }; _alertContainer.AddSubviews (new UIView[] { _image, _title, _message, _bottomSeparator }); for (int i = 0; i < Actions.Length; i++) { CRSAlertAction action = Actions [i]; var btn = new UIButton { Frame = new CGRect(buttonWidth*i, _bottomSeparator.Frame.Bottom, buttonWidth, buttonHeight), BackgroundColor = ButtonBackground, Font = action.Highlighted ? AlertButtonHighlightedFont : AlertButtonNormalFont }; btn.ContentMode = UIViewContentMode.ScaleAspectFit; btn.SetTitle (string.IsNullOrEmpty (action.Text) ? "" : action.Text, UIControlState.Normal); btn.Tag = i; btn.TouchDown += (sender, e) => { btn.BackgroundColor = ButtonHighlighted; }; btn.TouchUpOutside += (sender, e) => { btn.BackgroundColor = ButtonBackground; }; btn.TouchUpInside += (sender, e) => { DidSelectAction((int)btn.Tag); }; btn.SetTitleColor (action.Highlighted ? (action.TintColor ?? Tint) : TitleTextColor, UIControlState.Normal); _alertContainer.Add (btn); if (i < Actions.Length - 1) { var s = new UIView { Frame = new CGRect(btn.Frame.Right - 1, btn.Frame.Top, 1, buttonHeight), BackgroundColor = SeparatorColor }; _alertContainer.Add (s); } } nfloat alertEnd = (_alertContainer.Subviews[_alertContainer.Subviews.Length - 1] as UIView).Frame.Bottom; _alertContainer.Frame = new CGRect (_alertContainer.Frame.Left, _alertContainer.Frame.Top, _alertContainer.Frame.Width, alertEnd); _alertContainer.Center = new CGPoint (CRSAlertView.AlertWindow.Frame.Width / 2, CRSAlertView.AlertWindow.Frame.Height / 2); Add (_alertContainer); } #endregion #region Showing/Hiding public void Show(float duration = AnimationDuration*2) { if( !_displayOverAlert && AlertsDisplayed > 0 ) { return; } if (_alertContainer == null) { MakeUI (); } CRSAlertView.PreviousKeyWindow = UIApplication.SharedApplication.KeyWindow; CRSAlertView.PreviousKeyWindow.EndEditing (true); CRSAlertView.AlertWindow.Alpha = 0f; Alpha = 0; _alertContainer.Alpha = 0f; CRSAlertView.AlertWindow.RootViewController = new AlertViewController (this); CRSAlertView.AlertWindow.MakeKeyAndVisible (); UIView.Animate (duration/2, () => { CRSAlertView.AlertWindow.Alpha = 1f; Alpha = 1; }, () => { if (UIApplication.SharedApplication.KeyWindow != CRSAlertView.AlertWindow) { CRSAlertView.AlertWindow.MakeKeyAndVisible(); } UIView.Animate(duration/2, () => { _alertContainer.Alpha = 1f; }, () => { if (Input != null && Input.OpenAutomatically) { _inputTextField.BecomeFirstResponder (); } }); }); } public void Hide(Action<CRSAlertView> didHide = null, float duration = AnimationDuration, UIWindow window = null) { --AlertsDisplayed; if (CRSAlertView.AlertWindow == null) { return; } if (_inputTextField != null && _inputTextField.IsFirstResponder) { _alertContainer.EndEditing (true); } UIView.Animate (AnimationDuration, () => { Alpha = 0f; CRSAlertView.AlertWindow.Alpha = 0f; }, () => { CRSAlertView.AlertWindow.RootViewController = new UIViewController(); if( CRSAlertView.PreviousKeyWindow == null || CRSAlertView.PreviousKeyWindow.Hidden ) { window = window ?? UIApplication.SharedApplication.KeyWindow; window.MakeKeyAndVisible(); } else { CRSAlertView.PreviousKeyWindow.MakeKeyAndVisible(); } if( didHide != null ) didHide( this ); }); } private void ShowInputTextField() { _inputButton.Hidden = true; UIView.Animate (AnimationDuration, () => { _inputLabel.Alpha = 0f; _inputImage.Frame = new CGRect (pad/2, _inputImage.Frame.Top, _inputImage.Frame.Width, _inputImage.Frame.Height); _inputImage.Center = new CGPoint (_inputImage.Center.X, _inputTextField.Center.Y); }, () => { _inputTextField.Alpha = 1f; _inputTextField.BecomeFirstResponder(); }); } #endregion #region Did Select public void DidSelectAction(int i) { if (Input != null) { Input.Text = _inputTextField.Text; } Hide (Actions[i].DidSelect); } #endregion #region TextFieldSource class InputSource : UITextFieldDelegate { public InputSource(){} public override bool ShouldReturn(UITextField textField) { textField.ResignFirstResponder (); return true; } } #endregion #region Keyboard Notifications private void OnKeyboardNotification (NSNotification notification) { //Check if the keyboard is becoming visible bool visible = notification.Name == UIKeyboard.WillShowNotification; //Start an animation, using values from the keyboard UIView.BeginAnimations ("AnimateForKeyboard"); UIView.SetAnimationBeginsFromCurrentState (true); UIView.SetAnimationDuration (UIKeyboard.AnimationDurationFromNotification (notification)); UIView.SetAnimationCurve ((UIViewAnimationCurve)UIKeyboard.AnimationCurveFromNotification (notification)); //Pass the notification, calculating keyboard height, etc. if (visible) { var keyboardFrame = UIKeyboard.FrameEndFromNotification (notification); OnKeyboardChanged (visible, keyboardFrame.Height); } else { var keyboardFrame = UIKeyboard.FrameBeginFromNotification (notification); OnKeyboardChanged (visible, keyboardFrame.Height); } //Commit the animation UIView.CommitAnimations (); } protected void OnKeyboardChanged (bool visible, nfloat height) { CreateAlertWindow (); if( _alertContainer == null ) return; if (visible) { _alertContainer.Frame = new CGRect (_alertContainer.Frame.Left, CRSAlertView.AlertWindow.Frame.Height - height - pad - _alertContainer.Frame.Height, _alertContainer.Frame.Width, _alertContainer.Frame.Height); } else { _alertContainer.Center = new CGPoint (CRSAlertView.AlertWindow.Frame.Width / 2, CRSAlertView.AlertWindow.Frame.Height / 2); } } #endregion #region View Controller class AlertViewController : UIViewController { readonly CRSAlertView _alert; public AlertViewController(CRSAlertView alert) { _alert = alert; } public override void ViewDidLoad() { base.ViewDidLoad (); View.BackgroundColor = UIColor.Clear; View.AddSubview(_alert); } } #endregion } #region Alert Action public class CRSAlertAction { public string Text { get; set; } public bool Highlighted { get; set; } public UIColor TintColor { get; set; } public Action<CRSAlertView> DidSelect { get; set; } } #endregion #region Alert Input public class CRSAlertInput { public UIImage Image { get; set; } public string Placeholder { get; set; } public string Text { get; set; } public UIColor TintColor { get; set; } public bool OpenAutomatically { get; set; } } #endregion }
#pragma warning disable 109, 114, 219, 429, 168, 162 namespace pony { public class DeltaTime : global::haxe.lang.HxObject { static DeltaTime() { #line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" { #line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" { #line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.events.Signal this1 = global::pony.events.Signal.createEmpty(); #line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.DeltaTime.update = ((global::pony.events.Signal) (this1) ); } #line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" { #line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.events.Signal this2 = global::pony.events.Signal.createEmpty(); #line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.DeltaTime.fixedUpdate = ((global::pony.events.Signal) (this2) ); } } #line 39 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.DeltaTime.speed = ((double) (1) ); #line 42 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.DeltaTime.@value = ((double) (0) ); global::pony.DeltaTime.fixedValue = ((double) (0) ); } public DeltaTime(global::haxe.lang.EmptyObject empty) { unchecked { #line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" { } } #line default } public DeltaTime() { unchecked { #line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.DeltaTime.__hx_ctor_pony_DeltaTime(this); } #line default } public static void __hx_ctor_pony_DeltaTime(global::pony.DeltaTime __temp_me93) { unchecked { #line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" { } } #line default } public static double speed; public static global::pony.events.Signal update; public static global::pony.events.Signal fixedUpdate; public static double @value; public static double fixedValue; public static double t; public static void tick() { unchecked { #line 55 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" double __temp_stmt419 = default(double); #line 55 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" { #line 55 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::Date _this = global::Date.now(); #line 55 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" __temp_stmt419 = ( ((double) (_this.date.Ticks) ) / ((double) (global::System.TimeSpan.TicksPerMillisecond) ) ); } #line 55 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.DeltaTime.fixedValue = ( (( __temp_stmt419 - global::pony.DeltaTime.t )) / 1000 ); { #line 56 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::Date _this1 = global::Date.now(); #line 56 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.DeltaTime.t = ( ((double) (_this1.date.Ticks) ) / ((double) (global::System.TimeSpan.TicksPerMillisecond) ) ); } global::pony.DeltaTime.@value = ( global::pony.DeltaTime.fixedValue * global::pony.DeltaTime.speed ); { #line 58 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.events.Signal this1 = global::pony.DeltaTime.update; #line 58 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" { #line 58 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" this1.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<double>(new double[]{global::pony.DeltaTime.@value})) ), ((object) (this1.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) ))); #line 58 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.events.Signal __temp_expr420 = this1; } #line 58 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" object __temp_expr421 = this1.target; } { #line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.events.Signal this2 = global::pony.DeltaTime.fixedUpdate; #line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" { #line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" this2.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<double>(new double[]{global::pony.DeltaTime.fixedValue})) ), ((object) (this2.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) ))); #line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.events.Signal __temp_expr422 = this2; } #line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" object __temp_expr423 = this2.target; } } #line default } public static void @set() { unchecked { #line 62 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" { #line 62 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::Date _this = global::Date.now(); #line 62 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.DeltaTime.t = ( ((double) (_this.date.Ticks) ) / ((double) (global::System.TimeSpan.TicksPerMillisecond) ) ); } } #line default } public static double @get() { unchecked { #line 63 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" double __temp_stmt424 = default(double); #line 63 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" { #line 63 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::Date _this = global::Date.now(); #line 63 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" __temp_stmt424 = ( ((double) (_this.date.Ticks) ) / ((double) (global::System.TimeSpan.TicksPerMillisecond) ) ); } #line 63 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" return ( (( __temp_stmt424 - global::pony.DeltaTime.t )) / 1000 ); } #line default } public static void createSignals() { unchecked { #line 88 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" { #line 88 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.events.Signal this1 = global::pony.events.Signal.createEmpty(); #line 88 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.DeltaTime.update = ((global::pony.events.Signal) (this1) ); } { #line 89 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.events.Signal this2 = global::pony.events.Signal.createEmpty(); #line 89 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.DeltaTime.fixedUpdate = ((global::pony.events.Signal) (this2) ); } } #line default } public static void testRun(global::haxe.lang.Null<double> sec) { unchecked { #line 96 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" double __temp_sec92 = ( (global::haxe.lang.Runtime.eq((sec).toDynamic(), (default(global::haxe.lang.Null<double>)).toDynamic())) ? (((double) (60) )) : (sec.@value) ); int d = default(int); #line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" if (( __temp_sec92 < 100 )) { #line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" d = 10; } else { #line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" if (( __temp_sec92 < 1000 )) { #line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" d = 50; } else { #line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" d = 100; } } while (( __temp_sec92 > 0 )) { double r = ( global::Math.rand.NextDouble() * d ); if (( __temp_sec92 >= r )) { __temp_sec92 -= r; } else { #line 103 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" r = __temp_sec92; __temp_sec92 = ((double) (0) ); } #line 106 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" { #line 106 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.events.Signal this1 = global::pony.DeltaTime.update; #line 106 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" { #line 106 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" this1.dispatchEvent(new global::pony.events.Event(((global::Array) (new global::Array<double>(new double[]{r})) ), ((object) (this1.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) ))); #line 106 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" global::pony.events.Signal __temp_expr425 = this1; } #line 106 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" object __temp_expr426 = this1.target; } } } #line default } public static new object __hx_createEmpty() { unchecked { #line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" return new global::pony.DeltaTime(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) )); } #line default } public static new object __hx_create(global::Array arr) { unchecked { #line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/DeltaTime.hx" return new global::pony.DeltaTime(); } #line default } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.ServiceModel; using System.ServiceModel.Channels; using TestTypes; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; public static class TypedProxyTests { // ServiceContract typed proxy tests create a ChannelFactory using a provided [ServiceContract] Interface which... // returns a generated proxy based on that Interface. // ChannelShape typed proxy tests create a ChannelFactory using a WCF understood channel shape which... // returns a generated proxy based on the channel shape used, such as... // IRequestChannel (for a request-reply message exchange pattern) // IDuplexChannel (for a two-way duplex message exchange pattern) private const string action = "http://tempuri.org/IWcfService/MessageRequestReply"; private const string clientMessage = "[client] This is my request."; static TimeSpan maxTestWaitTime = TimeSpan.FromSeconds(10); [Fact] [OuterLoop] public static void ServiceContract_TypedProxy_AsyncBeginEnd_Call() { CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); ServiceContract_TypedProxy_AsyncBeginEnd_Call(customBinding, Endpoints.DefaultCustomHttp_Address, "ServiceContract_TypedProxy_AsyncBeginEnd_Call"); } [Fact] [OuterLoop] public static void ServiceContract_TypedProxy_NetTcpBinding_AsyncBeginEnd_Call() { NetTcpBinding netTcpBinding = new NetTcpBinding(SecurityMode.None); ServiceContract_TypedProxy_AsyncBeginEnd_Call(netTcpBinding, Endpoints.Tcp_NoSecurity_Address, "ServiceContract_TypedProxy_NetTcpBinding_AsyncBeginEnd_Call"); } [Fact] [OuterLoop] public static void ServiceContract_TypedProxy_AsyncBeginEnd_Call_WithNoCallback() { CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); ServiceContract_TypedProxy_AsyncBeginEnd_Call_WithNoCallback(customBinding, Endpoints.DefaultCustomHttp_Address, "ServiceContract_TypedProxy_AsyncBeginEnd_Call_WithNoCallback"); } [Fact] [OuterLoop] public static void ServiceContract_TypedProxy_NetTcpBinding_AsyncBeginEnd_Call_WithNoCallback() { NetTcpBinding netTcpBinding = new NetTcpBinding(SecurityMode.None); ServiceContract_TypedProxy_AsyncBeginEnd_Call_WithNoCallback(netTcpBinding, Endpoints.Tcp_NoSecurity_Address, "ServiceContract_TypedProxy_NetTcpBinding_AsyncBeginEnd_Call_WithNoCallback"); } [Fact] [OuterLoop] public static void ServiceContract_TypedProxy_AsyncBeginEnd_Call_WithSingleThreadedSyncContext() { bool success = Task.Run(() => { SingleThreadSynchronizationContext.Run(() => { Task.Factory.StartNew(() => TypedProxyTests.ServiceContract_TypedProxy_AsyncBeginEnd_Call(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait(); }); }).Wait(ScenarioTestHelpers.TestTimeout); Assert.True(success, "Test Scenario: TypedProxy_AsyncBeginEnd_Call_WithSingleThreadedSyncContext timed out"); } [Fact] [OuterLoop] public static void ServiceContract_TypedProxy_NetTcpBinding_AsyncBeginEnd_Call_WithSingleThreadedSyncContext() { bool success = Task.Run(() => { SingleThreadSynchronizationContext.Run(() => { Task.Factory.StartNew(() => TypedProxyTests.ServiceContract_TypedProxy_NetTcpBinding_AsyncBeginEnd_Call(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait(); }); }).Wait(ScenarioTestHelpers.TestTimeout); Assert.True(success, "Test Scenario: ServiceContract_TypedProxy_NetTcpBinding_AsyncBeginEnd_Call_WithSingleThreadedSyncContext timed out"); } [Fact] [OuterLoop] public static void ServiceContract_TypedProxy_AsyncTask_Call() { CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); ServiceContract_TypedProxy_AsyncTask_Call(customBinding, Endpoints.DefaultCustomHttp_Address, "ServiceContract_TypedProxy_AsyncTask_Call"); } [Fact] [OuterLoop] public static void ServiceContract_TypedProxy_NetTcpBinding_AsyncTask_Call() { NetTcpBinding netTcpBinding = new NetTcpBinding(); netTcpBinding.Security.Mode = SecurityMode.None; ServiceContract_TypedProxy_AsyncTask_Call(netTcpBinding, Endpoints.Tcp_NoSecurity_Address, "ServiceContract_TypedProxy_NetTcpBinding_AsyncTask_Call"); } [Fact] [OuterLoop] public static void ServiceContract_TypedProxy_AsyncTask_Call_WithSingleThreadedSyncContext() { bool success = Task.Run(() => { SingleThreadSynchronizationContext.Run(() => { Task.Factory.StartNew(() => TypedProxyTests.ServiceContract_TypedProxy_AsyncTask_Call(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait(); }); }).Wait(ScenarioTestHelpers.TestTimeout); Assert.True(success, "Test Scenario: TypedProxy_AsyncTask_Call_WithSingleThreadedSyncContext timed out"); } [Fact] [OuterLoop] public static void ServiceContract_TypedProxy__NetTcpBinding_AsyncTask_Call_WithSingleThreadedSyncContext() { bool success = Task.Run(() => { SingleThreadSynchronizationContext.Run(() => { Task.Factory.StartNew(() => TypedProxyTests.ServiceContract_TypedProxy_NetTcpBinding_AsyncTask_Call(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait(); }); }).Wait(ScenarioTestHelpers.TestTimeout); Assert.True(success, "Test Scenario: ServiceContract_TypedProxy__NetTcpBinding_AsyncTask_Call_WithSingleThreadedSyncContext timed out"); } [Fact] [OuterLoop] public static void ServiceContract_TypedProxy_Synchronous_Call() { // This test verifies a typed proxy can call a service operation synchronously StringBuilder errorBuilder = new StringBuilder(); try { CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); // Note the service interface used. It was manually generated with svcutil. ChannelFactory<IWcfServiceGenerated> factory = new ChannelFactory<IWcfServiceGenerated>(customBinding, new EndpointAddress(Endpoints.DefaultCustomHttp_Address)); IWcfServiceGenerated serviceProxy = factory.CreateChannel(); string result = serviceProxy.Echo("Hello"); if (!string.Equals(result, "Hello")) { errorBuilder.AppendLine(String.Format("Expected response from Service: {0} Actual was: {1}", "Hello", result)); } factory.Close(); } catch (Exception ex) { errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString())); } Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: TypedProxySynchronousCall FAILED with the following errors: {0}", errorBuilder)); } [Fact] [OuterLoop] public static void ServiceContract_TypedProxy_Synchronous_Call_WithSingleThreadedSyncContext() { bool success = Task.Run(() => { TestTypes.SingleThreadSynchronizationContext.Run(() => { Task.Factory.StartNew(() => TypedProxyTests.ServiceContract_TypedProxy_Synchronous_Call(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait(); }); }).Wait(ScenarioTestHelpers.TestTimeout); Assert.True(success, "Test Scenario: TypedProxy_Synchronous_Call_WithSingleThreadedSyncContext timed out"); } [Fact] [OuterLoop] public static void ServiceContract_TypedProxy_Task_Call_WithSyncContext_ContinuesOnSameThread() { // This test verifies a task based call to a service operation continues on the same thread StringBuilder errorBuilder = new StringBuilder(); try { CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); ChannelFactory<IWcfServiceGenerated> factory = new ChannelFactory<IWcfServiceGenerated>(customBinding, new EndpointAddress(Endpoints.DefaultCustomHttp_Address)); IWcfServiceGenerated serviceProxy = factory.CreateChannel(); string result = String.Empty; bool success = Task.Run(() => { SingleThreadSynchronizationContext.Run(async delegate { int startThread = Environment.CurrentManagedThreadId; result = await serviceProxy.EchoAsync("Hello"); if (startThread != Environment.CurrentManagedThreadId) { errorBuilder.AppendLine(String.Format("Expected continuation to happen on thread {0} but actually continued on thread {1}", startThread, Environment.CurrentManagedThreadId)); } }); }).Wait(ScenarioTestHelpers.TestTimeout); if (!success) { errorBuilder.AppendLine(String.Format("Test didn't complete within the expected time")); } if (!string.Equals(result, "Hello")) { errorBuilder.AppendLine(String.Format("Expected response from Service: {0} Actual was: {1}", "Hello", result)); } factory.Close(); } catch (Exception ex) { errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString())); } Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: TaskCallWithSynchContextContinuesOnSameThread FAILED with the following errors: {0}", errorBuilder)); } [Fact] [OuterLoop] public static void ChannelShape_TypedProxy_InvokeIRequestChannel() { string address = Endpoints.DefaultCustomHttp_Address; StringBuilder errorBuilder = new StringBuilder(); try { CustomBinding binding = new CustomBinding(new BindingElement[] { new TextMessageEncodingBindingElement(MessageVersion.Default, Encoding.UTF8), new HttpTransportBindingElement() }); EndpointAddress endpointAddress = new EndpointAddress(address); // Create the channel factory for the request-reply message exchange pattern. var factory = new ChannelFactory<IRequestChannel>(binding, endpointAddress); // Create the channel. IRequestChannel channel = factory.CreateChannel(); channel.Open(); // Create the Message object to send to the service. Message requestMessage = Message.CreateMessage( binding.MessageVersion, action, new CustomBodyWriter(clientMessage)); // Send the Message and receive the Response. Message replyMessage = channel.Request(requestMessage); string replyMessageAction = replyMessage.Headers.Action; if (!string.Equals(replyMessageAction, action + "Response")) { errorBuilder.AppendLine(String.Format("A response was received from the Service but it was not the expected Action, expected: {0} actual: {1}", action + "Response", replyMessageAction)); } var replyReader = replyMessage.GetReaderAtBodyContents(); string actualResponse = replyReader.ReadElementContentAsString(); string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply."; if (!string.Equals(actualResponse, expectedResponse)) { errorBuilder.AppendLine(String.Format("Actual MessageBodyContent from service did not match the expected MessageBodyContent, expected: {0} actual: {1}", expectedResponse, actualResponse)); } replyMessage.Close(); channel.Close(); factory.Close(); } catch (Exception ex) { errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString())); } Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: InvokeRequestChannelViaProxy FAILED with the following errors: {0}", errorBuilder)); } [Fact] [OuterLoop] public static void ChannelShape_TypedProxy_InvokeIRequestChannelTimeout() { string address = Endpoints.DefaultCustomHttp_Address; StringBuilder errorBuilder = new StringBuilder(); try { CustomBinding binding = new CustomBinding(new BindingElement[] { new TextMessageEncodingBindingElement(MessageVersion.Default, Encoding.UTF8), new HttpTransportBindingElement() }); EndpointAddress endpointAddress = new EndpointAddress(address); // Create the channel factory for the request-reply message exchange pattern. var factory = new ChannelFactory<IRequestChannel>(binding, endpointAddress); // Create the channel. IRequestChannel channel = factory.CreateChannel(); channel.Open(); // Create the Message object to send to the service. Message requestMessage = Message.CreateMessage( binding.MessageVersion, action, new CustomBodyWriter(clientMessage)); // Send the Message and receive the Response. Message replyMessage = channel.Request(requestMessage, TimeSpan.FromSeconds(60)); string replyMessageAction = replyMessage.Headers.Action; if (!string.Equals(replyMessageAction, action + "Response")) { errorBuilder.AppendLine(String.Format("A response was received from the Service but it was not the expected Action, expected: {0} actual: {1}", action + "Response", replyMessageAction)); } var replyReader = replyMessage.GetReaderAtBodyContents(); string actualResponse = replyReader.ReadElementContentAsString(); string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply."; if (!string.Equals(actualResponse, expectedResponse)) { errorBuilder.AppendLine(String.Format("Actual MessageBodyContent from service did not match the expected MessageBodyContent, expected: {0} actual: {1}", expectedResponse, actualResponse)); } replyMessage.Close(); channel.Close(); factory.Close(); } catch (Exception ex) { errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString())); } Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: InvokeIRequestChannelViaProxyTimeout FAILED with the following errors: {0}", errorBuilder)); } [Fact] [OuterLoop] public static void ChannelShape_TypedProxy_InvokeIRequestChannelAsync() { string address = Endpoints.DefaultCustomHttp_Address; StringBuilder errorBuilder = new StringBuilder(); try { CustomBinding binding = new CustomBinding(new BindingElement[] { new TextMessageEncodingBindingElement(MessageVersion.Default, Encoding.UTF8), new HttpTransportBindingElement() }); EndpointAddress endpointAddress = new EndpointAddress(address); // Create the channel factory for the request-reply message exchange pattern. var factory = new ChannelFactory<IRequestChannel>(binding, endpointAddress); // Create the channel. IRequestChannel channel = factory.CreateChannel(); channel.Open(); // Create the Message object to send to the service. Message requestMessage = Message.CreateMessage( binding.MessageVersion, action, new CustomBodyWriter(clientMessage)); // Send the Message and receive the Response. IAsyncResult ar = channel.BeginRequest(requestMessage, null, null); Message replyMessage = channel.EndRequest(ar); string replyMessageAction = replyMessage.Headers.Action; if (!string.Equals(replyMessageAction, action + "Response")) { errorBuilder.AppendLine(String.Format("A response was received from the Service but it was not the expected Action, expected: {0} actual: {1}", action + "Response", replyMessageAction)); } var replyReader = replyMessage.GetReaderAtBodyContents(); string actualResponse = replyReader.ReadElementContentAsString(); string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply."; if (!string.Equals(actualResponse, expectedResponse)) { errorBuilder.AppendLine(String.Format("Actual MessageBodyContent from service did not match the expected MessageBodyContent, expected: {0} actual: {1}", expectedResponse, actualResponse)); } replyMessage.Close(); channel.Close(); factory.Close(); } catch (Exception ex) { errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString())); } Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: InvokeIRequestChannelViaProxyAsync FAILED with the following errors: {0}", errorBuilder)); } [Fact] [OuterLoop] public static void ServiceContract_TypedProxy_DuplexCallback() { DuplexChannelFactory<IDuplexChannelService> factory = null; StringBuilder errorBuilder = new StringBuilder(); Guid guid = Guid.NewGuid(); try { NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; DuplexChannelServiceCallback callbackService = new DuplexChannelServiceCallback(); InstanceContext context = new InstanceContext(callbackService); factory = new DuplexChannelFactory<IDuplexChannelService>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_DuplexCallback_Address)); IDuplexChannelService serviceProxy = factory.CreateChannel(); serviceProxy.Ping(guid); Guid returnedGuid = callbackService.CallbackGuid; if (guid != returnedGuid) { errorBuilder.AppendLine(String.Format("The sent GUID does not match the returned GUID. Sent: {0} Received: {1}", guid, returnedGuid)); } factory.Close(); } catch (Exception ex) { errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString())); for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException) { errorBuilder.AppendLine(String.Format("Inner exception: {0}", innerException.ToString())); } } finally { if (factory != null && factory.State != CommunicationState.Closed) { factory.Abort(); } } if (errorBuilder.Length != 0) { Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: ServiceContract_TypedProxy_DuplexCallback FAILED with the following errors: {0}", errorBuilder)); } } public class DuplexChannelServiceCallback : IDuplexChannelCallback { private TaskCompletionSource<Guid> _tcs; public DuplexChannelServiceCallback() { _tcs = new TaskCompletionSource<Guid>(); } public Guid CallbackGuid { get { if (_tcs.Task.Wait(maxTestWaitTime)) { return _tcs.Task.Result; } throw new TimeoutException(string.Format("Not completed within the alloted time of {0}", maxTestWaitTime)); } } public void OnPingCallback(Guid guid) { _tcs.SetResult(guid); } } [ServiceContract(CallbackContract = typeof(IDuplexChannelCallback))] public interface IDuplexChannelService { [OperationContract(IsOneWay = true)] void Ping(Guid guid); } public interface IDuplexChannelCallback { [OperationContract(IsOneWay = true)] void OnPingCallback(Guid guid); } private static void ServiceContract_TypedProxy_AsyncBeginEnd_Call(Binding binding, string endpoint, string testName) { // Verifies a typed proxy can call a service operation asynchronously using Begin/End StringBuilder errorBuilder = new StringBuilder(); try { ChannelFactory<IWcfServiceBeginEndGenerated> factory = new ChannelFactory<IWcfServiceBeginEndGenerated>(binding, new EndpointAddress(endpoint)); IWcfServiceBeginEndGenerated serviceProxy = factory.CreateChannel(); string result = null; ManualResetEvent waitEvent = new ManualResetEvent(false); // The callback is optional with this Begin call, but we want to test that it works. // This delegate should execute when the call has completed, and that is how it gets the result of the call. AsyncCallback callback = (iar) => { result = serviceProxy.EndEcho(iar); waitEvent.Set(); }; IAsyncResult ar = serviceProxy.BeginEcho("Hello", callback, null); // This test requires the callback to be called. // An actual timeout should call the callback, but we still set // a maximum wait time in case that does not happen. bool success = waitEvent.WaitOne(ScenarioTestHelpers.TestTimeout); if (!success) { errorBuilder.AppendLine("AsyncCallback was not called."); } if (!string.Equals(result, "Hello")) { errorBuilder.AppendLine(String.Format("Expected response from Service: {0} Actual was: {1}", "Hello", result)); } factory.Close(); } catch (Exception ex) { errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString())); } Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: {0} FAILED with the following errors: {1}", testName, errorBuilder)); } private static void ServiceContract_TypedProxy_AsyncBeginEnd_Call_WithNoCallback(Binding binding, string endpoint, string testName) { // This test verifies a typed proxy can call a service operation asynchronously using Begin/End StringBuilder errorBuilder = new StringBuilder(); try { ChannelFactory<IWcfServiceBeginEndGenerated> factory = new ChannelFactory<IWcfServiceBeginEndGenerated>(binding, new EndpointAddress(endpoint)); IWcfServiceBeginEndGenerated serviceProxy = factory.CreateChannel(); string result = null; IAsyncResult ar = serviceProxy.BeginEcho("Hello", null, null); // An actual timeout should complete the ar, but we still set // a maximum wait time in case that does not happen. bool success = ar.AsyncWaitHandle.WaitOne(ScenarioTestHelpers.TestTimeout); if (success) { result = serviceProxy.EndEcho(ar); } else { errorBuilder.AppendLine("AsyncCallback was not called."); } if (!string.Equals(result, "Hello")) { errorBuilder.AppendLine(String.Format("Expected response from Service: {0} Actual was: {1}", "Hello", result)); } factory.Close(); } catch (Exception ex) { errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString())); } Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: {0} FAILED with the following errors: {1}", testName, errorBuilder)); } private static void ServiceContract_TypedProxy_AsyncTask_Call(Binding binding, string endpoint, string testName) { // This test verifies a typed proxy can call a service operation asynchronously using Task<string> StringBuilder errorBuilder = new StringBuilder(); try { ChannelFactory<IWcfServiceGenerated> factory = new ChannelFactory<IWcfServiceGenerated>(binding, new EndpointAddress(endpoint)); IWcfServiceGenerated serviceProxy = factory.CreateChannel(); Task<string> task = serviceProxy.EchoAsync("Hello"); string result = task.Result; if (!string.Equals(result, "Hello")) { errorBuilder.AppendLine(String.Format("Expected response from Service: {0} Actual was: {1}", "Hello", result)); } factory.Close(); } catch (Exception ex) { errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString())); } Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: TypedProxyAsyncTaskCall FAILED with the following errors: {0}", errorBuilder)); } }
#pragma warning disable 1587 #region Header /// /// JsonWriter.cs /// Stream-like facility to output JSON text. /// /// The authors disclaim copyright to this source code. For more details, see /// the COPYING file included with this distribution. /// #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace ThirdParty.Json.LitJson { internal enum Condition { InArray, InObject, NotAProperty, Property, Value } internal class WriterContext { public int Count; public bool InArray; public bool InObject; public bool ExpectingValue; public int Padding; } public class JsonWriter { #region Fields private static NumberFormatInfo number_format; private WriterContext context; private Stack<WriterContext> ctx_stack; private bool has_reached_end; private char[] hex_seq; private int indentation; private int indent_value; private StringBuilder inst_string_builder; private bool pretty_print; private bool validate; private TextWriter writer; #endregion #region Properties public int IndentValue { get { return indent_value; } set { indentation = (indentation / indent_value) * value; indent_value = value; } } public bool PrettyPrint { get { return pretty_print; } set { pretty_print = value; } } public TextWriter TextWriter { get { return writer; } } public bool Validate { get { return validate; } set { validate = value; } } #endregion #region Constructors static JsonWriter () { number_format = NumberFormatInfo.InvariantInfo; } public JsonWriter () { inst_string_builder = new StringBuilder (); writer = new StringWriter (inst_string_builder); Init (); } public JsonWriter (StringBuilder sb) : this (new StringWriter (sb)) { } public JsonWriter (TextWriter writer) { if (writer == null) throw new ArgumentNullException ("writer"); this.writer = writer; Init (); } #endregion #region Private Methods private void DoValidation (Condition cond) { if (! context.ExpectingValue) context.Count++; if (! validate) return; if (has_reached_end) throw new JsonException ( "A complete JSON symbol has already been written"); switch (cond) { case Condition.InArray: if (! context.InArray) throw new JsonException ( "Can't close an array here"); break; case Condition.InObject: if (! context.InObject || context.ExpectingValue) throw new JsonException ( "Can't close an object here"); break; case Condition.NotAProperty: if (context.InObject && ! context.ExpectingValue) throw new JsonException ( "Expected a property"); break; case Condition.Property: if (! context.InObject || context.ExpectingValue) throw new JsonException ( "Can't add a property here"); break; case Condition.Value: if (! context.InArray && (! context.InObject || ! context.ExpectingValue)) throw new JsonException ( "Can't add a value here"); break; } } private void Init () { has_reached_end = false; hex_seq = new char[4]; indentation = 0; indent_value = 4; pretty_print = false; validate = true; ctx_stack = new Stack<WriterContext> (); context = new WriterContext (); ctx_stack.Push (context); } private static void IntToHex (int n, char[] hex) { int num; for (int i = 0; i < 4; i++) { num = n % 16; if (num < 10) hex[3 - i] = (char) ('0' + num); else hex[3 - i] = (char) ('A' + (num - 10)); n >>= 4; } } private void Indent () { if (pretty_print) indentation += indent_value; } private void Put (string str) { if (pretty_print && ! context.ExpectingValue) for (int i = 0; i < indentation; i++) writer.Write (' '); writer.Write (str); } private void PutNewline () { PutNewline (true); } private void PutNewline (bool add_comma) { if (add_comma && ! context.ExpectingValue && context.Count > 1) writer.Write (','); if (pretty_print && ! context.ExpectingValue) writer.Write ("\r\n"); } private void PutString (string str) { Put (String.Empty); writer.Write ('"'); int n = str.Length; for (int i = 0; i < n; i++) { char c = str[i]; switch (c) { case '\n': writer.Write ("\\n"); continue; case '\r': writer.Write ("\\r"); continue; case '\t': writer.Write ("\\t"); continue; case '"': case '\\': writer.Write ('\\'); writer.Write (c); continue; case '\f': writer.Write ("\\f"); continue; case '\b': writer.Write ("\\b"); continue; } if ((int) c >= 32 && (int) c <= 126) { writer.Write (c); continue; } if (c < ' ' || (c >= '\u0080' && c < '\u00a0')) { // Turn into a \uXXXX sequence IntToHex((int)c, hex_seq); writer.Write("\\u"); writer.Write(hex_seq); } else { writer.Write(c); } } writer.Write ('"'); } private void Unindent () { if (pretty_print) indentation -= indent_value; } #endregion public override string ToString () { if (inst_string_builder == null) return String.Empty; return inst_string_builder.ToString (); } public void Reset () { has_reached_end = false; ctx_stack.Clear (); context = new WriterContext (); ctx_stack.Push (context); if (inst_string_builder != null) inst_string_builder.Remove (0, inst_string_builder.Length); } public void Write (bool boolean) { DoValidation (Condition.Value); PutNewline (); Put (boolean ? "true" : "false"); context.ExpectingValue = false; } public void Write (decimal number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write (double number) { DoValidation (Condition.Value); PutNewline (); string str = Convert.ToString (number, number_format); Put (str); if (str.IndexOf ('.') == -1 && str.IndexOf ('E') == -1) writer.Write (".0"); context.ExpectingValue = false; } public void Write (int number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write (long number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number)); context.ExpectingValue = false; } public void Write (string str) { DoValidation (Condition.Value); PutNewline (); if (str == null) Put ("null"); else PutString (str); context.ExpectingValue = false; } [CLSCompliant(false)] public void Write (ulong number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write(DateTime date) { DoValidation(Condition.Value); PutNewline(); Put(Amazon.Util.AWSSDKUtils.ConvertToUnixEpochMilliSeconds(date).ToString()); context.ExpectingValue = false; } public void WriteArrayEnd () { DoValidation (Condition.InArray); PutNewline (false); ctx_stack.Pop (); if (ctx_stack.Count == 1) has_reached_end = true; else { context = ctx_stack.Peek (); context.ExpectingValue = false; } Unindent (); Put ("]"); } public void WriteArrayStart () { DoValidation (Condition.NotAProperty); PutNewline (); Put ("["); context = new WriterContext (); context.InArray = true; ctx_stack.Push (context); Indent (); } public void WriteObjectEnd () { DoValidation (Condition.InObject); PutNewline (false); ctx_stack.Pop (); if (ctx_stack.Count == 1) has_reached_end = true; else { context = ctx_stack.Peek (); context.ExpectingValue = false; } Unindent (); Put ("}"); } public void WriteObjectStart () { DoValidation (Condition.NotAProperty); PutNewline (); Put ("{"); context = new WriterContext (); context.InObject = true; ctx_stack.Push (context); Indent (); } public void WritePropertyName (string property_name) { DoValidation (Condition.Property); PutNewline (); PutString (property_name); if (pretty_print) { if (property_name.Length > context.Padding) context.Padding = property_name.Length; for (int i = context.Padding - property_name.Length; i >= 0; i--) writer.Write (' '); writer.Write (": "); } else writer.Write (':'); context.ExpectingValue = true; } } }
using System.Configuration; using Rhino.Etl.Core.Infrastructure; namespace Rhino.Etl.Core.Operations { using System; using System.Collections.Generic; using System.Data.SqlClient; using DataReaders; /// <summary> /// Allows to execute an operation that perform a bulk insert into a sql server database /// </summary> public abstract class SqlBulkInsertOperation : AbstractDatabaseOperation { /// <summary> /// The schema of the destination table /// </summary> private IDictionary<string, Type> _schema = new Dictionary<string, Type>(); /// <summary> /// The mapping of columns from the row to the database schema. /// Important: The column name in the database is case sensitive! /// </summary> public IDictionary<string, string> Mappings = new Dictionary<string, string>(); private readonly IDictionary<string, Type> _inputSchema = new Dictionary<string, Type>(); private SqlBulkCopy sqlBulkCopy; private string targetTable; private int timeout; private int batchSize; private int notifyBatchSize; private SqlBulkCopyOptions bulkCopyOptions = SqlBulkCopyOptions.Default; /// <summary> /// Initializes a new instance of the <see cref="SqlBulkInsertOperation"/> class. /// </summary> /// <param name="connectionStringName">Name of the connection string.</param> /// <param name="targetTable">The target table.</param> protected SqlBulkInsertOperation(string connectionStringName, string targetTable) : this(ConfigurationManager.ConnectionStrings[connectionStringName], targetTable) { } /// <summary> /// Initializes a new instance of the <see cref="SqlBulkInsertOperation"/> class. /// </summary> /// <param name="connectionStringSettings">Connection string settings to use.</param> /// <param name="targetTable">The target table.</param> protected SqlBulkInsertOperation(ConnectionStringSettings connectionStringSettings, string targetTable) : this(connectionStringSettings, targetTable, 600) { } /// <summary> /// Initializes a new instance of the <see cref="SqlBulkInsertOperation"/> class. /// </summary> /// <param name="connectionStringName">Name of the connection string.</param> /// <param name="targetTable">The target table.</param> /// <param name="timeout">The timeout.</param> protected SqlBulkInsertOperation(string connectionStringName, string targetTable, int timeout) : this(ConfigurationManager.ConnectionStrings[connectionStringName], targetTable, timeout) { Guard.Against(string.IsNullOrEmpty(targetTable), "TargetTable was not set, but it is mandatory"); this.targetTable = targetTable; this.timeout = timeout; } /// <summary> /// Initializes a new instance of the <see cref="SqlBulkInsertOperation"/> class. /// </summary> /// <param name="connectionStringSettings">Connection string settings to use.</param> /// <param name="targetTable">The target table.</param> /// <param name="timeout">The timeout.</param> protected SqlBulkInsertOperation(ConnectionStringSettings connectionStringSettings, string targetTable, int timeout) : base(connectionStringSettings) { Guard.Against(string.IsNullOrEmpty(targetTable), "TargetTable was not set, but it is mandatory"); this.targetTable = targetTable; this.timeout = timeout; } /// <summary>The timeout value of the bulk insert operation</summary> public virtual int Timeout { get { return timeout; } set { timeout = value; } } /// <summary>The batch size value of the bulk insert operation</summary> public virtual int BatchSize { get { return batchSize; } set { batchSize = value; } } /// <summary>The batch size value of the bulk insert operation</summary> public virtual int NotifyBatchSize { get { return notifyBatchSize>0 ? notifyBatchSize : batchSize; } set { notifyBatchSize = value; } } /// <summary>The table or view to bulk load the data into.</summary> public string TargetTable { get { return targetTable; } set { targetTable = value; } } /// <summary><c>true</c> to turn the <see cref="SqlBulkCopyOptions.TableLock"/> option on, otherwise <c>false</c>.</summary> public virtual bool LockTable { get { return IsOptionOn(SqlBulkCopyOptions.TableLock); } set { ToggleOption(SqlBulkCopyOptions.TableLock, value); } } /// <summary><c>true</c> to turn the <see cref="SqlBulkCopyOptions.KeepIdentity"/> option on, otherwise <c>false</c>.</summary> public virtual bool KeepIdentity { get { return IsOptionOn(SqlBulkCopyOptions.KeepIdentity); } set { ToggleOption(SqlBulkCopyOptions.KeepIdentity, value); } } /// <summary><c>true</c> to turn the <see cref="SqlBulkCopyOptions.KeepNulls"/> option on, otherwise <c>false</c>.</summary> public virtual bool KeepNulls { get { return IsOptionOn(SqlBulkCopyOptions.KeepNulls); } set { ToggleOption(SqlBulkCopyOptions.KeepNulls, value); } } /// <summary><c>true</c> to turn the <see cref="SqlBulkCopyOptions.CheckConstraints"/> option on, otherwise <c>false</c>.</summary> public virtual bool CheckConstraints { get { return IsOptionOn(SqlBulkCopyOptions.CheckConstraints); } set { ToggleOption(SqlBulkCopyOptions.CheckConstraints, value); } } /// <summary><c>true</c> to turn the <see cref="SqlBulkCopyOptions.FireTriggers"/> option on, otherwise <c>false</c>.</summary> public virtual bool FireTriggers { get { return IsOptionOn(SqlBulkCopyOptions.FireTriggers); } set { ToggleOption(SqlBulkCopyOptions.FireTriggers, value); } } /// <summary>Turns a <see cref="bulkCopyOptions"/> on or off depending on the value of <paramref name="on"/></summary> /// <param name="option">The <see cref="SqlBulkCopyOptions"/> to turn on or off.</param> /// <param name="on"><c>true</c> to set the <see cref="SqlBulkCopyOptions"/> <paramref name="option"/> on otherwise <c>false</c> to turn the <paramref name="option"/> off.</param> protected void ToggleOption(SqlBulkCopyOptions option, bool on) { if (on) { TurnOptionOn(option); } else { TurnOptionOff(option); } } /// <summary>Returns <c>true</c> if the <paramref name="option"/> is turned on, otherwise <c>false</c></summary> /// <param name="option">The <see cref="SqlBulkCopyOptions"/> option to test for.</param> /// <returns></returns> protected bool IsOptionOn(SqlBulkCopyOptions option) { return (bulkCopyOptions & option) == option; } /// <summary>Turns the <paramref name="option"/> on.</summary> /// <param name="option"></param> protected void TurnOptionOn(SqlBulkCopyOptions option) { bulkCopyOptions |= option; } /// <summary>Turns the <paramref name="option"/> off.</summary> /// <param name="option"></param> protected void TurnOptionOff(SqlBulkCopyOptions option) { if (IsOptionOn(option)) bulkCopyOptions ^= option; } /// <summary>The table or view's schema information.</summary> public IDictionary<string, Type> Schema { get { return _schema; } set { _schema = value; } } /// <summary> /// Prepares the mapping for use, by default, it uses the schema mapping. /// This is the preferred appraoch /// </summary> public virtual void PrepareMapping() { foreach (KeyValuePair<string, Type> pair in _schema) { Mappings[pair.Key] = pair.Key; } } /// <summary>Use the destination Schema and Mappings to create the /// operations input schema so it can build the adapter for sending /// to the WriteToServer method.</summary> public virtual void CreateInputSchema() { foreach(KeyValuePair<string, string> pair in Mappings) { _inputSchema.Add(pair.Key, _schema[pair.Value]); } } /// <summary> /// Executes this operation /// </summary> public override IEnumerable<Row> Execute(IEnumerable<Row> rows) { Guard.Against<ArgumentException>(rows == null, "SqlBulkInsertOperation cannot accept a null enumerator"); PrepareSchema(); PrepareMapping(); CreateInputSchema(); using (SqlConnection connection = (SqlConnection)Use.Connection(ConnectionStringSettings)) using (SqlTransaction transaction = (SqlTransaction) BeginTransaction(connection)) { sqlBulkCopy = CreateSqlBulkCopy(connection, transaction); DictionaryEnumeratorDataReader adapter = new DictionaryEnumeratorDataReader(_inputSchema, rows); sqlBulkCopy.WriteToServer(adapter); if (PipelineExecuter.HasErrors) { Warn("Rolling back transaction in {0}", Name); if (transaction != null) transaction.Rollback(); Warn("Rolled back transaction in {0}", Name); } else { Debug("Committing {0}", Name); if (transaction != null) transaction.Commit(); Debug("Committed {0}", Name); } } yield break; } /// <summary> /// Handle sql notifications /// </summary> protected virtual void onSqlRowsCopied(object sender, SqlRowsCopiedEventArgs e) { Debug("{0} rows copied to database", e.RowsCopied); } /// <summary> /// Prepares the schema of the target table /// </summary> protected abstract void PrepareSchema(); /// <summary> /// Creates the SQL bulk copy instance /// </summary> private SqlBulkCopy CreateSqlBulkCopy(SqlConnection connection, SqlTransaction transaction) { SqlBulkCopy copy = new SqlBulkCopy(connection, bulkCopyOptions, transaction); copy.BatchSize = batchSize; foreach (KeyValuePair<string, string> pair in Mappings) { copy.ColumnMappings.Add(pair.Key, pair.Value); } copy.NotifyAfter = NotifyBatchSize; copy.SqlRowsCopied += onSqlRowsCopied; copy.DestinationTableName = TargetTable; copy.BulkCopyTimeout = Timeout; return copy; } } }
// // Copyright (C) 2012-2014 DataStax 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.Linq; using Cassandra.Serialization; namespace Cassandra { /// <summary> /// Represents a prepared statement, a query with bound variables that has been /// prepared (pre-parsed) by the database. <p> A prepared statement can be /// executed once concrete values has been provided for the bound variables. The /// pair of a prepared statement and values for its bound variables is a /// BoundStatement and can be executed (by <link>Session#Execute</link>).</p> /// </summary> public class PreparedStatement { internal readonly RowSetMetadata Metadata; private readonly Serializer _serializer; private volatile RoutingKey _routingKey; private string[] _routingNames; private volatile int[] _routingIndexes; /// <summary> /// The cql query /// </summary> internal string Cql { get; private set; } /// <summary> /// The prepared statement identifier /// </summary> internal byte[] Id { get; private set; } /// <summary> /// The keyspace were the prepared statement was first executed /// </summary> internal string Keyspace { get; private set; } /// <summary> /// Gets the the incoming payload, that is, the payload that the server /// sent back with its prepared response, or null if the server did not include any custom payload. /// </summary> public IDictionary<string, byte[]> IncomingPayload { get; internal set; } /// <summary> /// Gets custom payload for that will be included when executing an Statement. /// </summary> public IDictionary<string, byte[]> OutgoingPayload { get; private set; } /// <summary> /// Gets metadata on the bounded variables of this prepared statement. /// </summary> public RowSetMetadata Variables { get { return Metadata; } } /// <summary> /// Gets the routing key for the prepared statement. /// </summary> public RoutingKey RoutingKey { get { return _routingKey; } } /// <summary> /// Gets or sets the parameter indexes that are part of the partition key /// </summary> public int[] RoutingIndexes { get { return _routingIndexes; } internal set { _routingIndexes = value; } } /// <summary> /// Gets the default consistency level for all executions using this instance /// </summary> public ConsistencyLevel? ConsistencyLevel { get; private set; } /// <summary> /// Determines if the query is idempotent, i.e. whether it can be applied multiple times without /// changing the result beyond the initial application. /// <para> /// Idempotence of the prepared statement plays a role in <see cref="ISpeculativeExecutionPolicy"/>. /// If a query is <em>not idempotent</em>, the driver will not schedule speculative executions for it. /// </para> /// When the property is null, the driver will use the default value from the <see cref="QueryOptions.GetDefaultIdempotence()"/>. /// </summary> public bool? IsIdempotent { get; private set; } /// <summary> /// Initializes a new instance of the Cassandra.PreparedStatement class /// </summary> public PreparedStatement() { //Default constructor for client test and mocking frameworks } internal PreparedStatement(RowSetMetadata metadata, byte[] id, string cql, string keyspace, Serializer serializer) { Metadata = metadata; Id = id; Cql = cql; Keyspace = keyspace; _serializer = serializer; } /// <summary> /// Creates a new BoundStatement object and bind its variables to the provided /// values. /// <para> /// Specify the parameter values by the position of the markers in the query or by name, /// using a single instance of an anonymous type, with property names as parameter names. /// </para> /// <para> /// Note that while no more <c>values</c> than bound variables can be provided, it is allowed to /// provide less <c>values</c> that there is variables. /// </para> /// </summary> /// <param name="values"> the values to bind to the variables of the newly /// created BoundStatement. </param> /// <returns>the newly created <c>BoundStatement</c> with its variables /// bound to <c>values</c>. </returns> public virtual BoundStatement Bind(params object[] values) { var bs = new BoundStatement(this, _serializer); bs.SetRoutingKey(_routingKey); if (values == null) { return bs; } var valuesByPosition = values; var useNamedParameters = values.Length == 1 && Utils.IsAnonymousType(values[0]); if (useNamedParameters) { //Using named parameters //Reorder the params according the position in the query valuesByPosition = Utils.GetValues(Metadata.Columns.Select(c => c.Name), values[0]).ToArray(); } bs.SetValues(valuesByPosition); bs.CalculateRoutingKey(useNamedParameters, RoutingIndexes, _routingNames, valuesByPosition, values); return bs; } /// <summary> /// Sets a default consistency level for all <c>BoundStatement</c> created /// from this object. <p> If no consistency level is set through this method, the /// BoundStatement created from this object will use the default consistency /// level (One). </p><p> Changing the default consistency level is not retroactive, /// it only applies to BoundStatement created after the change.</p> /// </summary> /// <param name="consistency"> the default consistency level to set. </param> /// <returns>this <c>PreparedStatement</c> object.</returns> public PreparedStatement SetConsistencyLevel(ConsistencyLevel consistency) { ConsistencyLevel = consistency; return this; } /// <summary> /// Sets the partition keys of the query /// </summary> /// <returns>True if it was possible to set the routing indexes for this query</returns> internal bool SetPartitionKeys(TableColumn[] keys) { var queryParameters = Metadata.Columns; var routingIndexes = new List<int>(); foreach (var key in keys) { //find the position of the key in the parameters for (var i = 0; i < queryParameters.Length; i++) { if (queryParameters[i].Name != key.Name) { continue; } routingIndexes.Add(i); break; } } if (routingIndexes.Count != keys.Length) { //The parameter names don't match the partition keys return false; } _routingIndexes = routingIndexes.ToArray(); return true; } /// <summary> /// Set the routing key for this query. /// <para> /// The routing key is a hint for token aware load balancing policies but is never mandatory. /// This method allows you to manually provide a routing key for this query. /// </para> /// <para> /// Use this method ONLY if the partition keys are the same for all query executions (hard-coded parameters). /// </para> /// <para> /// If the partition key is composite, you should provide multiple routing key components. /// </para> /// </summary> /// <param name="routingKeyComponents"> the raw (binary) values to compose to /// obtain the routing key. </param> /// <returns>this <c>PreparedStatement</c> object.</returns> public PreparedStatement SetRoutingKey(params RoutingKey[] routingKeyComponents) { _routingKey = RoutingKey.Compose(routingKeyComponents); return this; } /// <summary> /// For named query markers, it sets the parameter names that are part of the routing key. /// <para> /// Use this method ONLY if the parameter names are different from the partition key names. /// </para> /// </summary> /// <returns>this <c>PreparedStatement</c> object.</returns> public PreparedStatement SetRoutingNames(params string[] names) { if (names == null) { return this; } _routingNames = names; return this; } /// <summary> /// Sets whether the prepared statement is idempotent. /// <para> /// Idempotence of the query plays a role in <see cref="ISpeculativeExecutionPolicy"/>. /// If a query is <em>not idempotent</em>, the driver will not schedule speculative executions for it. /// </para> /// </summary> public PreparedStatement SetIdempotence(bool value) { IsIdempotent = value; return this; } /// <summary> /// Sets a custom outgoing payload for this statement. /// Each time an statement generated using this prepared statement is executed, this payload will be included in the request. /// Once it is set using this method, the payload should not be modified. /// </summary> public PreparedStatement SetOutgoingPayload(IDictionary<string, byte[]> payload) { OutgoingPayload = payload; return this; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace GuidanceService.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// DragNotebook.cs // // Author: // Todd Berman <tberman@off.net> // // Copyright (c) 2004 Todd Berman // // 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 Gdk; using Gtk; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Pinta.Docking; using Pinta.Docking.Gui; namespace Pinta.Docking.DockNotebook { public delegate void TabsReorderedHandler (Widget widget, int oldPlacement, int newPlacement); public class DockNotebook : Gtk.VBox { List<DockNotebookTab> pages = new List<DockNotebookTab> (); List<DockNotebookTab> pagesHistory = new List<DockNotebookTab> (); TabStrip tabStrip; Gtk.EventBox contentBox; ReadOnlyCollection<DockNotebookTab> pagesCol; const int MAX_LASTACTIVEWINDOWS = 10; DockNotebookTab currentTab; static DockNotebook activeNotebook; static List<DockNotebook> allNotebooks = new List<DockNotebook> (); enum TargetList { UriList = 100 } static Gtk.TargetEntry[] targetEntryTypes = new Gtk.TargetEntry[] { new Gtk.TargetEntry ("text/uri-list", 0, (uint)TargetList.UriList) }; public DockNotebook () { pagesCol = new ReadOnlyCollection<DockNotebookTab> (pages); AddEvents ((Int32)(EventMask.AllEventsMask)); tabStrip = new TabStrip (this); PackStart (tabStrip, false, false, 0); contentBox = new EventBox (); PackStart (contentBox, true, true, 0); ShowAll (); tabStrip.Visible = DockNotebookManager.TabStripVisible; DockNotebookManager.TabStripVisibleChanged += (o, e) => tabStrip.Visible = DockNotebookManager.TabStripVisible; contentBox.NoShowAll = true; tabStrip.DropDownButton.Sensitive = false; tabStrip.DropDownButton.MenuCreator = delegate { Gtk.Menu menu = new Menu (); foreach (var tab in pages) { var mi = new Gtk.ImageMenuItem (""); menu.Insert (mi, -1); var label = (Gtk.AccelLabel) mi.Child; if (tab.Markup != null) label.Markup = tab.Markup; else label.Text = tab.Text; var locTab = tab; mi.Activated += delegate { CurrentTab = locTab; }; } menu.ShowAll (); return menu; }; Gtk.Drag.DestSet (this, Gtk.DestDefaults.Motion | Gtk.DestDefaults.Highlight | Gtk.DestDefaults.Drop, targetEntryTypes, Gdk.DragAction.Copy); DragDataReceived += new Gtk.DragDataReceivedHandler (OnDragDataReceived); DragMotion += delegate { // Bring this window to the front. Otherwise, the drop may end being done in another window that overlaps this one if (!Platform.IsWindows) { var window = ((Gtk.Window)Toplevel); if (window is DockWindow) window.Present (); } }; allNotebooks.Add (this); } internal static DockNotebook ActiveNotebook { get { return activeNotebook; } set { if (activeNotebook != value) { if (activeNotebook != null) activeNotebook.tabStrip.IsActiveNotebook = false; activeNotebook = value; if (activeNotebook != null) activeNotebook.tabStrip.IsActiveNotebook = true; DockNotebookManager.OnActiveNotebookChanged (); } } } internal static IEnumerable<DockNotebook> AllNotebooks { get { return allNotebooks; } } Cursor fleurCursor = new Cursor (CursorType.Fleur); public event EventHandler<TabEventArgs> TabActivated; public event EventHandler PageAdded; public event EventHandler PageRemoved; public event EventHandler SwitchPage; public event EventHandler PreviousButtonClicked { add { tabStrip.PreviousButton.Clicked += value; } remove { tabStrip.PreviousButton.Clicked -= value; } } public event EventHandler NextButtonClicked { add { tabStrip.NextButton.Clicked += value; } remove { tabStrip.NextButton.Clicked -= value; } } public bool PreviousButtonEnabled { get { return tabStrip.PreviousButton.Sensitive; } set { tabStrip.PreviousButton.Sensitive = value; } } public bool NextButtonEnabled { get { return tabStrip.NextButton.Sensitive; } set { tabStrip.NextButton.Sensitive = value; } } public bool NavigationButtonsVisible { get { return tabStrip.NavigationButtonsVisible; } set { tabStrip.NavigationButtonsVisible = value; } } public ReadOnlyCollection<DockNotebookTab> Tabs { get { return pagesCol; } } public DockNotebookTab CurrentTab { get { return currentTab; } set { if (currentTab != value) { currentTab = value; if (contentBox.Child != null) contentBox.Remove (contentBox.Child); if (currentTab != null) { if (currentTab.Content != null) { contentBox.Add (currentTab.Content); contentBox.ChildFocus (DirectionType.Down); } pagesHistory.Remove (currentTab); pagesHistory.Insert (0, currentTab); if (pagesHistory.Count > MAX_LASTACTIVEWINDOWS) pagesHistory.RemoveAt (pagesHistory.Count - 1); } tabStrip.Update (); if (SwitchPage != null) SwitchPage (this, EventArgs.Empty); DockNotebookManager.OnActiveTabChanged (); } } } public int CurrentTabIndex { get { return currentTab != null ? currentTab.Index : -1; } set { if (value > pages.Count - 1) CurrentTab = null; else CurrentTab = pages [value]; } } void SelectLastActiveTab (int lastClosed) { if (pages.Count == 0) { CurrentTab = null; return; } while (pagesHistory.Count > 0 && pagesHistory [0].Content == null) pagesHistory.RemoveAt (0); if (pagesHistory.Count > 0) CurrentTab = pagesHistory [0]; else { if (lastClosed + 1 < pages.Count) CurrentTab = pages [lastClosed + 1]; else CurrentTab = pages [lastClosed - 1]; } } public int TabCount { get { return pages.Count; } } public int BarHeight { get { return tabStrip.BarHeight; } } public void InitSize () { tabStrip.InitSize (); } void OnDragDataReceived (object o, Gtk.DragDataReceivedArgs args) { DockNotebookManager.OnDragDataReceived (o, args); } public DockNotebookContainer Container { get { var container = (DockNotebookContainer)Parent; return container.MotherContainer () ?? container; } } /// <summary> /// Returns the next notebook in the same window /// </summary> public DockNotebook GetNextNotebook () { return Container.GetNextNotebook (this); } /// <summary> /// Returns the previous notebook in the same window /// </summary> public DockNotebook GetPreviousNotebook () { return Container.GetPreviousNotebook (this); } public Action<DockNotebook, int,Gdk.EventButton> DoPopupMenu { get; set; } public DockNotebookTab AddTab (Gtk.Widget content = null) { var t = InsertTab (-1); if (content != null) t.Content = content; return t; } public DockNotebookTab InsertTab (IViewContent content, int index) { // Create the new tab var tab = InsertTab (index); // Create a content window and add it to the tab var window = new SdiWorkspaceWindow (content, this, tab); tab.Content = window; tab.Content.Show (); return tab; } public DockNotebookTab InsertTab (int index) { var tab = new DockNotebookTab (this, tabStrip); if (index == -1) { pages.Add (tab); tab.Index = pages.Count - 1; } else { pages.Insert (index, tab); tab.Index = index; UpdateIndexes (index + 1); } pagesHistory.Add (tab); if (pages.Count == 1) CurrentTab = tab; tabStrip.StartOpenAnimation ((DockNotebookTab)tab); tabStrip.Update (); tabStrip.DropDownButton.Sensitive = pages.Count > 0; if (PageAdded != null) PageAdded (this, EventArgs.Empty); return tab; } void UpdateIndexes (int startIndex) { for (int n=startIndex; n < pages.Count; n++) ((DockNotebookTab)pages [n]).Index = n; } public DockNotebookTab GetTab (int n) { if (n < 0 || n >= pages.Count) return null; else return pages [n]; } public void RemoveTab (int page, bool animate) { var tab = pages [page]; if (animate) tabStrip.StartCloseAnimation ((DockNotebookTab)tab); pagesHistory.Remove (tab); if (pages.Count == 1) CurrentTab = null; else if (page == CurrentTabIndex) SelectLastActiveTab (page); pages.RemoveAt (page); UpdateIndexes (page); tabStrip.Update (); tabStrip.DropDownButton.Sensitive = pages.Count > 0; if (PageRemoved != null) PageRemoved (this, EventArgs.Empty); } internal void ReorderTab (DockNotebookTab tab, DockNotebookTab targetTab) { if (tab == targetTab) return; int targetPos = targetTab.Index; if (tab.Index > targetTab.Index) { pages.RemoveAt (tab.Index); pages.Insert (targetPos, tab); } else { pages.Insert (targetPos + 1, tab); pages.RemoveAt (tab.Index); } // JONTODO //IdeApp.Workbench.ReorderDocuments (tab.Index, targetPos); UpdateIndexes (Math.Min (tab.Index, targetPos)); tabStrip.Update (); } // Returns true if the tab was successfully closed internal bool OnCloseTab (DockNotebookTab tab) { var e = new TabClosedEventArgs () { Tab = tab }; DockNotebookManager.OnTabClosed (this, e); return !e.Cancel; } internal void OnActivateTab (DockNotebookTab tab) { if (TabActivated != null) TabActivated (this, new TabEventArgs () { Tab = tab }); } internal void ShowContent (DockNotebookTab tab) { if (tab == currentTab) contentBox.Child = tab.Content; } protected override bool OnButtonPressEvent (EventButton evnt) { ActiveNotebook = this; return base.OnButtonPressEvent (evnt); } protected override void OnDestroyed () { allNotebooks.Remove (this); if (ActiveNotebook == this) ActiveNotebook = null; if (fleurCursor != null) { fleurCursor.Dispose (); fleurCursor = null; } base.OnDestroyed (); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Microsoft.PythonTools.Analysis; using Microsoft.PythonTools.Django.Project; using Microsoft.PythonTools.Django.TemplateParsing; using Microsoft.PythonTools.Intellisense; using Microsoft.PythonTools.Interpreter; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; namespace Microsoft.PythonTools.Django.Intellisense { internal abstract class DjangoCompletionSourceBase : ICompletionSource { protected readonly IGlyphService _glyphService; protected readonly DjangoAnalyzer _analyzer; protected readonly ITextBuffer _buffer; internal static readonly Dictionary<string, string> _nestedTags = new Dictionary<string, string>() { { "for", "endfor" }, { "if", "endif" }, { "ifequal", "endifequal" }, { "ifnotequal", "endifnotequal" }, { "ifchanged", "endifchanged" }, { "autoescape", "endautoescape" }, { "comment", "endcomment" }, { "filter", "endfilter" }, { "spaceless", "endspaceless" }, { "with", "endwith" }, { "empty", "endfor" }, { "else", "endif" }, }; internal static readonly HashSet<string> _nestedEndTags = MakeNestedEndTags(); private static readonly HashSet<string> _nestedStartTags = MakeNestedStartTags(); protected DjangoCompletionSourceBase(IGlyphService glyphService, DjangoAnalyzer analyzer, ITextBuffer textBuffer) { _glyphService = glyphService; _analyzer = analyzer; _buffer = textBuffer; } #region ICompletionSource Members public abstract void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets); /// <param name="kind">The type of template tag we are processing</param> /// <param name="templateText">The text of the template tag which we are offering a completion in</param> /// <param name="templateStart">The offset in the buffer where the template starts</param> /// <param name="triggerPoint">The point in the buffer where the completion was triggered</param> internal CompletionSet GetCompletionSet(CompletionOptions options, DjangoAnalyzer analyzer, TemplateTokenKind kind, string templateText, int templateStart, SnapshotPoint triggerPoint, out ITrackingSpan applicableSpan) { int position = triggerPoint.Position - templateStart; IEnumerable<CompletionInfo> tags; IDjangoCompletionContext context; applicableSpan = GetWordSpan(templateText, templateStart, triggerPoint); switch (kind) { case TemplateTokenKind.Block: var block = DjangoBlock.Parse(templateText); if (block != null) { if (position <= block.ParseInfo.Start + block.ParseInfo.Command.Length) { // we are completing before the command // TODO: Return a new set of tags? Do nothing? Do this based upon ctrl-space? tags = FilterBlocks(CompletionInfo.ToCompletionInfo(analyzer._tags, StandardGlyphGroup.GlyphKeyword), triggerPoint); } else { // we are in the arguments, let the block handle the completions context = new ProjectBlockCompletionContext(analyzer, _buffer); tags = block.GetCompletions(context, position); } } else { // no tag entered yet, provide the known list of tags. tags = FilterBlocks(CompletionInfo.ToCompletionInfo(analyzer._tags, StandardGlyphGroup.GlyphKeyword), triggerPoint); } break; case TemplateTokenKind.Variable: var variable = DjangoVariable.Parse(templateText); context = new ProjectBlockCompletionContext(analyzer, _buffer); if (variable != null) { tags = variable.GetCompletions(context, position); } else { // show variable names tags = CompletionInfo.ToCompletionInfo(context.Variables, StandardGlyphGroup.GlyphGroupVariable); } break; default: throw new InvalidOperationException(); } var completions = tags .OrderBy(tag => tag.DisplayText, StringComparer.OrdinalIgnoreCase) .Select(tag => new DynamicallyVisibleCompletion( tag.DisplayText, tag.InsertionText, StripDocumentation(tag.Documentation), _glyphService.GetGlyph(tag.Glyph, StandardGlyphItem.GlyphItemPublic), "tag")); return new FuzzyCompletionSet( "PythonDjangoTags", "Django Tags", applicableSpan, completions, options, CompletionComparer.UnderscoresLast); } private ITrackingSpan GetWordSpan(string templateText, int templateStart, SnapshotPoint triggerPoint) { ITrackingSpan applicableSpan; int spanStart = triggerPoint.Position; for (int i = triggerPoint.Position - templateStart - 1; i >= 0 && i < templateText.Length; --i, --spanStart) { char c = templateText[i]; if (!char.IsLetterOrDigit(c) && c != '_') { break; } } int length = triggerPoint.Position - spanStart; for (int i = triggerPoint.Position; i < triggerPoint.Snapshot.Length; i++) { char c = triggerPoint.Snapshot[i]; if (!char.IsLetterOrDigit(c) && c != '_') { break; } length++; } applicableSpan = triggerPoint.Snapshot.CreateTrackingSpan( spanStart, length, SpanTrackingMode.EdgeInclusive ); return applicableSpan; } internal static string StripDocumentation(string doc) { if (doc == null) { return String.Empty; } StringBuilder result = new StringBuilder(doc.Length); foreach (string line in doc.Split('\n')) { if (result.Length > 0) { result.Append("\r\n"); } result.Append(line.Trim()); } return result.ToString(); } protected abstract IEnumerable<DjangoBlock> GetBlocks(IEnumerable<CompletionInfo> results, SnapshotPoint triggerPoint); private IEnumerable<CompletionInfo> FilterBlocks(IEnumerable<CompletionInfo> results, SnapshotPoint triggerPoint) { int depth = 0; HashSet<string> included = new HashSet<string>(); foreach (var block in GetBlocks(results, triggerPoint)) { var cmd = block.ParseInfo.Command; if (cmd == "elif") { if (depth == 0) { included.Add("endif"); } // otherwise elif both starts and ends a block, // so depth remains the same. } else if (_nestedEndTags.Contains(cmd)) { depth++; } else if (_nestedStartTags.Contains(cmd)) { if (depth == 0) { included.Add(_nestedTags[cmd]); if (cmd == "if") { included.Add("elif"); } } // we happily let depth go negative, it'll prevent us from // including an end tag for outer blocks when we're in an // inner block. depth--; } } foreach (var value in results) { if (!(_nestedEndTags.Contains(value.DisplayText) || value.DisplayText == "elif") || included.Contains(value.DisplayText)) { yield return value; } } } #endregion private static HashSet<string> MakeNestedEndTags() { HashSet<string> res = new HashSet<string>(); foreach (var value in _nestedTags.Values) { res.Add(value); } return res; } private static HashSet<string> MakeNestedStartTags() { HashSet<string> res = new HashSet<string>(); foreach (var key in _nestedTags.Keys) { res.Add(key); } return res; } #region IDisposable Members public void Dispose() { } #endregion } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation 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 (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ using System; using System.ComponentModel.Design; using System.Runtime.InteropServices; // Platform references using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Shell; // IronPython namespaces. using IronPython.Hosting; // Unit test framework. using Microsoft.VsSDK.UnitTestLibrary; using Microsoft.VisualStudio.TestTools.UnitTesting; // Namespace of the class to test using Microsoft.Samples.VisualStudio.IronPythonInterfaces; using Microsoft.Samples.VisualStudio.IronPythonConsole; namespace Microsoft.Samples.VisualStudio.IronPythonConsole.UnitTest { [TestClass] public class ConsoleCommandHandlers { // Callback function used to define the OleMenuCommand objects needed to // verify the command handler function. private static void EmptyMenuCallback(object sender, EventArgs e) { } [TestMethod] public void SupportCommandOnInputPositionVerifySender() { using (OleServiceProvider provider = new OleServiceProvider()) { // Create a mock text buffer for the console. BaseMock textLinesMock = MockFactories.TextBufferFactory.GetInstance(); // Add the text buffer to the local registry LocalRegistryMock mockLocalRegistry = new LocalRegistryMock(); mockLocalRegistry.AddClass(typeof(VsTextBufferClass), textLinesMock); // Add the local registry to the list of services. provider.AddService(typeof(SLocalRegistry), mockLocalRegistry, false); // Create the console. using (ToolWindowPane windowPane = CommandWindowHelper.CreateConsoleWindow(provider) as ToolWindowPane) { // Verify OnBeforeHistory can handle a null sender CommandWindowHelper.ExecuteSupportCommandOnInputPosition(windowPane, null); // Verify OnBeforeHistory can handle a sender of unexpected type. CommandWindowHelper.ExecuteSupportCommandOnInputPosition(windowPane, ""); } } } /// <summary> /// Verify that the commands that are supposed to be supported only when the cursor is in /// a input position are actually supported / unsupported. /// </summary> [TestMethod] public void InputPositionCommand() { using (OleServiceProvider provider = new OleServiceProvider()) { // Create a mock text buffer for the console. BaseMock textLinesMock = MockFactories.CreateBufferWithMarker(); BaseMock lineMarkerMock = (BaseMock)textLinesMock["LineMarker"]; // Add the text buffer to the local registry LocalRegistryMock mockLocalRegistry = new LocalRegistryMock(); mockLocalRegistry.AddClass(typeof(VsTextBufferClass), textLinesMock); // Define the mock object for the text view and add it to the local registry. BaseMock textViewMock = MockFactories.TextViewFactory.GetInstance(); mockLocalRegistry.AddClass(typeof(VsTextViewClass), textViewMock); // Add the local registry to the list of services. provider.AddService(typeof(SLocalRegistry), mockLocalRegistry, false); // Create the console. using (ToolWindowPane windowPane = CommandWindowHelper.CreateConsoleWindow(provider) as ToolWindowPane) { // Call the CreatePaneWindow method that will force the creation of the text view. IntPtr newHwnd; Assert.IsTrue(Microsoft.VisualStudio.ErrorHandler.Succeeded( ((IVsWindowPane)windowPane).CreatePaneWindow(IntPtr.Zero, 0, 0, 0, 0, out newHwnd))); // Now we have to set the frame property on the ToolWindowFrame because // this will cause the execution of OnToolWindowCreated and this will add the // command handling for the return key. windowPane.Frame = (IVsWindowFrame)MockFactories.WindowFrameFactory.GetInstance(); // Make sure that the text marker is created. CommandWindowHelper.EnsureConsoleTextMarker(windowPane); // Reset the span of the marker. TextSpan markerSpan = new TextSpan(); markerSpan.iStartLine = 0; markerSpan.iStartIndex = 0; markerSpan.iEndLine = 4; markerSpan.iEndIndex = 3; lineMarkerMock["Span"] = markerSpan; // Create the helper class to handle the command target implemented // by the console. CommandTargetHelper helper = new CommandTargetHelper((IOleCommandTarget)windowPane); // Simulate the fact that the cursor is after the end of the marker. textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 4, 7 }); // Verify that the commands are supported. uint flags; Assert.IsTrue( helper.IsCommandSupported( typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.UP, out flags)); Assert.IsTrue( helper.IsCommandSupported( typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.DOWN, out flags)); Assert.IsTrue( helper.IsCommandSupported( typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.BOL_EXT, out flags)); // Simulate the cursor on the last line, but before the end of the marker. textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 4, 2 }); Assert.IsFalse( helper.IsCommandSupported( typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.UP, out flags)); Assert.IsFalse( helper.IsCommandSupported( typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.DOWN, out flags)); Assert.IsFalse( helper.IsCommandSupported( typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.BOL_EXT, out flags)); // Simulate the cursor on a line before the end of the marker. textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 1, 7 }); Assert.IsFalse( helper.IsCommandSupported( typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.UP, out flags)); Assert.IsFalse( helper.IsCommandSupported( typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.DOWN, out flags)); Assert.IsFalse( helper.IsCommandSupported( typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.BOL_EXT, out flags)); // Simulate the cursor on a line after the last. textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 5, 7 }); Assert.IsTrue( helper.IsCommandSupported( typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.UP, out flags)); Assert.IsTrue( helper.IsCommandSupported( typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.DOWN, out flags)); Assert.IsTrue( helper.IsCommandSupported( typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.BOL_EXT, out flags)); } } } [TestMethod] public void VerifyHistoryEmpty() { using (OleServiceProvider provider = new OleServiceProvider()) { // Create a mock text buffer for the console. BaseMock textLinesMock = MockFactories.CreateBufferWithMarker(); // Add the text buffer to the local registry LocalRegistryMock mockLocalRegistry = new LocalRegistryMock(); mockLocalRegistry.AddClass(typeof(VsTextBufferClass), textLinesMock); // Define the mock object for the text view and add it to the local registry. BaseMock textViewMock = MockFactories.TextViewFactory.GetInstance(); mockLocalRegistry.AddClass(typeof(VsTextViewClass), textViewMock); // Add the local registry to the list of services. provider.AddService(typeof(SLocalRegistry), mockLocalRegistry, false); // Create the console. using (ToolWindowPane windowPane = CommandWindowHelper.CreateConsoleWindow(provider) as ToolWindowPane) { // Call the CreatePaneWindow method that will force the creation of the text view. IntPtr newHwnd; Assert.IsTrue(Microsoft.VisualStudio.ErrorHandler.Succeeded( ((IVsWindowPane)windowPane).CreatePaneWindow(IntPtr.Zero, 0, 0, 0, 0, out newHwnd))); // Now we have to set the frame property on the ToolWindowFrame because // this will cause the execution of OnToolWindowCreated and this will add the // commands handling functions. windowPane.Frame = (IVsWindowFrame)MockFactories.WindowFrameFactory.GetInstance(); // Make sure that the text marker is created. CommandWindowHelper.EnsureConsoleTextMarker(windowPane); // The history should be empty, so no function on the text buffer or text marker // should be called. Reset all the function calls on these objects to verify. BaseMock markerMock = (BaseMock)textLinesMock["LineMarker"]; markerMock.ResetAllFunctionCalls(); textLinesMock.ResetAllFunctionCalls(); // Create the command target helper. CommandTargetHelper helper = new CommandTargetHelper(windowPane as IOleCommandTarget); // Call the command handler for the UP arrow. helper.ExecCommand(typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (uint)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.UP); Assert.IsTrue(0 == markerMock.TotalCallsAllFunctions()); Assert.IsTrue(0 == textLinesMock.TotalCallsAllFunctions()); // Call the command handler for the DOWN arrow. helper.ExecCommand(typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (uint)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.DOWN); Assert.IsTrue(0 == markerMock.TotalCallsAllFunctions()); Assert.IsTrue(0 == textLinesMock.TotalCallsAllFunctions()); } } } private static void ReplaceLinesCallback(object sender, CallbackArgs args) { IntPtr stringPointer = (IntPtr)args.GetParameter(4); int stringLen = (int)args.GetParameter(5); Assert.IsTrue(IntPtr.Zero != stringPointer); Assert.IsTrue(stringLen > 0); string newText = Marshal.PtrToStringAuto(stringPointer, stringLen); BaseMock mock = (BaseMock)sender; mock["Text"] = (string)mock["Text"] + newText; args.ReturnValue = Microsoft.VisualStudio.VSConstants.S_OK; } [TestMethod] public void VerifyHistoryOneElement() { using (OleServiceProvider provider = new OleServiceProvider()) { // Create a mock text buffer for the console. BaseMock textLinesMock = MockFactories.CreateBufferWithMarker(); // Add the text buffer to the local registry LocalRegistryMock mockLocalRegistry = new LocalRegistryMock(); mockLocalRegistry.AddClass(typeof(VsTextBufferClass), textLinesMock); // Define the mock object for the text view and add it to the local registry. BaseMock textViewMock = MockFactories.TextViewFactory.GetInstance(); mockLocalRegistry.AddClass(typeof(VsTextViewClass), textViewMock); // Add the local registry to the list of services. provider.AddService(typeof(SLocalRegistry), mockLocalRegistry, false); // Create the console. using (ToolWindowPane windowPane = CommandWindowHelper.CreateConsoleWindow(provider) as ToolWindowPane) { // Call the CreatePaneWindow method that will force the creation of the text view. IntPtr newHwnd; Assert.IsTrue(Microsoft.VisualStudio.ErrorHandler.Succeeded( ((IVsWindowPane)windowPane).CreatePaneWindow(IntPtr.Zero, 0, 0, 0, 0, out newHwnd))); // Now we have to set the frame property on the ToolWindowFrame because // this will cause the execution of OnToolWindowCreated and this will add the // commands handling functions. windowPane.Frame = (IVsWindowFrame)MockFactories.WindowFrameFactory.GetInstance(); // Make sure that the text marker is created. CommandWindowHelper.EnsureConsoleTextMarker(windowPane); // Create the command target helper. CommandTargetHelper helper = new CommandTargetHelper(windowPane as IOleCommandTarget); // Add an element to the history executing a command. textLinesMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLineCount"), new object[] { 0, 3 }); textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 2, 4 }); textLinesMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLengthOfLine"), new object[] { 0, 3, 10 }); BaseMock markerMock = (BaseMock)textLinesMock["LineMarker"]; TextSpan span = new TextSpan(); span.iEndLine = 2; span.iEndIndex = 4; markerMock["Span"] = span; textLinesMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLineText"), new object[] { 0, 2, 4, 2, 10, "Line 1" }); // Execute the OnReturn handler. helper.ExecCommand(typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (uint)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.RETURN); // Now there should be one element in the history buffer. // Verify that DOWN key does nothing. markerMock.ResetAllFunctionCalls(); textLinesMock.ResetAllFunctionCalls(); helper.ExecCommand(typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (uint)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.DOWN); Assert.IsTrue(0 == markerMock.TotalCallsAllFunctions()); Assert.IsTrue(0 == textLinesMock.TotalCallsAllFunctions()); // The UP key should force the "Line 1" text in the last line of the text buffer. textLinesMock.AddMethodCallback( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "ReplaceLines"), new EventHandler<CallbackArgs>(ReplaceLinesCallback)); textLinesMock["Text"] = ""; helper.ExecCommand(typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (uint)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.UP); Assert.IsTrue(1 == textLinesMock.FunctionCalls(string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "ReplaceLines"))); Assert.IsTrue("Line 1" == (string)textLinesMock["Text"]); } } } private static void SetCaretPosCallback(object sender, CallbackArgs args) { BaseMock mock = (BaseMock)sender; mock["CaretLine"] = (int)args.GetParameter(0); mock["CaretColumn"] = (int)args.GetParameter(1); args.ReturnValue = Microsoft.VisualStudio.VSConstants.S_OK; } [TestMethod] public void VerifyOnHome() { using (OleServiceProvider provider = new OleServiceProvider()) { // Create a mock text buffer for the console. BaseMock textLinesMock = MockFactories.CreateBufferWithMarker(); // Add the text buffer to the local registry LocalRegistryMock mockLocalRegistry = new LocalRegistryMock(); mockLocalRegistry.AddClass(typeof(VsTextBufferClass), textLinesMock); // Define the mock object for the text view and add it to the local registry. BaseMock textViewMock = MockFactories.TextViewFactory.GetInstance(); textViewMock.AddMethodCallback( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "SetCaretPos"), new EventHandler<CallbackArgs>(SetCaretPosCallback)); mockLocalRegistry.AddClass(typeof(VsTextViewClass), textViewMock); // Add the local registry to the list of services. provider.AddService(typeof(SLocalRegistry), mockLocalRegistry, false); // Create the console. using (ToolWindowPane windowPane = CommandWindowHelper.CreateConsoleWindow(provider) as ToolWindowPane) { // Make sure that the text marker is created. CommandWindowHelper.EnsureConsoleTextMarker(windowPane); // Call the CreatePaneWindow method that will force the creation of the text view. IntPtr newHwnd; Assert.IsTrue(Microsoft.VisualStudio.ErrorHandler.Succeeded( ((IVsWindowPane)windowPane).CreatePaneWindow(IntPtr.Zero, 0, 0, 0, 0, out newHwnd))); // Now we have to set the frame property on the ToolWindowFrame because // this will cause the execution of OnToolWindowCreated and this will add the // command handling for the return key. windowPane.Frame = (IVsWindowFrame)MockFactories.WindowFrameFactory.GetInstance(); CommandTargetHelper helper = new CommandTargetHelper(windowPane as IOleCommandTarget); // Simulate the fact that the cursor is on the last line of the buffer. textLinesMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLineCount"), new object[] { 0, 6 }); // Simulate a cursor 3 chars long. BaseMock markerMock = (BaseMock)textLinesMock["LineMarker"]; TextSpan span = new TextSpan(); span.iEndLine = 5; span.iEndIndex = 3; markerMock["Span"] = span; textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 5, 7 }); helper.ExecCommand(typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (uint)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.BOL); Assert.IsTrue(5 == (int)textViewMock["CaretLine"]); Assert.IsTrue(3 == (int)textViewMock["CaretColumn"]); // Simulate the fact that the cursor is before last line of the buffer. textLinesMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLineCount"), new object[] { 0, 6 }); textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 3, 7 }); helper.ExecCommand(typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (uint)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.BOL); Assert.IsTrue(3 == (int)textViewMock["CaretLine"]); Assert.IsTrue(0 == (int)textViewMock["CaretColumn"]); // Simulate the fact that the cursor is after last line of the buffer. textLinesMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLineCount"), new object[] { 0, 6 }); textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 8, 7 }); helper.ExecCommand(typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (uint)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.BOL); Assert.IsTrue(8 == (int)textViewMock["CaretLine"]); Assert.IsTrue(0 == (int)textViewMock["CaretColumn"]); } } } private static void SetSelectionCallback(object sender, CallbackArgs args) { BaseMock mock = (BaseMock)sender; mock["StartLine"] = (int)args.GetParameter(0); mock["StartColumn"] = (int)args.GetParameter(1); mock["EndLine"] = (int)args.GetParameter(2); mock["EndColumn"] = (int)args.GetParameter(3); args.ReturnValue = Microsoft.VisualStudio.VSConstants.S_OK; } [TestMethod] public void OnShiftHomeTest() { using (OleServiceProvider provider = new OleServiceProvider()) { // Create a mock text buffer for the console. BaseMock textLinesMock = MockFactories.CreateBufferWithMarker(); BaseMock lineMarkerMock = (BaseMock)textLinesMock["LineMarker"]; // Add the text buffer to the local registry LocalRegistryMock mockLocalRegistry = new LocalRegistryMock(); mockLocalRegistry.AddClass(typeof(VsTextBufferClass), textLinesMock); // Define the mock object for the text view and add it to the local registry. BaseMock textViewMock = MockFactories.TextViewFactory.GetInstance(); textViewMock.AddMethodCallback( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "SetSelection"), new EventHandler<CallbackArgs>(SetSelectionCallback)); mockLocalRegistry.AddClass(typeof(VsTextViewClass), textViewMock); // Add the local registry to the list of services. provider.AddService(typeof(SLocalRegistry), mockLocalRegistry, false); // Create the console. using (ToolWindowPane windowPane = CommandWindowHelper.CreateConsoleWindow(provider) as ToolWindowPane) { // Make sure that the text marker is created. CommandWindowHelper.EnsureConsoleTextMarker(windowPane); // Reset the span of the marker. TextSpan markerSpan = new TextSpan(); markerSpan.iStartLine = 0; markerSpan.iStartIndex = 0; markerSpan.iEndLine = 4; markerSpan.iEndIndex = 3; lineMarkerMock["Span"] = markerSpan; // Call the CreatePaneWindow method that will force the creation of the text view. IntPtr newHwnd; Assert.IsTrue(Microsoft.VisualStudio.ErrorHandler.Succeeded( ((IVsWindowPane)windowPane).CreatePaneWindow(IntPtr.Zero, 0, 0, 0, 0, out newHwnd))); // Now we have to set the frame property on the ToolWindowFrame because // this will cause the execution of OnToolWindowCreated and this will add the // command handling for the return key. windowPane.Frame = (IVsWindowFrame)MockFactories.WindowFrameFactory.GetInstance(); CommandTargetHelper helper = new CommandTargetHelper(windowPane as IOleCommandTarget); // Set the cursor after the end of the marker, but on the same line. textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 4, 7 }); helper.ExecCommand( typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.BOL_EXT); Assert.IsTrue(4 == (int)textViewMock["StartLine"]); Assert.IsTrue(4 == (int)textViewMock["EndLine"]); Assert.IsTrue(7 == (int)textViewMock["StartColumn"]); Assert.IsTrue(3 == (int)textViewMock["EndColumn"]); // Set the cursor before the end of the marker, but on the same line. textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 4, 2 }); helper.ExecCommand( typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.BOL_EXT); Assert.IsTrue(4 == (int)textViewMock["StartLine"]); Assert.IsTrue(4 == (int)textViewMock["EndLine"]); Assert.IsTrue(2 == (int)textViewMock["StartColumn"]); Assert.IsTrue(0 == (int)textViewMock["EndColumn"]); // Set the cursor before the end of the marker, on a different line. textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 2, 8 }); helper.ExecCommand( typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.BOL_EXT); Assert.IsTrue(2 == (int)textViewMock["StartLine"]); Assert.IsTrue(2 == (int)textViewMock["EndLine"]); Assert.IsTrue(8 == (int)textViewMock["StartColumn"]); Assert.IsTrue(0 == (int)textViewMock["EndColumn"]); // Set the cursor after the end of the marker, on a different line. textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 9, 12 }); helper.ExecCommand( typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.BOL_EXT); Assert.IsTrue(9 == (int)textViewMock["StartLine"]); Assert.IsTrue(9 == (int)textViewMock["EndLine"]); Assert.IsTrue(12 == (int)textViewMock["StartColumn"]); Assert.IsTrue(0 == (int)textViewMock["EndColumn"]); } } } [TestMethod] public void OnBeforeMoveLeftVerifySender() { using (OleServiceProvider provider = new OleServiceProvider()) { // Create a mock text buffer for the console. BaseMock textLinesMock = MockFactories.TextBufferFactory.GetInstance(); // Add the text buffer to the local registry LocalRegistryMock mockLocalRegistry = new LocalRegistryMock(); mockLocalRegistry.AddClass(typeof(VsTextBufferClass), textLinesMock); // Add the local registry to the list of services. provider.AddService(typeof(SLocalRegistry), mockLocalRegistry, false); // Create the console. using (ToolWindowPane windowPane = CommandWindowHelper.CreateConsoleWindow(provider) as ToolWindowPane) { // Verify OnBeforeMoveLeft can handle a null sender CommandWindowHelper.ExecuteOnBeforeMoveLeft(windowPane, null); // Verify OnBeforeMoveLeft can handle a sender of unexpected type. CommandWindowHelper.ExecuteOnBeforeMoveLeft(windowPane, ""); } } } [TestMethod] public void VerifyOnBeforeMoveLeft() { using (OleServiceProvider provider = new OleServiceProvider()) { // Create a mock text buffer for the console. BaseMock textLinesMock = MockFactories.CreateBufferWithMarker(); // Add the text buffer to the local registry LocalRegistryMock mockLocalRegistry = new LocalRegistryMock(); mockLocalRegistry.AddClass(typeof(VsTextBufferClass), textLinesMock); // Define the mock object for the text view and add it to the local registry. BaseMock textViewMock = MockFactories.TextViewFactory.GetInstance(); mockLocalRegistry.AddClass(typeof(VsTextViewClass), textViewMock); // Add the local registry to the list of services. provider.AddService(typeof(SLocalRegistry), mockLocalRegistry, false); // Create the console. using (ToolWindowPane windowPane = CommandWindowHelper.CreateConsoleWindow(provider) as ToolWindowPane) { // Call the CreatePaneWindow method that will force the creation of the text view. IntPtr newHwnd; Assert.IsTrue(Microsoft.VisualStudio.ErrorHandler.Succeeded( ((IVsWindowPane)windowPane).CreatePaneWindow(IntPtr.Zero, 0, 0, 0, 0, out newHwnd))); // Now we have to set the frame property on the ToolWindowFrame because // this will cause the execution of OnToolWindowCreated and this will add the // command handling for the return key. windowPane.Frame = (IVsWindowFrame)MockFactories.WindowFrameFactory.GetInstance(); // Make sure that the text marker is created. CommandWindowHelper.EnsureConsoleTextMarker(windowPane); BaseMock markerMock = (BaseMock)textLinesMock["LineMarker"]; // Create a OleMenuCommand to use to call OnBeforeHistory. OleMenuCommand cmd = new OleMenuCommand(new EventHandler(EmptyMenuCallback), new CommandID(Guid.Empty, 0)); // Simulate the fact that the cursor is on the last line of the buffer and after the // end of the prompt. cmd.Supported = true; textLinesMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLineCount"), new object[] { 0, 5 }); textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 4, 7 }); TextSpan span = new TextSpan(); span.iEndIndex = 4; span.iEndLine = 3; markerMock["Span"] = span; CommandWindowHelper.ExecuteOnBeforeMoveLeft(windowPane, cmd); Assert.IsFalse(cmd.Supported); // Simulate the cursor over the prompt. textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 4, 3 }); CommandWindowHelper.ExecuteOnBeforeMoveLeft(windowPane, cmd); Assert.IsTrue(cmd.Supported); // Simulate the cursor right after the prompt. cmd.Supported = false; textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 4, 4 }); CommandWindowHelper.ExecuteOnBeforeMoveLeft(windowPane, cmd); Assert.IsTrue(cmd.Supported); // Simulate the cursor on a line before the last. cmd.Supported = true; textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 3, 7 }); CommandWindowHelper.ExecuteOnBeforeMoveLeft(windowPane, cmd); Assert.IsFalse(cmd.Supported); // Simulate the cursor on a line before the last but over the prompt. cmd.Supported = true; textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 3, 2 }); CommandWindowHelper.ExecuteOnBeforeMoveLeft(windowPane, cmd); Assert.IsFalse(cmd.Supported); // Simulate the cursor on a line after the last. cmd.Supported = true; textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 5, 7 }); CommandWindowHelper.ExecuteOnBeforeMoveLeft(windowPane, cmd); Assert.IsFalse(cmd.Supported); // Simulate the cursor on a line after the last, but over the prompt. cmd.Supported = true; textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 5, 0 }); CommandWindowHelper.ExecuteOnBeforeMoveLeft(windowPane, cmd); Assert.IsFalse(cmd.Supported); } } } private static void GetLineTextCallback(object sender, CallbackArgs args) { int startLine = (int)args.GetParameter(0); Assert.IsTrue(12 == startLine); int startPos = (int)args.GetParameter(1); Assert.IsTrue(4 == startPos); int endLine = (int)args.GetParameter(2); Assert.IsTrue(endLine == startLine); int endPos = (int)args.GetParameter(3); Assert.IsTrue(13 == endPos); args.SetParameter(4, "Test Line"); args.ReturnValue = Microsoft.VisualStudio.VSConstants.S_OK; } private static void ExecuteToConsoleCallback(object sender, CallbackArgs args) { BaseMock mock = (BaseMock)sender; mock["ExecutedCommand"] = args.GetParameter(0); } [TestMethod] public void VerifyOnReturn() { using (OleServiceProvider provider = new OleServiceProvider()) { // Create a mock text buffer for the console. BaseMock textLinesMock = MockFactories.CreateBufferWithMarker(); textLinesMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLastLineIndex"), new object[] { 0, 0, 4 }); textLinesMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLengthOfLine"), new object[] { 0, 0, 13 }); textLinesMock.AddMethodCallback( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLineText"), new EventHandler<CallbackArgs>(GetLineTextCallback)); textLinesMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLineCount"), new object[] { 0, 13 }); LocalRegistryMock mockLocalRegistry = new LocalRegistryMock(); mockLocalRegistry.AddClass(typeof(VsTextBufferClass), textLinesMock); // Define the mock object for the text view. BaseMock textViewMock = MockFactories.TextViewFactory.GetInstance(); mockLocalRegistry.AddClass(typeof(VsTextViewClass), textViewMock); // Add the local registry to the list of services. provider.AddService(typeof(SLocalRegistry), mockLocalRegistry, false); // Create a mock engine provider. BaseMock mockEngineProvider = MockFactories.EngineProviderFactory.GetInstance(); // Create a mock engine. BaseMock mockEngine = MockFactories.CreateStandardEngine(); // Set this engine as the one returned from the GetSharedEngine of the engine provider. mockEngineProvider.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IPythonEngineProvider), "GetSharedEngine"), new object[] { (IEngine)mockEngine }); // Set the callback function for the ExecuteToConsole method of the engine. mockEngine.AddMethodCallback( string.Format("{0}.{1}", typeof(IEngine).FullName, "ExecuteToConsole"), new EventHandler<CallbackArgs>(ExecuteToConsoleCallback)); // Add the engine provider to the list of the services. provider.AddService(typeof(IPythonEngineProvider), mockEngineProvider, false); // Create the console window. using (ToolWindowPane windowPane = CommandWindowHelper.CreateConsoleWindow(provider) as ToolWindowPane) { // Call the CreatePaneWindow method that will force the creation of the text view. IntPtr newHwnd; Assert.IsTrue(Microsoft.VisualStudio.ErrorHandler.Succeeded( ((IVsWindowPane)windowPane).CreatePaneWindow(IntPtr.Zero, 0, 0, 0, 0, out newHwnd))); // Make sure that the text marker is created. CommandWindowHelper.EnsureConsoleTextMarker(windowPane); // Now we have to set the frame property on the ToolWindowFrame because // this will cause the execution of OnToolWindowCreated and this will add the // command handling for the return key. windowPane.Frame = (IVsWindowFrame)MockFactories.WindowFrameFactory.GetInstance(); // Simulate the cursor on a line different from the last one. textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 5, 8 }); // Execute the command handler for the RETURN key. CommandTargetHelper helper = new CommandTargetHelper(windowPane as IOleCommandTarget); helper.ExecCommand(typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (uint)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.RETURN); // In this case nothing should happen because we are not on the input line. Assert.IsTrue(0 == CommandWindowHelper.LinesInInputBuffer(windowPane)); // Now simulate the cursor on the input line. textViewMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextView).FullName, "GetCaretPos"), new object[] { 0, 12, 1 }); // Make sure that the mock engine can execute the command. mockEngine.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IEngine).FullName, "ParseInteractiveInput"), new object[] { true }); // Execute the command. helper.ExecCommand(typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (uint)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.RETURN); // The input buffer should not contain any text because the engine should have // executed it. Assert.AreEqual<int>(0, CommandWindowHelper.LinesInInputBuffer(windowPane)); Assert.AreEqual<string>("Test Line", (string)mockEngine["ExecutedCommand"]); // Now change the length of the line so that it is shorter than the // console's prompt. textLinesMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLengthOfLine"), new object[] { 0, 0, 3 }); // Reset the count of the calls to GetLineText so that we can verify // if it is called. textLinesMock.ResetFunctionCalls(string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLineText")); // Do the same for the ParseInteractiveInput method of the engine. mockEngine.ResetFunctionCalls(string.Format("{0}.{1}", typeof(IEngine).FullName, "ParseInteractiveInput")); // Simulate a partial statment. mockEngine.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IEngine).FullName, "ParseInteractiveInput"), new object[] { false }); // Execute again the command handler. helper.ExecCommand(typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (uint)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.RETURN); // Verify that GetLineText was not called. Assert.IsTrue(0 == textLinesMock.FunctionCalls(string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLineText"))); // Verify that the engine was not called to run an interactive command. Assert.IsTrue(1 == mockEngine.FunctionCalls(string.Format("{0}.{1}", typeof(IEngine).FullName, "ParseInteractiveInput"))); // Verify that the console's buffer contains an empty string. Assert.IsTrue(0 == CommandWindowHelper.LinesInInputBuffer(windowPane)); } } } private void ReplaceLinesCallback_ClearPane(object sender, CallbackArgs args) { const int arraySize = 4; BaseMock mock = (BaseMock)sender; int callCount = (int)mock["CallCount"]; int[] expected = (int[])mock["ReplaceRegion"]; for (int i = 0; i < arraySize; i++) { Assert.IsTrue(expected[arraySize * callCount + i] == (int)args.GetParameter(i)); } mock["CallCount"] = callCount + 1; args.ReturnValue = Microsoft.VisualStudio.VSConstants.S_OK; } [TestMethod] public void OnClearPaneOnlyOneLine() { using (OleServiceProvider provider = new OleServiceProvider()) { // Create a mock text buffer for the console. BaseMock textLinesMock = MockFactories.CreateBufferWithMarker(); BaseMock lineMarkerMock = (BaseMock)textLinesMock["LineMarker"]; // Add the text buffer to the local registry LocalRegistryMock mockLocalRegistry = new LocalRegistryMock(); mockLocalRegistry.AddClass(typeof(VsTextBufferClass), textLinesMock); // Define the mock object for the text view and add it to the local registry. BaseMock textViewMock = MockFactories.TextViewFactory.GetInstance(); mockLocalRegistry.AddClass(typeof(VsTextViewClass), textViewMock); // Add the local registry to the list of services. provider.AddService(typeof(SLocalRegistry), mockLocalRegistry, false); // Create the console. using (ToolWindowPane windowPane = CommandWindowHelper.CreateConsoleWindow(provider) as ToolWindowPane) { // Make sure that the text marker is created. CommandWindowHelper.EnsureConsoleTextMarker(windowPane); // Reset the span of the marker. TextSpan markerSpan = new TextSpan(); markerSpan.iStartLine = 0; markerSpan.iStartIndex = 0; markerSpan.iEndLine = 0; markerSpan.iEndIndex = 3; lineMarkerMock["Span"] = markerSpan; // Call the CreatePaneWindow method that will force the creation of the text view. IntPtr newHwnd; Assert.IsTrue(Microsoft.VisualStudio.ErrorHandler.Succeeded( ((IVsWindowPane)windowPane).CreatePaneWindow(IntPtr.Zero, 0, 0, 0, 0, out newHwnd))); // Now we have to set the frame property on the ToolWindowFrame because // this will cause the execution of OnToolWindowCreated and this will add the // command handling for the return key. windowPane.Frame = (IVsWindowFrame)MockFactories.WindowFrameFactory.GetInstance(); CommandTargetHelper helper = new CommandTargetHelper(windowPane as IOleCommandTarget); // Set the last index of the buffer before the end of the line marker. textLinesMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLastLineIndex"), new object[] { 0, 0, 2 }); // Reset the counters of function calls for the text buffer. textLinesMock.ResetAllFunctionCalls(); // Execute the "Clear" command. helper.ExecCommand(typeof(Microsoft.VisualStudio.VSConstants.VSStd97CmdID).GUID, (uint)Microsoft.VisualStudio.VSConstants.VSStd97CmdID.ClearPane); // Verify that ReplaceLines wan never called. Assert.IsTrue(0 == textLinesMock.FunctionCalls(string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "ReplaceLines"))); // Set the last index of the buffer after the end of the line marker. textLinesMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLastLineIndex"), new object[] { 0, 2, 1 }); textLinesMock.AddMethodCallback( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "ReplaceLines"), new EventHandler<CallbackArgs>(ReplaceLinesCallback_ClearPane)); textLinesMock["ReplaceRegion"] = new int[] { 0, 3, 2, 1 }; textLinesMock["CallCount"] = 0; // Reset the counters of function calls for the text buffer. textLinesMock.ResetAllFunctionCalls(); // Execute the "Clear" command. helper.ExecCommand(typeof(Microsoft.VisualStudio.VSConstants.VSStd97CmdID).GUID, (uint)Microsoft.VisualStudio.VSConstants.VSStd97CmdID.ClearPane); // Verify that ReplaceLines wan called only once. Assert.IsTrue(1 == textLinesMock.FunctionCalls(string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "ReplaceLines"))); } } } [TestMethod] public void OnClearPaneMultipleLines() { using (OleServiceProvider provider = new OleServiceProvider()) { // Create a mock text buffer for the console. BaseMock textLinesMock = MockFactories.CreateBufferWithMarker(); textLinesMock.AddMethodCallback( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "ReplaceLines"), new EventHandler<CallbackArgs>(ReplaceLinesCallback_ClearPane)); BaseMock lineMarkerMock = (BaseMock)textLinesMock["LineMarker"]; // Add the text buffer to the local registry LocalRegistryMock mockLocalRegistry = new LocalRegistryMock(); mockLocalRegistry.AddClass(typeof(VsTextBufferClass), textLinesMock); // Define the mock object for the text view and add it to the local registry. BaseMock textViewMock = MockFactories.TextViewFactory.GetInstance(); mockLocalRegistry.AddClass(typeof(VsTextViewClass), textViewMock); // Add the local registry to the list of services. provider.AddService(typeof(SLocalRegistry), mockLocalRegistry, false); // Create the console. using (ToolWindowPane windowPane = CommandWindowHelper.CreateConsoleWindow(provider) as ToolWindowPane) { // Make sure that the text marker is created. CommandWindowHelper.EnsureConsoleTextMarker(windowPane); // Reset the span of the marker. TextSpan markerSpan = new TextSpan(); markerSpan.iStartLine = 0; markerSpan.iStartIndex = 0; markerSpan.iEndLine = 2; markerSpan.iEndIndex = 3; lineMarkerMock["Span"] = markerSpan; // Call the CreatePaneWindow method that will force the creation of the text view. IntPtr newHwnd; Assert.IsTrue(Microsoft.VisualStudio.ErrorHandler.Succeeded( ((IVsWindowPane)windowPane).CreatePaneWindow(IntPtr.Zero, 0, 0, 0, 0, out newHwnd))); // Now we have to set the frame property on the ToolWindowFrame because // this will cause the execution of OnToolWindowCreated and this will add the // command handling for the return key. windowPane.Frame = (IVsWindowFrame)MockFactories.WindowFrameFactory.GetInstance(); CommandTargetHelper helper = new CommandTargetHelper(windowPane as IOleCommandTarget); // Set the last index of the buffer after the end of the line marker. textLinesMock.AddMethodReturnValues( string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "GetLastLineIndex"), new object[] { 0, 2, 8 }); textLinesMock["ReplaceRegion"] = new int[] { 0, 0, 2, 0, 0, 3, 2, 8 }; textLinesMock["CallCount"] = 0; // Reset the counters of function calls for the text buffer. textLinesMock.ResetAllFunctionCalls(); // Execute the "Clear" command. helper.ExecCommand(typeof(Microsoft.VisualStudio.VSConstants.VSStd97CmdID).GUID, (uint)Microsoft.VisualStudio.VSConstants.VSStd97CmdID.ClearPane); // Verify that ReplaceLines wan called 2 times. Assert.IsTrue(2 == textLinesMock.FunctionCalls(string.Format("{0}.{1}", typeof(IVsTextLines).FullName, "ReplaceLines"))); // Verify that the marker was resized. markerSpan = (TextSpan)lineMarkerMock["Span"]; Assert.IsTrue(2 == markerSpan.iStartLine); Assert.IsTrue(0 == markerSpan.iStartIndex); Assert.IsTrue(2 == markerSpan.iEndLine); Assert.IsTrue(3 == markerSpan.iEndIndex); } } } [TestMethod] public void ContextMenuNoUIShell() { using (OleServiceProvider provider = new OleServiceProvider()) { // Create a mock text buffer for the console. BaseMock textLinesMock = MockFactories.TextBufferFactory.GetInstance(); // Add the text buffer to the local registry LocalRegistryMock mockLocalRegistry = new LocalRegistryMock(); mockLocalRegistry.AddClass(typeof(VsTextBufferClass), textLinesMock); // Define the mock object for the text view and add it to the local registry. BaseMock textViewMock = MockFactories.TextViewFactory.GetInstance(); mockLocalRegistry.AddClass(typeof(VsTextViewClass), textViewMock); // Add the local registry to the list of services. provider.AddService(typeof(SLocalRegistry), mockLocalRegistry, false); // Create the console. using (ToolWindowPane windowPane = CommandWindowHelper.CreateConsoleWindow(provider) as ToolWindowPane) { // Call the CreatePaneWindow method that will force the creation of the text view. IntPtr newHwnd; Assert.IsTrue(Microsoft.VisualStudio.ErrorHandler.Succeeded( ((IVsWindowPane)windowPane).CreatePaneWindow(IntPtr.Zero, 0, 0, 0, 0, out newHwnd))); // Now we have to set the frame property on the ToolWindowFrame because // this will cause the execution of OnToolWindowCreated and this will add the // command handlers to the console window. windowPane.Frame = (IVsWindowFrame)MockFactories.WindowFrameFactory.GetInstance(); CommandTargetHelper helper = new CommandTargetHelper(windowPane as IOleCommandTarget); // Verify that the "ShowContextMenu" command handler does not crashes in // case of missing SVsUIShell service. helper.ExecCommand(typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (uint)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.SHOWCONTEXTMENU); } } } [TestMethod] public void ContextMenu() { using (OleServiceProvider provider = new OleServiceProvider()) { // Create a mock text buffer for the console. BaseMock textLinesMock = MockFactories.TextBufferFactory.GetInstance(); // Add the text buffer to the local registry LocalRegistryMock mockLocalRegistry = new LocalRegistryMock(); mockLocalRegistry.AddClass(typeof(VsTextBufferClass), textLinesMock); // Define the mock object for the text view and add it to the local registry. BaseMock textViewMock = MockFactories.TextViewFactory.GetInstance(); mockLocalRegistry.AddClass(typeof(VsTextViewClass), textViewMock); // Add the local registry to the list of services. provider.AddService(typeof(SLocalRegistry), mockLocalRegistry, false); // Create a mock UIShell. BaseMock uiShellMock = MockFactories.UIShellFactory.GetInstance(); provider.AddService(typeof(SVsUIShell), uiShellMock, false); // Create the console. using (ToolWindowPane windowPane = CommandWindowHelper.CreateConsoleWindow(provider) as ToolWindowPane) { // Call the CreatePaneWindow method that will force the creation of the text view. IntPtr newHwnd; Assert.IsTrue(Microsoft.VisualStudio.ErrorHandler.Succeeded( ((IVsWindowPane)windowPane).CreatePaneWindow(IntPtr.Zero, 0, 0, 0, 0, out newHwnd))); // Now we have to set the frame property on the ToolWindowFrame because // this will cause the execution of OnToolWindowCreated and this will add the // command handlers to the console window. windowPane.Frame = (IVsWindowFrame)MockFactories.WindowFrameFactory.GetInstance(); CommandTargetHelper helper = new CommandTargetHelper(windowPane as IOleCommandTarget); // Verify that the "ShowContextMenu" command handler calls the // ShowContextMenu method of IVsUIShell. uiShellMock.ResetFunctionCalls(string.Format("{0}.{1}", typeof(IVsUIShell).FullName, "ShowContextMenu")); helper.ExecCommand(typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID, (uint)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.SHOWCONTEXTMENU); Assert.IsTrue(1 == uiShellMock.FunctionCalls(string.Format("{0}.{1}", typeof(IVsUIShell).FullName, "ShowContextMenu"))); } } } } }
using Godot; // This is identical to the GDScript version, yet it doesn't work. [Tool] public class Viewport25D : Control { private int zoomLevel = 0; private bool isPanning = false; private Vector2 panCenter; private Vector2 viewportCenter; private int viewModeIndex = 0; // The type or namespace name 'EditorInterface' could not be found (are you missing a using directive or an assembly reference?) // No idea why this error shows up in VS Code. It builds fine... public EditorInterface editorInterface; // Set in node25d_plugin.gd private bool moving = false; private Viewport viewport2d; private Viewport viewportOverlay; private ButtonGroup viewModeButtonGroup; private Label zoomLabel; private PackedScene gizmo25dScene; public async override void _Ready() { // Give Godot a chance to fully load the scene. Should take two frames. await ToSignal(GetTree(), "idle_frame"); await ToSignal(GetTree(), "idle_frame"); var editedSceneRoot = GetTree().EditedSceneRoot; if (editedSceneRoot == null) { // Godot hasn't finished loading yet, so try loading the plugin again. //editorInterface.SetPluginEnabled("node25d", false); //editorInterface.SetPluginEnabled("node25d", true); return; } // Alright, we're loaded up. Now check if we have a valid world and assign it. var world2d = editedSceneRoot.GetViewport().World2d; if (world2d == GetViewport().World2d) { return; // This is the MainScreen25D scene opened in the editor! } viewport2d.World2d = world2d; // Onready vars. viewport2d = GetNode<Viewport>("Viewport2D"); viewportOverlay = GetNode<Viewport>("ViewportOverlay"); viewModeButtonGroup = GetParent().GetNode("TopBar").GetNode("ViewModeButtons").GetNode<Button>("45Degree").Group; zoomLabel = GetParent().GetNode("TopBar").GetNode("Zoom").GetNode<Label>("ZoomPercent"); gizmo25dScene = ResourceLoader.Load<PackedScene>("res://addons/node25d/main_screen/gizmo_25d.tscn"); } public override void _Process(float delta) { if (editorInterface == null) // Something's not right... bail! { return; } // View mode polling. var viewModeChangedThisFrame = false; var newViewMode = viewModeButtonGroup.GetPressedButton().GetIndex(); if (viewModeIndex != newViewMode) { viewModeIndex = newViewMode; viewModeChangedThisFrame = true; RecursiveChangeViewMode(GetTree().EditedSceneRoot); } // Zooming. if (Input.IsMouseButtonPressed((int)ButtonList.WheelUp)) { zoomLevel += 1; } else if (Input.IsMouseButtonPressed((int)ButtonList.WheelDown)) { zoomLevel -= 1; } float zoom = GetZoomAmount(); // Viewport size. Vector2 size = GetGlobalRect().Size; viewport2d.Size = size; // Viewport transform. Transform2D viewportTrans = Transform2D.Identity; viewportTrans.x *= zoom; viewportTrans.y *= zoom; viewportTrans.origin = viewportTrans.BasisXform(viewportCenter) + size / 2; viewport2d.CanvasTransform = viewportTrans; viewportOverlay.CanvasTransform = viewportTrans; // Delete unused gizmos. var selection = editorInterface.GetSelection().GetSelectedNodes(); var overlayChildren = viewportOverlay.GetChildren(); foreach (Gizmo25D overlayChild in overlayChildren) { bool contains = false; foreach (Node selected in selection) { if (selected == overlayChild.node25d && !viewModeChangedThisFrame) { contains = true; } } if (!contains) { overlayChild.QueueFree(); } } // Add new gizmos. foreach (Node sel in selection) { if (sel is Node25D selected) { var newNode = true; foreach (Gizmo25D overlayChild2 in overlayChildren) { if (selected == overlayChild2.node25d) { newNode = false; } } if (newNode) { Gizmo25D gizmo = (Gizmo25D)gizmo25dScene.Instance(); viewportOverlay.AddChild(gizmo); gizmo.node25d = selected; gizmo.Initialize(); } } } } // This only accepts input when the mouse is inside of the 2.5D viewport. public override void _GuiInput(InputEvent inputEvent) { if (inputEvent is InputEventMouseButton mouseButtonEvent) { if (mouseButtonEvent.IsPressed()) { if ((ButtonList)mouseButtonEvent.ButtonIndex == ButtonList.WheelUp) { zoomLevel += 1; AcceptEvent(); } else if ((ButtonList)mouseButtonEvent.ButtonIndex == ButtonList.WheelDown) { zoomLevel -= 1; AcceptEvent(); } else if ((ButtonList)mouseButtonEvent.ButtonIndex == ButtonList.Middle) { isPanning = true; panCenter = viewportCenter - mouseButtonEvent.Position; AcceptEvent(); } else if ((ButtonList)mouseButtonEvent.ButtonIndex == ButtonList.Left) { var overlayChildren2 = viewportOverlay.GetChildren(); foreach (Gizmo25D overlayChild in overlayChildren2) { overlayChild.wantsToMove = true; } AcceptEvent(); } } else if ((ButtonList)mouseButtonEvent.ButtonIndex == ButtonList.Middle) { isPanning = false; AcceptEvent(); } else if ((ButtonList)mouseButtonEvent.ButtonIndex == ButtonList.Left) { var overlayChildren3 = viewportOverlay.GetChildren(); foreach (Gizmo25D overlayChild in overlayChildren3) { overlayChild.wantsToMove = false; } AcceptEvent(); } } else if (inputEvent is InputEventMouseMotion mouseEvent) { if (isPanning) { viewportCenter = panCenter + mouseEvent.Position; AcceptEvent(); } } } public void RecursiveChangeViewMode(Node currentNode) { // TODO if (currentNode.HasMethod("SetViewMode")) { //currentNode.SetViewMode(viewModeIndex); } foreach (Node child in currentNode.GetChildren()) { RecursiveChangeViewMode(child); } } private float GetZoomAmount() { float zoomAmount = Mathf.Pow(1.05476607648f, zoomLevel); // 13th root of 2 zoomLabel.Text = Mathf.Round(zoomAmount * 1000) / 10 + "%"; return zoomAmount; } public void OnZoomOutPressed() { zoomLevel -= 1; } public void OnZoomInPressed() { zoomLevel += 1; } public void OnZoomResetPressed() { zoomLevel = 0; } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Xml; namespace WebsitePanel.Setup { public class Global { public const string SilentInstallerShell = "SilentInstallerShell"; public const string DefaultInstallPathRoot = @"C:\WebsitePanel"; public const string LoopbackIPv4 = "127.0.0.1"; public const string InstallerProductCode = "cfg core"; public const string DefaultProductName = "WebsitePanel"; public abstract class Parameters { public const string ComponentId = "ComponentId"; public const string EnterpriseServerUrl = "EnterpriseServerUrl"; public const string ShellMode = "ShellMode"; public const string ShellVersion = "ShellVersion"; public const string IISVersion = "IISVersion"; public const string BaseDirectory = "BaseDirectory"; public const string Installer = "Installer"; public const string InstallerType = "InstallerType"; public const string InstallerPath = "InstallerPath"; public const string InstallerFolder = "InstallerFolder"; public const string Version = "Version"; public const string ComponentDescription = "ComponentDescription"; public const string ComponentCode = "ComponentCode"; public const string ApplicationName = "ApplicationName"; public const string ComponentName = "ComponentName"; public const string WebSiteIP = "WebSiteIP"; public const string WebSitePort = "WebSitePort"; public const string WebSiteDomain = "WebSiteDomain"; public const string ServerPassword = "ServerPassword"; public const string UserDomain = "UserDomain"; public const string UserAccount = "UserAccount"; public const string NewUserAccount = "NewUserAccount"; public const string UserPassword = "UserPassword"; public const string CryptoKey = "CryptoKey"; public const string ServerAdminPassword = "ServerAdminPassword"; public const string SetupXml = "SetupXml"; public const string ParentForm = "ParentForm"; public const string Component = "Component"; public const string FullFilePath = "FullFilePath"; public const string DatabaseServer = "DatabaseServer"; public const string DbServerAdmin = "DbServerAdmin"; public const string DbServerAdminPassword = "DbServerAdminPassword"; public const string DatabaseName = "DatabaseName"; public const string ConnectionString = "ConnectionString"; public const string InstallConnectionString = "InstallConnectionString"; public const string Release = "Release"; public const string SchedulerServiceFileName = "WebsitePanel.SchedulerService.exe"; public const string SchedulerServiceName = "WebsitePanel Scheduler"; public const string DatabaseUser = "DatabaseUser"; public const string DatabaseUserPassword = "DatabaseUserPassword"; } public abstract class Messages { public const string NotEnoughPermissionsError = "You do not have the appropriate permissions to perform this operation. Make sure you are running the application from the local disk and you have local system administrator privileges."; public const string InstallerVersionIsObsolete = "WebsitePanel Installer {0} or higher required."; public const string ComponentIsAlreadyInstalled = "Component or its part is already installed."; public const string AnotherInstanceIsRunning = "Another instance of the installation process is already running."; public const string NoInputParametersSpecified = "No input parameters specified"; public const int InstallationError = -1000; public const int UnknownComponentCodeError = -999; public const int SuccessInstallation = 0; public const int AnotherInstanceIsRunningError = -998; public const int NotEnoughPermissionsErrorCode = -997; public const int NoInputParametersSpecifiedError = -996; public const int ComponentIsAlreadyInstalledError = -995; } public abstract class Server { public abstract class CLI { public const string ServerPassword = "passw"; }; public const string ComponentName = "Server"; public const string ComponentCode = "server"; public const string ComponentDescription = "WebsitePanel Server is a set of services running on the remote server to be controlled. Server application should be reachable from Enterprise Server one."; public const string ServiceAccount = "WPServer"; public const string DefaultPort = "9003"; public const string DefaultIP = "127.0.0.1"; public const string SetupController = "Server"; public static string[] ServiceUserMembership { get { if (IISVersion.Major >= 7) { return new string[] { "AD:Domain Admins", "SID:" + SystemSID.ADMINISTRATORS, "IIS_IUSRS" }; } // return new string[] { "AD:Domain Admins", "SID:" + SystemSID.ADMINISTRATORS, "IIS_WPG" }; } } } public abstract class StandaloneServer { public const string SetupController = "StandaloneServerSetup"; public const string ComponentCode = "standalone"; public const string ComponentName = "Standalone Server Setup"; } public abstract class WebPortal { public const string ComponentName = "Portal"; public const string ComponentDescription = "WebsitePanel Portal is a control panel itself with user interface which allows managing user accounts, hosting spaces, web sites, FTP accounts, files, etc."; public const string ServiceAccount = "WPPortal"; public const string DefaultPort = "9001"; public const string DefaultIP = ""; public const string DefaultEntServURL = "http://127.0.0.1:9002"; public const string ComponentCode = "portal"; public const string SetupController = "Portal"; public static string[] ServiceUserMembership { get { if (IISVersion.Major >= 7) { return new string[] { "IIS_IUSRS" }; } // return new string[] { "IIS_WPG" }; } } public abstract class CLI { public const string EnterpriseServerUrl = "esurl"; } } public abstract class EntServer { public const string ComponentName = "Enterprise Server"; public const string ComponentDescription = "Enterprise Server is the heart of WebsitePanel system. It includes all business logic of the application. Enterprise Server should have access to Server and be accessible from Portal applications."; public const string ServiceAccount = "WPEnterpriseServer"; public const string DefaultPort = "9002"; public const string DefaultIP = "127.0.0.1"; public const string DefaultDbServer = @"localhost\sqlexpress"; public const string DefaultDatabase = "WebsitePanel"; public const string AspNetConnectionStringFormat = "server={0};database={1};uid={2};pwd={3};"; public const string ComponentCode = "enterprise server"; public const string SetupController = "EnterpriseServer"; public static string[] ServiceUserMembership { get { if (IISVersion.Major >= 7) { return new string[] { "IIS_IUSRS" }; } // return new string[] { "IIS_WPG" }; } } public abstract class CLI { public const string ServeradminPassword = "passw"; public const string DatabaseName = "dbname"; public const string DatabaseServer = "dbserver"; public const string DbServerAdmin = "dbadmin"; public const string DbServerAdminPassword = "dbapassw"; } } public abstract class Scheduler { public const string ComponentName = "Scheduler Service"; public const string ComponentCode = "scheduler service"; } public abstract class CLI { public const string WebSiteIP = "webip"; public const string ServiceAccountPassword = "upassw"; public const string ServiceAccountDomain = "udomaim"; public const string ServiceAccountName = "uname"; public const string WebSitePort = "webport"; public const string WebSiteDomain = "webdom"; } private Global() { } private static Version iisVersion; // public static Version IISVersion { get { if (iisVersion == null) { iisVersion = RegistryUtils.GetIISVersion(); } // return iisVersion; } } // private static OS.WindowsVersion osVersion = OS.WindowsVersion.Unknown; /// <summary> /// Represents Setup Control Panel Accounts system settings set (SCPA) /// </summary> public class SCPA { public const string SettingsKeyName = "EnabledSCPA"; } public static OS.WindowsVersion OSVersion { get { if (osVersion == OS.WindowsVersion.Unknown) { osVersion = OS.GetVersion(); } // return osVersion; } } public static XmlDocument SetupXmlDocument { get; set; } } public class SetupEventArgs<T> : EventArgs { public T EventData { get; set; } public string EventMessage { get; set; } } }
/* Copyright (c) 2017 Marcin Szeniak (https://github.com/Klocman/) Apache License Version 2.0 */ using System; using System.Collections; using System.Windows.Forms; using System.Text.RegularExpressions; namespace Klocman { public enum SortModifiers { SortByImage, SortByCheckbox, SortByText } /// <summary> /// This class is an implementation of the 'IComparer' interface. /// </summary> public sealed class ListViewColumnSorter : IComparer { /// <summary> /// Specifies the column to be sorted /// </summary> public int ColumnToSort { get; set; } /// <summary> /// Specifies the order in which to sort (i.e. 'Ascending'). /// </summary> public SortOrder OrderOfSort { get; set; } /// <summary> /// Case insensitive comparer object /// </summary> private NumberCaseInsensitiveComparer ObjectCompare; private ImageTextComparer FirstObjectCompare; private CheckboxTextComparer FirstObjectCompare2; private SortModifiers mySortModifier = SortModifiers.SortByText; public SortModifiers _SortModifier { set { mySortModifier = value; } get { return mySortModifier; } } /// <summary> /// Class constructor. Initializes various elements /// </summary> public ListViewColumnSorter() { // Initialize the column to '0' //ColumnToSort = 0; // Initialize the CaseInsensitiveComparer object ObjectCompare = new NumberCaseInsensitiveComparer(); FirstObjectCompare = new ImageTextComparer(); FirstObjectCompare2 = new CheckboxTextComparer(); } /// <summary> /// This method is inherited from the IComparer interface. It compares the two objects passed using a case insensitive comparison. /// </summary> /// <param name="x">First object to be compared</param> /// <param name="y">Second object to be compared</param> /// <returns>The result of the comparison. "0" if equal, negative if 'x' is less than 'y' and positive if 'x' is greater than 'y'</returns> public int Compare(object x, object y) { int compareResult = 0; ListViewItem listviewX, listviewY; // Cast the objects to be compared to ListViewItem objects listviewX = (ListViewItem)x; listviewY = (ListViewItem)y; ListView listViewMain = listviewX.ListView; // Calculate correct return value based on object comparison if (listViewMain.Sorting != SortOrder.Ascending && listViewMain.Sorting != SortOrder.Descending) { // Return '0' to indicate they are equal return compareResult; } if (mySortModifier.Equals(SortModifiers.SortByText) || ColumnToSort > 0) { // Compare the two items if (listviewX.SubItems.Count <= ColumnToSort && listviewY.SubItems.Count <= ColumnToSort) { compareResult = ObjectCompare.Compare(null, null); } else if (listviewX.SubItems.Count <= ColumnToSort && listviewY.SubItems.Count > ColumnToSort) { compareResult = ObjectCompare.Compare(null, listviewY.SubItems[ColumnToSort].Text.Trim()); } else if (listviewX.SubItems.Count > ColumnToSort && listviewY.SubItems.Count <= ColumnToSort) { compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text.Trim(), null); } else { compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text.Trim(), listviewY.SubItems[ColumnToSort].Text.Trim()); } } else { switch (mySortModifier) { case SortModifiers.SortByCheckbox: compareResult = FirstObjectCompare2.Compare(x, y); break; case SortModifiers.SortByImage: compareResult = FirstObjectCompare.Compare(x, y); break; default: compareResult = FirstObjectCompare.Compare(x, y); break; } } // Calculate correct return value based on object comparison if (OrderOfSort == SortOrder.Ascending) { // Ascending sort is selected, return normal result of compare operation return compareResult; } else if (OrderOfSort == SortOrder.Descending) { // Descending sort is selected, return negative result of compare operation return (-compareResult); } else { // Return '0' to indicate they are equal return 0; } } /// <summary> /// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0'). /// </summary> public int SortColumn { set { ColumnToSort = value; } get { return ColumnToSort; } } /// <summary> /// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending'). /// </summary> public SortOrder Order { set { OrderOfSort = value; } get { return OrderOfSort; } } } public sealed class ImageTextComparer : IComparer { //private CaseInsensitiveComparer ObjectCompare; private NumberCaseInsensitiveComparer ObjectCompare; public ImageTextComparer() { // Initialize the CaseInsensitiveComparer object ObjectCompare = new NumberCaseInsensitiveComparer(); } public int Compare(object x, object y) { //int compareResult; int image1, image2; ListViewItem listviewX, listviewY; // Cast the objects to be compared to ListViewItem objects listviewX = (ListViewItem)x; image1 = listviewX.ImageIndex; listviewY = (ListViewItem)y; image2 = listviewY.ImageIndex; if (image1 < image2) { return -1; } else if (image1 == image2) { return ObjectCompare.Compare(listviewX.Text.Trim(), listviewY.Text.Trim()); } else { return 1; } } } public sealed class CheckboxTextComparer : IComparer { private NumberCaseInsensitiveComparer ObjectCompare; public CheckboxTextComparer() { // Initialize the CaseInsensitiveComparer object ObjectCompare = new NumberCaseInsensitiveComparer(); } public int Compare(object x, object y) { // Cast the objects to be compared to ListViewItem objects ListViewItem listviewX = (ListViewItem)x; ListViewItem listviewY = (ListViewItem)y; if (listviewX.Checked && !listviewY.Checked) { return -1; } else if (listviewX.Checked.Equals(listviewY.Checked)) { if (listviewX.ImageIndex < listviewY.ImageIndex) { return -1; } else if (listviewX.ImageIndex == listviewY.ImageIndex) { return ObjectCompare.Compare(listviewX.Text.Trim(), listviewY.Text.Trim()); } else { return 1; } } else { return 1; } } } public sealed class NumberCaseInsensitiveComparer : CaseInsensitiveComparer { public NumberCaseInsensitiveComparer() { } public new int Compare(object x, object y) { if (x == null && y == null) { return 0; } else if (x == null && y != null) { return -1; } else if (x != null && y == null) { return 1; } var xs = x as string; var ys = y as string; if (xs != null && IsWholeNumber(xs) && ys != null && IsWholeNumber(ys)) { try { return base.Compare(Convert.ToUInt64(xs.Trim()), Convert.ToUInt64(ys.Trim())); } catch { return -1; } } else { return base.Compare(x, y); } } private bool IsWholeNumber(string strNumber) { Regex wholePattern = new Regex(@"^\d+$"); return wholePattern.IsMatch(strNumber); } } }
using UnityEngine; namespace Xft { public class RibbonTrail { public const int CHAIN_EMPTY = 99999; protected Color Color = Color.white; protected float ElapsedTime; public int ElemCount; public Element[] ElementArray; protected float ElemLength; protected float Fps; public int Head; protected Vector3 HeadPosition; protected bool IndexDirty; protected Vector2 LowerLeftUV; public int MaxElements; public float SquaredElemLength; protected int StretchType; public int Tail; protected float TrailLength; protected float UnitWidth; protected Vector2 UVDimensions; protected VertexPool.VertexSegment Vertexsegment; public RibbonTrail(VertexPool.VertexSegment segment, float width, int maxelemnt, float len, Vector3 pos, int stretchType, float maxFps) { if (maxelemnt <= 2) { Debug.LogError("ribbon trail's maxelement should > 2!"); } this.MaxElements = maxelemnt; this.Vertexsegment = segment; this.ElementArray = new Element[this.MaxElements]; this.Tail = 99999; this.Head = 99999; this.SetTrailLen(len); this.UnitWidth = width; this.HeadPosition = pos; this.StretchType = stretchType; Element dtls = new Element(this.HeadPosition, this.UnitWidth); this.IndexDirty = false; this.Fps = 1f / maxFps; this.AddElememt(dtls); Element element2 = new Element(this.HeadPosition, this.UnitWidth); this.AddElememt(element2); } public void AddElememt(Element dtls) { if (this.Head == 99999) { this.Tail = this.MaxElements - 1; this.Head = this.Tail; this.IndexDirty = true; this.ElemCount++; } else { if (this.Head == 0) { this.Head = this.MaxElements - 1; } else { this.Head--; } if (this.Head == this.Tail) { if (this.Tail == 0) { this.Tail = this.MaxElements - 1; } else { this.Tail--; } } else { this.ElemCount++; } } this.ElementArray[this.Head] = dtls; this.IndexDirty = true; } public void Reset() { this.ResetElementsPos(); } public void ResetElementsPos() { if (this.Head != 99999 && this.Head != this.Tail) { int head = this.Head; while (true) { int index = head; if (index == this.MaxElements) { index = 0; } this.ElementArray[index].Position = this.HeadPosition; if (index == this.Tail) { return; } head = index + 1; } } } public void SetColor(Color color) { this.Color = color; } public void SetHeadPosition(Vector3 pos) { this.HeadPosition = pos; } public void SetTrailLen(float len) { this.TrailLength = len; this.ElemLength = this.TrailLength / (this.MaxElements - 1); this.SquaredElemLength = this.ElemLength * this.ElemLength; } public void SetUVCoord(Vector2 lowerleft, Vector2 dimensions) { this.LowerLeftUV = lowerleft; this.UVDimensions = dimensions; } public void Smooth() { if (this.ElemCount > 3) { Element element = this.ElementArray[this.Head]; int index = this.Head + 1; if (index == this.MaxElements) { index = 0; } int num2 = index + 1; if (num2 == this.MaxElements) { num2 = 0; } Element element2 = this.ElementArray[index]; Element element3 = this.ElementArray[num2]; Vector3 from = element.Position - element2.Position; Vector3 to = element2.Position - element3.Position; float num3 = Vector3.Angle(from, to); if (num3 > 60f) { Vector3 vector3 = (element.Position + element3.Position) / 2f; Vector3 vector4 = vector3 - element2.Position; Vector3 zero = Vector3.zero; float smoothTime = 0.1f / (num3 / 60f); element2.Position = Vector3.SmoothDamp(element2.Position, element2.Position + vector4.normalized * element2.Width, ref zero, smoothTime); } } } public void Update() { this.ElapsedTime += Time.deltaTime; if (this.ElapsedTime >= this.Fps) { this.ElapsedTime -= this.Fps; bool flag = false; while (!flag) { Element element = this.ElementArray[this.Head]; int index = this.Head + 1; if (index == this.MaxElements) { index = 0; } Element element2 = this.ElementArray[index]; Vector3 headPosition = this.HeadPosition; Vector3 vector2 = headPosition - element2.Position; if (vector2.sqrMagnitude >= this.SquaredElemLength) { Vector3 vector3 = vector2 * (this.ElemLength / vector2.magnitude); element.Position = element2.Position + vector3; Element dtls = new Element(headPosition, this.UnitWidth); this.AddElememt(dtls); vector2 = headPosition - element.Position; if (vector2.sqrMagnitude <= this.SquaredElemLength) { flag = true; } } else { element.Position = headPosition; flag = true; } if ((this.Tail + 1) % this.MaxElements == this.Head) { int num3; Element element4 = this.ElementArray[this.Tail]; if (this.Tail == 0) { num3 = this.MaxElements - 1; } else { num3 = this.Tail - 1; } Element element5 = this.ElementArray[num3]; Vector3 vector4 = element4.Position - element5.Position; float magnitude = vector4.magnitude; if (magnitude > 1E-06) { float num5 = this.ElemLength - vector2.magnitude; vector4 = vector4 * (num5 / magnitude); element4.Position = element5.Position + vector4; } } } Vector3 position = Camera.main.transform.position; this.UpdateVertices(position); this.UpdateIndices(); } } public void UpdateIndices() { if (this.IndexDirty) { VertexPool pool = this.Vertexsegment.Pool; if (this.Head != 99999 && this.Head != this.Tail) { int head = this.Head; int num2 = 0; while (true) { int num3 = head + 1; if (num3 == this.MaxElements) { num3 = 0; } if (num3 * 2 >= 65536) { Debug.LogError("Too many elements!"); } int num4 = this.Vertexsegment.VertStart + num3 * 2; int num5 = this.Vertexsegment.VertStart + head * 2; int index = this.Vertexsegment.IndexStart + num2 * 6; pool.Indices[index] = num5; pool.Indices[index + 1] = num5 + 1; pool.Indices[index + 2] = num4; pool.Indices[index + 3] = num5 + 1; pool.Indices[index + 4] = num4 + 1; pool.Indices[index + 5] = num4; if (num3 == this.Tail) { pool.IndiceChanged = true; break; } head = num3; num2++; } } this.IndexDirty = false; } } public void UpdateVertices(Vector3 eyePos) { float num = 0f; float num2 = 0f; float num3 = this.ElemLength * (this.MaxElements - 2); if (this.Head != 99999 && this.Head != this.Tail) { int head = this.Head; int index = this.Head; while (true) { Vector3 vector; if (index == this.MaxElements) { index = 0; } Element element = this.ElementArray[index]; if (index * 2 >= 65536) { Debug.LogError("Too many elements!"); } int num6 = this.Vertexsegment.VertStart + index * 2; int num7 = index + 1; if (num7 == this.MaxElements) { num7 = 0; } if (index == this.Head) { vector = this.ElementArray[num7].Position - element.Position; } else if (index == this.Tail) { vector = element.Position - this.ElementArray[head].Position; } else { vector = this.ElementArray[num7].Position - this.ElementArray[head].Position; } Vector3 rhs = eyePos - element.Position; Vector3 vector3 = Vector3.Cross(vector, rhs); vector3.Normalize(); vector3 = vector3 * (element.Width * 0.5f); Vector3 vector4 = element.Position - vector3; Vector3 vector5 = element.Position + vector3; VertexPool pool = this.Vertexsegment.Pool; if (this.StretchType == 0) { num = num2 / num3 * Mathf.Abs(this.UVDimensions.y); } else { num = num2 / num3 * Mathf.Abs(this.UVDimensions.x); } Vector2 zero = Vector2.zero; pool.Vertices[num6] = vector4; pool.Colors[num6] = this.Color; if (this.StretchType == 0) { zero.x = this.LowerLeftUV.x + this.UVDimensions.x; zero.y = this.LowerLeftUV.y - num; } else { zero.x = this.LowerLeftUV.x + num; zero.y = this.LowerLeftUV.y; } pool.UVs[num6] = zero; pool.Vertices[num6 + 1] = vector5; pool.Colors[num6 + 1] = this.Color; if (this.StretchType == 0) { zero.x = this.LowerLeftUV.x; zero.y = this.LowerLeftUV.y - num; } else { zero.x = this.LowerLeftUV.x + num; zero.y = this.LowerLeftUV.y - Mathf.Abs(this.UVDimensions.y); } pool.UVs[num6 + 1] = zero; if (index == this.Tail) { this.Vertexsegment.Pool.UVChanged = true; this.Vertexsegment.Pool.VertChanged = true; this.Vertexsegment.Pool.ColorChanged = true; return; } head = index; Vector3 vector7 = this.ElementArray[num7].Position - element.Position; num2 += vector7.magnitude; index++; } } } public class Element { public Vector3 Position; public float Width; public Element(Vector3 position, float width) { this.Position = position; this.Width = width; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Text; using System.IO; using System.Diagnostics; [assembly: System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] namespace System.Xml.XmlDiff { internal enum DiffType { None, Success, Element, Whitespace, Comment, PI, Text, CData, Attribute, NS, Prefix, SourceExtra, TargetExtra, NodeType } public class XmlDiff { private XmlDiffDocument _SourceDoc; private XmlDiffDocument _TargetDoc; private XmlWriter _Writer; // Writer to write out the result private StringBuilder _Output; // Option Flags private XmlDiffOption _XmlDiffOption = XmlDiffOption.None; private bool _IgnoreEmptyElement = true; private bool _IgnoreWhitespace = true; private bool _IgnoreComments = false; private bool _IgnoreAttributeOrder = true; private bool _IgnoreNS = true; private bool _IgnorePrefix = true; private bool _IgnoreDTD = true; private bool _IgnoreChildOrder = true; public XmlDiff() { } public XmlDiffOption Option { get { return _XmlDiffOption; } set { _XmlDiffOption = value; IgnoreEmptyElement = (((int)_XmlDiffOption) & ((int)XmlDiffOption.IgnoreEmptyElement)) > 0; IgnoreWhitespace = (((int)_XmlDiffOption) & ((int)XmlDiffOption.IgnoreWhitespace)) > 0; IgnoreComments = (((int)_XmlDiffOption) & ((int)XmlDiffOption.IgnoreComments)) > 0; IgnoreAttributeOrder = (((int)_XmlDiffOption) & ((int)XmlDiffOption.IgnoreAttributeOrder)) > 0; IgnoreNS = (((int)_XmlDiffOption) & ((int)XmlDiffOption.IgnoreNS)) > 0; IgnorePrefix = (((int)_XmlDiffOption) & ((int)XmlDiffOption.IgnorePrefix)) > 0; IgnoreDTD = (((int)_XmlDiffOption) & ((int)XmlDiffOption.IgnoreDTD)) > 0; IgnoreChildOrder = (((int)_XmlDiffOption) & ((int)XmlDiffOption.IgnoreChildOrder)) > 0; } } internal bool IgnoreEmptyElement { get { return _IgnoreEmptyElement; } set { _IgnoreEmptyElement = value; } } internal bool IgnoreComments { get { return _IgnoreComments; } set { _IgnoreComments = value; } } internal bool IgnoreAttributeOrder { get { return _IgnoreAttributeOrder; } set { _IgnoreAttributeOrder = value; } } internal bool IgnoreWhitespace { get { return _IgnoreWhitespace; } set { _IgnoreWhitespace = value; } } internal bool IgnoreNS { get { return _IgnoreNS; } set { _IgnoreNS = value; } } internal bool IgnorePrefix { get { return _IgnorePrefix; } set { _IgnorePrefix = value; } } internal bool IgnoreDTD { get { return _IgnoreDTD; } set { _IgnoreDTD = value; } } internal bool IgnoreChildOrder { get { return _IgnoreChildOrder; } set { _IgnoreChildOrder = value; } } private void InitFiles() { this._SourceDoc = new XmlDiffDocument(); this._SourceDoc.Option = this._XmlDiffOption; this._TargetDoc = new XmlDiffDocument(); this._TargetDoc.Option = this.Option; _Output = new StringBuilder(String.Empty); } public bool Compare(Stream source, Stream target) { InitFiles(); this._SourceDoc.Load(XmlReader.Create(source)); this._TargetDoc.Load(XmlReader.Create(target)); return Diff(); } public bool Compare(XmlReader source, XmlReader target) { InitFiles(); this._SourceDoc.Load(source); this._TargetDoc.Load(target); return Diff(); } public bool Compare(XmlReader source, XmlReader target, XmlDiffAdvancedOptions advOptions) { InitFiles(); this._SourceDoc.Load(source); this._TargetDoc.Load(target); XmlDiffNavigator nav = this._SourceDoc.CreateNavigator(); if (advOptions.IgnoreChildOrderExpr != null && advOptions.IgnoreChildOrderExpr != "") { this._SourceDoc.SortChildren(); this._TargetDoc.SortChildren(); } return Diff(); } private bool Diff() { bool flag = false; XmlWriterSettings xws = new XmlWriterSettings(); xws.ConformanceLevel = ConformanceLevel.Auto; xws.CheckCharacters = false; _Writer = XmlWriter.Create(new StringWriter(_Output), xws); _Writer.WriteStartElement(String.Empty, "Root", String.Empty); flag = CompareChildren(this._SourceDoc, this._TargetDoc); _Writer.WriteEndElement(); _Writer.Dispose(); return flag; } // This function is being called recursively to compare the children of a certain node. // When calling this function the navigator should be pointing at the parent node whose children // we wants to compare and return the navigator back to the same node before exiting from it. private bool CompareChildren(XmlDiffNode sourceNode, XmlDiffNode targetNode) { XmlDiffNode sourceChild = sourceNode.FirstChild; XmlDiffNode targetChild = targetNode.FirstChild; bool flag = true; bool tempFlag = true; DiffType result; // Loop to compare all the child elements of the parent node while (sourceChild != null || targetChild != null) { //Console.WriteLine( (sourceChild!=null)?(sourceChild.NodeType.ToString()):"null" ); //Console.WriteLine( (targetChild!=null)?(targetChild.NodeType.ToString()):"null" ); if (sourceChild != null) { if (targetChild != null) { // Both Source and Target Read successful if ((result = CompareNodes(sourceChild, targetChild)) == DiffType.Success) { // Child nodes compared successfully, write out the result WriteResult(sourceChild, targetChild, DiffType.Success); // Check whether this Node has Children, if it does call CompareChildren recursively if (sourceChild.FirstChild != null) tempFlag = CompareChildren(sourceChild, targetChild); else if (targetChild.FirstChild != null) { WriteResult(null, targetChild, DiffType.TargetExtra); tempFlag = false; } // set the compare flag flag = (flag && tempFlag); // Writing out End Element to the result if (sourceChild.NodeType == XmlDiffNodeType.Element && !(sourceChild is XmlDiffEmptyElement)) { XmlDiffElement sourceElem = sourceChild as XmlDiffElement; XmlDiffElement targetElem = targetChild as XmlDiffElement; Debug.Assert(sourceElem != null); Debug.Assert(targetElem != null); _Writer.WriteStartElement(String.Empty, "Node", String.Empty); _Writer.WriteAttributeString(String.Empty, "SourceLineNum", String.Empty, sourceElem.EndLineNumber.ToString()); _Writer.WriteAttributeString(String.Empty, "SourceLinePos", String.Empty, sourceElem.EndLinePosition.ToString()); _Writer.WriteAttributeString(String.Empty, "TargetLineNum", String.Empty, targetElem.EndLineNumber.ToString()); _Writer.WriteAttributeString(String.Empty, "TargetLinePos", String.Empty, targetElem.EndLinePosition.ToString()); _Writer.WriteStartElement(String.Empty, "Diff", String.Empty); _Writer.WriteEndElement(); _Writer.WriteStartElement(String.Empty, "Lexical-equal", String.Empty); _Writer.WriteCData("</" + sourceElem.Name + ">"); _Writer.WriteEndElement(); _Writer.WriteEndElement(); } // Move to Next child sourceChild = sourceChild.NextSibling; targetChild = targetChild.NextSibling; } else { // Child nodes not matched, start the recovery process bool recoveryFlag = false; // Try to match the source node with the target nodes at the same level XmlDiffNode backupTargetChild = targetChild.NextSibling; while (!recoveryFlag && backupTargetChild != null) { if (CompareNodes(sourceChild, backupTargetChild) == DiffType.Success) { recoveryFlag = true; do { WriteResult(null, targetChild, DiffType.TargetExtra); targetChild = targetChild.NextSibling; } while (targetChild != backupTargetChild); break; } backupTargetChild = backupTargetChild.NextSibling; } // If not recovered, try to match the target node with the source nodes at the same level if (!recoveryFlag) { XmlDiffNode backupSourceChild = sourceChild.NextSibling; while (!recoveryFlag && backupSourceChild != null) { if (CompareNodes(backupSourceChild, targetChild) == DiffType.Success) { recoveryFlag = true; do { WriteResult(sourceChild, null, DiffType.SourceExtra); sourceChild = sourceChild.NextSibling; } while (sourceChild != backupSourceChild); break; } backupSourceChild = backupSourceChild.NextSibling; } } // If still not recovered, write both of them as different nodes and move on if (!recoveryFlag) { WriteResult(sourceChild, targetChild, result); // Check whether this Node has Children, if it does call CompareChildren recursively if (sourceChild.FirstChild != null) { tempFlag = CompareChildren(sourceChild, targetChild); } else if (targetChild.FirstChild != null) { WriteResult(null, targetChild, DiffType.TargetExtra); tempFlag = false; } // Writing out End Element to the result bool bSourceNonEmpElemEnd = (sourceChild.NodeType == XmlDiffNodeType.Element && !(sourceChild is XmlDiffEmptyElement)); bool bTargetNonEmpElemEnd = (targetChild.NodeType == XmlDiffNodeType.Element && !(targetChild is XmlDiffEmptyElement)); if (bSourceNonEmpElemEnd || bTargetNonEmpElemEnd) { XmlDiffElement sourceElem = sourceChild as XmlDiffElement; XmlDiffElement targetElem = targetChild as XmlDiffElement; _Writer.WriteStartElement(String.Empty, "Node", String.Empty); _Writer.WriteAttributeString(String.Empty, "SourceLineNum", String.Empty, (sourceElem != null) ? sourceElem.EndLineNumber.ToString() : "-1"); _Writer.WriteAttributeString(String.Empty, "SourceLinePos", String.Empty, (sourceElem != null) ? sourceElem.EndLinePosition.ToString() : "-1"); _Writer.WriteAttributeString(String.Empty, "TargetLineNum", String.Empty, (targetElem != null) ? targetElem.EndLineNumber.ToString() : "-1"); _Writer.WriteAttributeString(String.Empty, "TargetLinePos", String.Empty, (targetElem != null) ? targetElem.EndLineNumber.ToString() : "-1"); _Writer.WriteStartElement(String.Empty, "Diff", String.Empty); _Writer.WriteAttributeString(String.Empty, "DiffType", String.Empty, GetDiffType(result)); if (bSourceNonEmpElemEnd) { _Writer.WriteStartElement(String.Empty, "File1", String.Empty); _Writer.WriteCData("</" + sourceElem.Name + ">"); _Writer.WriteEndElement(); } if (bTargetNonEmpElemEnd) { _Writer.WriteStartElement(String.Empty, "File2", String.Empty); _Writer.WriteCData("</" + targetElem.Name + ">"); _Writer.WriteEndElement(); } _Writer.WriteEndElement(); _Writer.WriteStartElement(String.Empty, "Lexical-equal", String.Empty); _Writer.WriteEndElement(); _Writer.WriteEndElement(); } sourceChild = sourceChild.NextSibling; targetChild = targetChild.NextSibling; } flag = false; } } else { // SourceRead NOT NULL targetRead is NULL WriteResult(sourceChild, null, DiffType.SourceExtra); flag = false; sourceChild = sourceChild.NextSibling; } } else if (targetChild != null) { // SourceRead is NULL and targetRead is NOT NULL WriteResult(null, targetChild, DiffType.TargetExtra); flag = false; targetChild = targetChild.NextSibling; } else { //Both SourceRead and TargetRead is NULL Debug.Assert(false, "Impossible Situation for comparison"); } } return flag; } // This function compares the two nodes passed to it, depending upon the options set by the user. private DiffType CompareNodes(XmlDiffNode sourceNode, XmlDiffNode targetNode) { if (sourceNode.NodeType != targetNode.NodeType) { return DiffType.NodeType; } switch (sourceNode.NodeType) { case XmlDiffNodeType.Element: XmlDiffElement sourceElem = sourceNode as XmlDiffElement; XmlDiffElement targetElem = targetNode as XmlDiffElement; Debug.Assert(sourceElem != null); Debug.Assert(targetElem != null); if (!IgnoreNS) { if (sourceElem.NamespaceURI != targetElem.NamespaceURI) return DiffType.NS; } if (!IgnorePrefix) { if (sourceElem.Prefix != targetElem.Prefix) return DiffType.Prefix; } if (sourceElem.LocalName != targetElem.LocalName) return DiffType.Element; if (!IgnoreEmptyElement) { if ((sourceElem is XmlDiffEmptyElement) != (targetElem is XmlDiffEmptyElement)) return DiffType.Element; } if (!CompareAttributes(sourceElem, targetElem)) { return DiffType.Attribute; } break; case XmlDiffNodeType.Text: case XmlDiffNodeType.Comment: case XmlDiffNodeType.WS: XmlDiffCharacterData sourceText = sourceNode as XmlDiffCharacterData; XmlDiffCharacterData targetText = targetNode as XmlDiffCharacterData; Debug.Assert(sourceText != null); Debug.Assert(targetText != null); if (IgnoreWhitespace) { if (sourceText.Value.Trim() == targetText.Value.Trim()) return DiffType.Success; } else { if (sourceText.Value == targetText.Value) return DiffType.Success; } if (sourceText.NodeType == XmlDiffNodeType.Text || sourceText.NodeType == XmlDiffNodeType.WS)//should ws nodes also as text nodes??? return DiffType.Text; else if (sourceText.NodeType == XmlDiffNodeType.Comment) return DiffType.Comment; else if (sourceText.NodeType == XmlDiffNodeType.CData) return DiffType.CData; else return DiffType.None; case XmlDiffNodeType.PI: XmlDiffProcessingInstruction sourcePI = sourceNode as XmlDiffProcessingInstruction; XmlDiffProcessingInstruction targetPI = targetNode as XmlDiffProcessingInstruction; Debug.Assert(sourcePI != null); Debug.Assert(targetPI != null); if (sourcePI.Name != targetPI.Name || sourcePI.Value != targetPI.Value) return DiffType.PI; break; default: break; } return DiffType.Success; } // This function writes the result in XML format so that it can be used by other applications to display the diff private void WriteResult(XmlDiffNode sourceNode, XmlDiffNode targetNode, DiffType result) { _Writer.WriteStartElement(String.Empty, "Node", String.Empty); _Writer.WriteAttributeString(String.Empty, "SourceLineNum", String.Empty, (sourceNode != null) ? sourceNode.LineNumber.ToString() : "-1"); _Writer.WriteAttributeString(String.Empty, "SourceLinePos", String.Empty, (sourceNode != null) ? sourceNode.LinePosition.ToString() : "-1"); _Writer.WriteAttributeString(String.Empty, "TargetLineNum", String.Empty, (targetNode != null) ? targetNode.LineNumber.ToString() : "-1"); _Writer.WriteAttributeString(String.Empty, "TargetLinePos", String.Empty, (targetNode != null) ? targetNode.LinePosition.ToString() : "-1"); if (result == DiffType.Success) { _Writer.WriteStartElement(String.Empty, "Diff", String.Empty); _Writer.WriteEndElement(); _Writer.WriteStartElement(String.Empty, "Lexical-equal", String.Empty); if (sourceNode.NodeType == XmlDiffNodeType.CData) { _Writer.WriteString("<![CDATA["); _Writer.WriteCData(GetNodeText(sourceNode, result)); _Writer.WriteString("]]>"); } else { _Writer.WriteCData(GetNodeText(sourceNode, result)); } _Writer.WriteEndElement(); } else { _Writer.WriteStartElement(String.Empty, "Diff", String.Empty); _Writer.WriteAttributeString(String.Empty, "DiffType", String.Empty, GetDiffType(result)); if (sourceNode != null) { _Writer.WriteStartElement(String.Empty, "File1", String.Empty); if (sourceNode.NodeType == XmlDiffNodeType.CData) { _Writer.WriteString("<![CDATA["); _Writer.WriteCData(GetNodeText(sourceNode, result)); _Writer.WriteString("]]>"); } else { _Writer.WriteString(GetNodeText(sourceNode, result)); } _Writer.WriteEndElement(); } if (targetNode != null) { _Writer.WriteStartElement(String.Empty, "File2", String.Empty); if (targetNode.NodeType == XmlDiffNodeType.CData) { _Writer.WriteString("<![CDATA["); _Writer.WriteCData(GetNodeText(targetNode, result)); _Writer.WriteString("]]>"); } else { _Writer.WriteString(GetNodeText(targetNode, result)); } _Writer.WriteEndElement(); } _Writer.WriteEndElement(); _Writer.WriteStartElement(String.Empty, "Lexical-equal", String.Empty); _Writer.WriteEndElement(); } _Writer.WriteEndElement(); } // This is a helper function for WriteResult. It gets the Xml representation of the different node we wants // to write out and all it's children. private String GetNodeText(XmlDiffNode diffNode, DiffType result) { string text = string.Empty; switch (diffNode.NodeType) { case XmlDiffNodeType.Element: if (result == DiffType.SourceExtra || result == DiffType.TargetExtra) return diffNode.OuterXml; StringWriter str = new StringWriter(); XmlWriter writer = XmlWriter.Create(str); XmlDiffElement diffElem = diffNode as XmlDiffElement; Debug.Assert(diffNode != null); writer.WriteStartElement(diffElem.Prefix, diffElem.LocalName, diffElem.NamespaceURI); XmlDiffAttribute diffAttr = diffElem.FirstAttribute; while (diffAttr != null) { writer.WriteAttributeString(diffAttr.Prefix, diffAttr.LocalName, diffAttr.NamespaceURI, diffAttr.Value); diffAttr = (XmlDiffAttribute)diffAttr.NextSibling; } if (diffElem is XmlDiffEmptyElement) { writer.WriteEndElement(); text = str.ToString(); } else { text = str.ToString(); text += ">"; } writer.Dispose(); break; case XmlDiffNodeType.CData: text = ((XmlDiffCharacterData)diffNode).Value; break; default: text = diffNode.OuterXml; break; } return text; } // This function is used to compare the attributes of an element node according to the options set by the user. private bool CompareAttributes(XmlDiffElement sourceElem, XmlDiffElement targetElem) { Debug.Assert(sourceElem != null); Debug.Assert(targetElem != null); if (sourceElem.AttributeCount != targetElem.AttributeCount) return false; if (sourceElem.AttributeCount == 0) return true; XmlDiffAttribute sourceAttr = sourceElem.FirstAttribute; XmlDiffAttribute targetAttr = targetElem.FirstAttribute; while (sourceAttr != null && targetAttr != null) { if (!IgnoreNS) { if (sourceAttr.NamespaceURI != targetAttr.NamespaceURI) return false; } if (!IgnorePrefix) { if (sourceAttr.Prefix != targetAttr.Prefix) return false; } if (sourceAttr.LocalName != targetAttr.LocalName || sourceAttr.Value != targetAttr.Value) return false; sourceAttr = (XmlDiffAttribute)(sourceAttr.NextSibling); targetAttr = (XmlDiffAttribute)(targetAttr.NextSibling); } return true; } public string ToXml() { if (_Output != null) return _Output.ToString(); return string.Empty; } public void ToXml(Stream stream) { StreamWriter writer = new StreamWriter(stream); writer.Write("<?xml-stylesheet type='text/xsl' href='diff.xsl'?>"); writer.Write(ToXml()); writer.Dispose(); } private String GetDiffType(DiffType type) { switch (type) { case DiffType.None: return String.Empty; case DiffType.Element: return "1"; case DiffType.Whitespace: return "2"; case DiffType.Comment: return "3"; case DiffType.PI: return "4"; case DiffType.Text: return "5"; case DiffType.Attribute: return "6"; case DiffType.NS: return "7"; case DiffType.Prefix: return "8"; case DiffType.SourceExtra: return "9"; case DiffType.TargetExtra: return "10"; case DiffType.NodeType: return "11"; case DiffType.CData: return "12"; default: return String.Empty; } } } }
using Lucene.Net.Support; using NUnit.Framework; using System; using System.Text; 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. */ [TestFixture] public class TestCharsRef : LuceneTestCase { [Test] public virtual void TestUTF16InUTF8Order() { int numStrings = AtLeast(1000); BytesRef[] utf8 = new BytesRef[numStrings]; CharsRef[] utf16 = new CharsRef[numStrings]; for (int i = 0; i < numStrings; i++) { string s = TestUtil.RandomUnicodeString(Random()); utf8[i] = new BytesRef(s); utf16[i] = new CharsRef(s); } Array.Sort(utf8); Array.Sort(utf16, CharsRef.UTF16SortedAsUTF8Comparer); for (int i = 0; i < numStrings; i++) { Assert.AreEqual(utf8[i].Utf8ToString(), utf16[i].ToString()); } } [Test] public virtual void TestAppend() { CharsRef @ref = new CharsRef(); StringBuilder builder = new StringBuilder(); int numStrings = AtLeast(10); for (int i = 0; i < numStrings; i++) { char[] charArray = TestUtil.RandomRealisticUnicodeString(Random(), 1, 100).ToCharArray(); int offset = Random().Next(charArray.Length); int length = charArray.Length - offset; builder.Append(charArray, offset, length); @ref.Append(charArray, offset, length); } Assert.AreEqual(builder.ToString(), @ref.ToString()); } [Test] public virtual void TestCopy() { int numIters = AtLeast(10); for (int i = 0; i < numIters; i++) { CharsRef @ref = new CharsRef(); char[] charArray = TestUtil.RandomRealisticUnicodeString(Random(), 1, 100).ToCharArray(); int offset = Random().Next(charArray.Length); int length = charArray.Length - offset; string str = new string(charArray, offset, length); @ref.CopyChars(charArray, offset, length); Assert.AreEqual(str, @ref.ToString()); } } // LUCENE-3590, AIOOBE if you append to a charsref with offset != 0 [Test] public virtual void TestAppendChars() { char[] chars = new char[] { 'a', 'b', 'c', 'd' }; CharsRef c = new CharsRef(chars, 1, 3); // bcd c.Append(new char[] { 'e' }, 0, 1); Assert.AreEqual("bcde", c.ToString()); } // LUCENE-3590, AIOOBE if you copy to a charsref with offset != 0 [Test] public virtual void TestCopyChars() { char[] chars = new char[] { 'a', 'b', 'c', 'd' }; CharsRef c = new CharsRef(chars, 1, 3); // bcd char[] otherchars = new char[] { 'b', 'c', 'd', 'e' }; c.CopyChars(otherchars, 0, 4); Assert.AreEqual("bcde", c.ToString()); } // LUCENE-3590, AIOOBE if you copy to a charsref with offset != 0 [Test] public virtual void TestCopyCharsRef() { char[] chars = new char[] { 'a', 'b', 'c', 'd' }; CharsRef c = new CharsRef(chars, 1, 3); // bcd char[] otherchars = new char[] { 'b', 'c', 'd', 'e' }; c.CopyChars(new CharsRef(otherchars, 0, 4)); Assert.AreEqual("bcde", c.ToString()); } // LUCENE-3590: fix charsequence to fully obey interface [Test] public virtual void TestCharSequenceCharAt() { CharsRef c = new CharsRef("abc"); Assert.AreEqual('b', c.CharAt(1)); try { c.CharAt(-1); Assert.Fail(); } catch (System.IndexOutOfRangeException expected) { // expected exception } try { c.CharAt(3); Assert.Fail(); } catch (System.IndexOutOfRangeException expected) { // expected exception } } // LUCENE-3590: fix off-by-one in subsequence, and fully obey interface // LUCENE-4671: fix subSequence [Test] public virtual void TestCharSequenceSubSequence() { ICharSequence[] sequences = { new CharsRef("abc"), new CharsRef("0abc".ToCharArray(), 1, 3), new CharsRef("abc0".ToCharArray(), 0, 3), new CharsRef("0abc0".ToCharArray(), 1, 3) }; foreach (ICharSequence c in sequences) { DoTestSequence(c); } } private void DoTestSequence(ICharSequence c) { // slice Assert.AreEqual("a", c.SubSequence(0, 1).ToString()); // mid subsequence Assert.AreEqual("b", c.SubSequence(1, 2).ToString()); // end subsequence Assert.AreEqual("bc", c.SubSequence(1, 3).ToString()); // empty subsequence Assert.AreEqual("", c.SubSequence(0, 0).ToString()); try { c.SubSequence(-1, 1); Assert.Fail(); } catch (System.IndexOutOfRangeException expected) { // expected exception } try { c.SubSequence(0, -1); Assert.Fail(); } catch (System.IndexOutOfRangeException expected) { // expected exception } try { c.SubSequence(0, 4); Assert.Fail(); } catch (System.IndexOutOfRangeException expected) { // expected exception } try { c.SubSequence(2, 1); Assert.Fail(); } catch (System.IndexOutOfRangeException expected) { // expected exception } } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * 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 OpenSim 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 System.Collections.Generic; using log4net; using MySql.Data.MySqlClient; using OpenMetaverse; using OpenSim.Framework; namespace OpenSim.Data.MySQL { /// <summary> /// A MySQL Interface for the Asset Server /// </summary> public class MySQLAssetData : AssetDataBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private MySQLManager _dbConnection; private long TicksToEpoch; #region IPlugin Members /// <summary> /// <para>Initialises Asset interface</para> /// <para> /// <list type="bullet"> /// <item>Loads and initialises the MySQL storage plugin.</item> /// <item>Warns and uses the obsolete mysql_connection.ini if connect string is empty.</item> /// <item>Check for migration</item> /// </list> /// </para> /// </summary> /// <param name="connect">connect string</param> override public void Initialise(string connect) { TicksToEpoch = new DateTime(1970,1,1).Ticks; // TODO: This will let you pass in the connect string in // the config, though someone will need to write that. if (connect == String.Empty) { // This is old seperate config file m_log.Warn("no connect string, using old mysql_connection.ini instead"); Initialise(); } else { _dbConnection = new MySQLManager(connect); } } /// <summary> /// <para>Initialises Asset interface</para> /// <para> /// <list type="bullet"> /// <item>Loads and initialises the MySQL storage plugin</item> /// <item>uses the obsolete mysql_connection.ini</item> /// </list> /// </para> /// </summary> /// <remarks>DEPRECATED and shouldn't be used</remarks> public override void Initialise() { IniFile GridDataMySqlFile = new IniFile("mysql_connection.ini"); string hostname = GridDataMySqlFile.ParseFileReadValue("hostname"); string database = GridDataMySqlFile.ParseFileReadValue("database"); string username = GridDataMySqlFile.ParseFileReadValue("username"); string password = GridDataMySqlFile.ParseFileReadValue("password"); string pooling = GridDataMySqlFile.ParseFileReadValue("pooling"); string port = GridDataMySqlFile.ParseFileReadValue("port"); _dbConnection = new MySQLManager(hostname, database, username, password, pooling, port); } public override void Dispose() { } /// <summary> /// Database provider version /// </summary> override public string Version { get { return _dbConnection.getVersion(); } } /// <summary> /// The name of this DB provider /// </summary> override public string Name { get { return "MySQL Asset storage engine"; } } #endregion #region IAssetDataPlugin Members /// <summary> /// Fetch Asset <paramref name="assetID"/> from database /// </summary> /// <param name="assetID">Asset UUID to fetch</param> /// <returns>Return the asset</returns> /// <remarks>On failure : throw an exception and attempt to reconnect to database</remarks> override protected AssetBase FetchStoredAsset(UUID assetID) { AssetBase asset = null; lock (_dbConnection) { _dbConnection.CheckConnection(); MySqlCommand cmd = new MySqlCommand( "SELECT name, description, assetType, local, temporary, data FROM assets WHERE id=?id", _dbConnection.Connection); cmd.Parameters.AddWithValue("?id", assetID.ToString()); try { using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (dbReader.Read()) { asset = new AssetBase(); asset.Data = (byte[]) dbReader["data"]; asset.Description = (string) dbReader["description"]; asset.FullID = assetID; try { asset.Local = (bool)dbReader["local"]; } catch (InvalidCastException) { asset.Local = false; } asset.Name = (string) dbReader["name"]; asset.Type = (sbyte) dbReader["assetType"]; } dbReader.Close(); cmd.Dispose(); } if (asset != null) UpdateAccessTime(asset); } catch (Exception e) { m_log.ErrorFormat( "[ASSETS DB]: MySql failure fetching asset {0}" + Environment.NewLine + e.ToString() + Environment.NewLine + "Reconnecting", assetID); _dbConnection.Reconnect(); } } return asset; } /// <summary> /// Create an asset in database, or update it if existing. /// </summary> /// <param name="asset">Asset UUID to create</param> /// <remarks>On failure : Throw an exception and attempt to reconnect to database</remarks> override public void CreateAsset(AssetBase asset) { lock (_dbConnection) { //m_log.Info("[ASSET DB]: Creating Asset " + asset.FullID); if (ExistsAsset(asset.FullID)) { //m_log.Info("[ASSET DB]: Asset exists already, ignoring."); return; } _dbConnection.CheckConnection(); MySqlCommand cmd = new MySqlCommand( "insert INTO assets(id, name, description, assetType, local, temporary, create_time, access_time, data)" + "VALUES(?id, ?name, ?description, ?assetType, ?local, ?temporary, ?create_time, ?access_time, ?data)", _dbConnection.Connection); // need to ensure we dispose try { using (cmd) { // create unix epoch time int now = (int)((DateTime.Now.Ticks - TicksToEpoch) / 10000000); cmd.Parameters.AddWithValue("?id", asset.ID); cmd.Parameters.AddWithValue("?name", asset.Name); cmd.Parameters.AddWithValue("?description", asset.Description); cmd.Parameters.AddWithValue("?assetType", asset.Type); cmd.Parameters.AddWithValue("?local", asset.Local); cmd.Parameters.AddWithValue("?temporary", asset.Temporary); cmd.Parameters.AddWithValue("?create_time", now); cmd.Parameters.AddWithValue("?access_time", now); cmd.Parameters.AddWithValue("?data", asset.Data); cmd.ExecuteNonQuery(); cmd.Dispose(); } } catch (Exception e) { m_log.ErrorFormat( "[ASSETS DB]: " + "MySql failure creating asset {0} with name {1}" + Environment.NewLine + e.ToString() + Environment.NewLine + "Attempting reconnection", asset.FullID, asset.Name); _dbConnection.Reconnect(); } } } private void UpdateAccessTime(AssetBase asset) { lock (_dbConnection) { _dbConnection.CheckConnection(); MySqlCommand cmd = new MySqlCommand("update assets set access_time=?access_time where id=?id", _dbConnection.Connection); // need to ensure we dispose try { using (cmd) { // create unix epoch time int now = (int)((DateTime.Now.Ticks - TicksToEpoch) / 10000000); cmd.Parameters.AddWithValue("?id", asset.ID); cmd.Parameters.AddWithValue("?access_time", now); cmd.ExecuteNonQuery(); cmd.Dispose(); } } catch (Exception e) { m_log.ErrorFormat( "[ASSETS DB]: " + "MySql failure updating access_time for asset {0} with name {1}" + Environment.NewLine + e.ToString() + Environment.NewLine + "Attempting reconnection", asset.FullID, asset.Name); _dbConnection.Reconnect(); } } } /// <summary> /// Update a asset in database, see <see cref="CreateAsset"/> /// </summary> /// <param name="asset">Asset UUID to update</param> override public void UpdateAsset(AssetBase asset) { CreateAsset(asset); } /// <summary> /// check if the asset UUID exist in database /// </summary> /// <param name="uuid">The asset UUID</param> /// <returns>true if exist.</returns> override public bool ExistsAsset(UUID uuid) { bool assetExists = false; lock (_dbConnection) { _dbConnection.CheckConnection(); MySqlCommand cmd = new MySqlCommand( "SELECT id FROM assets WHERE id=?id", _dbConnection.Connection); cmd.Parameters.AddWithValue("?id", uuid.ToString()); try { using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (dbReader.Read()) { assetExists = true; } dbReader.Close(); cmd.Dispose(); } } catch (Exception e) { m_log.ErrorFormat( "[ASSETS DB]: MySql failure fetching asset {0}" + Environment.NewLine + e.ToString() + Environment.NewLine + "Attempting reconnection", uuid); _dbConnection.Reconnect(); } } return assetExists; } /// <summary> /// Returns a list of AssetMetadata objects. The list is a subset of /// the entire data set offset by <paramref name="start" /> containing /// <paramref name="count" /> elements. /// </summary> /// <param name="start">The number of results to discard from the total data set.</param> /// <param name="count">The number of rows the returned list should contain.</param> /// <returns>A list of AssetMetadata objects.</returns> public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count) { List<AssetMetadata> retList = new List<AssetMetadata>(count); lock (_dbConnection) { _dbConnection.CheckConnection(); MySqlCommand cmd = new MySqlCommand("SELECT name,description,assetType,temporary,id FROM assets LIMIT ?start, ?count", _dbConnection.Connection); cmd.Parameters.AddWithValue("?start", start); cmd.Parameters.AddWithValue("?count", count); try { using (MySqlDataReader dbReader = cmd.ExecuteReader()) { while (dbReader.Read()) { AssetMetadata metadata = new AssetMetadata(); metadata.Name = (string) dbReader["name"]; metadata.Description = (string) dbReader["description"]; metadata.Type = (sbyte) dbReader["assetType"]; metadata.Temporary = (bool) dbReader["temporary"]; // Not sure if this is correct. metadata.FullID = new UUID(Convert.ToString(dbReader["id"])); // Current SHA1s are not stored/computed. metadata.SHA1 = new byte[] {}; retList.Add(metadata); } } } catch (Exception e) { m_log.Error("[ASSETS DB]: MySql failure fetching asset set" + Environment.NewLine + e.ToString() + Environment.NewLine + "Attempting reconnection"); _dbConnection.Reconnect(); } } return retList; } #endregion } }
/* * Copyright (c) 2014 All Rights Reserved by the SDL Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management.Automation; using Trisoft.ISHRemote.Objects; using Trisoft.ISHRemote.Objects.Public; using Trisoft.ISHRemote.Exceptions; using Trisoft.ISHRemote.HelperClasses; namespace Trisoft.ISHRemote.Cmdlets.PublicationOutput { /// <summary> /// <para type="synopsis">The Add-IshPublicationOutput cmdlet add the new publication outputs that are passed through the pipeline or determined via provided parameters</para> /// <para type="description">The Add-IshPublicationOutput cmdlet add the new publication outputs that are passed through the pipeline or determined via provided parameters</para> /// </summary> /// <example> /// <code> /// $ishSession = New-IshSession -WsBaseUrl "https://example.com/InfoShareWS/" -IshUserName "username" -IshUserPassword "userpassword" /// $metaDataCreate = Set-IshMetadataField -IshSession $ishSession -Name 'FISHFALLBACKLNGDEFAULT' -Level 'lng' -Value 'en' | /// Set-IshMetadataField -IshSession $ishSession -Name 'FISHFALLBACKLNGIMAGES' -Level 'lng' -Value 'en' | /// Set-IshMetadataField -IshSession $ishSession -Name 'FISHFALLBACKLNGRESOURCES' -Level 'lng' -Value 'en' /// Add-IshPublicationOutput -IshSession $ishSession ` /// -LogicalId "GUID-7EB6F836-A801-4DB3-A54A-22C207BAF671" ` /// -Version "1" ` /// -OutputFormat "GUID-2A69335D-F025-4963-A142-5E49988C7C0C" ` /// -LanguageCombination "en" ` /// -Metadata $metaDataCreate /// </code> /// <para>Creating a new publication output. New-IshSession will submit into SessionState, so it can be reused by this cmdlet.</para> /// </example> [Cmdlet(VerbsCommon.Add, "IshPublicationOutput", SupportsShouldProcess = true)] [OutputType(typeof(IshPublicationOutput))] public sealed class AddIshPublicationOutput : PublicationOutputCmdlet { /// <summary> /// <para type="description">The IshSession variable holds the authentication and contract information. This object can be initialized using the New-IshSession cmdlet.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectsGroup")] [ValidateNotNullOrEmpty] public IshSession IshSession { get; set; } /// <summary> /// <para type="description">The <see cref="Objects.Public.IshObject"/>s that need to be added.</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = "IshObjectsGroup")] [AllowEmptyCollection] public IshObject[] IshObject { get; set; } /// <summary> /// <para type="description">The FolderId for the PublicationOutput object.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectsGroup")] [ValidateNotNullOrEmpty] public long FolderId { get { return _folderId; } set { _folderId = value; } } /// <summary> /// <para type="description">The FolderId of the PublicationOutput by IshFolder object</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectsGroup")] [ValidateNotNull] public IshFolder IshFolder { private get { return null; } // required otherwise XmlDoc2CmdletDoc crashes with 'System.ArgumentException: Property Get method was not found.' set { _folderId = value.IshFolderRef; } } /// <summary> /// <para type="description">The LogicalId of the Publication.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup"), ValidateNotNullOrEmpty] public string LogicalId { get { return _logicalId; } set { _logicalId = value; } } /// <summary> /// <para type="description">The Version of the Publication.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup"), ValidateNotNull] public string Version { get { return _version; } set { _version = value; } } /// <summary> /// <para type="description">The requested OutputFormat for the new PublicationOutput.</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup"), ValidateNotNull] public string OutputFormat { get; set; } /// <summary> /// <para type="description">The requested language combination for the new PublicationOutput.</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup"), ValidateNotNull] public string LanguageCombination { get; set; } /// <summary> /// <para type="description">The metadata for the new PublicationOutput.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup"), ValidateNotNull] public IshField[] Metadata { get; set; } #region Private fields /// <summary> /// Logical Id will be defaulted to typical GUID-XYZ in uppercase /// </summary> private string _logicalId = ("GUID-" + Guid.NewGuid()).ToUpper(); /// <summary> /// Version will be defaulted to NEW, meaning that a first or next version will be created for existing objects /// </summary> private string _version = "NEW"; /// <summary> /// Holds the folder card id, specified by incoming parameter (long,IShObject) /// </summary> private long _folderId = -1; #endregion protected override void BeginProcessing() { if (IshSession == null) { IshSession = (IshSession)SessionState.PSVariable.GetValue(ISHRemoteSessionStateIshSession); } if (IshSession == null) { throw new ArgumentException(ISHRemoteSessionStateIshSessionException); } WriteDebug($"Using IshSession[{IshSession.Name}] from SessionState.{ISHRemoteSessionStateIshSession}"); base.BeginProcessing(); } /// <summary> /// Process the Add-IshPublicationOutput commandlet. /// </summary> /// <exception cref="TrisoftAutomationException"></exception> /// <exception cref="Exception"></exception> /// <remarks>Writes an <see cref="Objects.Public.IshObject"/> array to the pipeline.</remarks> protected override void ProcessRecord() { try { // validating the input List<IshObject> returnedObjects = new List<IshObject>(); WriteDebug("Adding"); if (IshObject != null) { // Using the pipeline int current = 0; IshObjects ishObjects = new IshObjects(IshObject); foreach (IshObject ishObject in ishObjects.Objects) { // Get values WriteDebug($"Id[{ishObject.IshRef}] {++current}/{IshObject.Length}"); string logicalId = ishObject.IshRef; //Remember that RetrieveFirst prefers id over element over value ishfields var versionMetadataField = ishObject.IshFields.RetrieveFirst("VERSION", Enumerations.Level.Version).ToMetadataField() as IshMetadataField; string version = versionMetadataField.Value; var outputFormatMetadataField = ishObject.IshFields.RetrieveFirst("FISHOUTPUTFORMATREF", Enumerations.Level.Lng).ToMetadataField() as IshMetadataField; string outputFormat = outputFormatMetadataField.Value; var languageCombinationMetadataField = ishObject.IshFields.RetrieveFirst("FISHPUBLNGCOMBINATION", Enumerations.Level.Lng).ToMetadataField() as IshMetadataField; string languageCombination = languageCombinationMetadataField.Value; var metadata = IshSession.IshTypeFieldSetup.ToIshMetadataFields(ISHType, ishObject.IshFields, Enumerations.ActionMode.Create); PublicationOutput25ServiceReference.CreateResponse response = null; if (ShouldProcess(logicalId + "=" + version + "=" + languageCombination + "=" + outputFormat)) { response = IshSession.PublicationOutput25.Create(new PublicationOutput25ServiceReference. CreateRequest( _folderId, logicalId, version, outputFormat, languageCombination, metadata.ToXml())); } IshFields requestedMetadata = IshSession.IshTypeFieldSetup.ToIshRequestedMetadataFields(IshSession.DefaultRequestedMetadata, ISHType, metadata, Enumerations.ActionMode.Read); var response2 = IshSession.PublicationOutput25.GetMetadata(new PublicationOutput25ServiceReference. GetMetadataRequest( response.logicalId, response.version, outputFormat, languageCombination, requestedMetadata.ToXml())); string xmlIshObjects = response2.xmlObjectList; IshObjects retrievedObjects = new IshObjects(ISHType, xmlIshObjects); returnedObjects.AddRange(retrievedObjects.Objects); } } else { var metadata = IshSession.IshTypeFieldSetup.ToIshMetadataFields(ISHType, new IshFields(Metadata), Enumerations.ActionMode.Create); PublicationOutput25ServiceReference.CreateResponse response = null; if (ShouldProcess(LogicalId + "=" + Version + "=" + LanguageCombination + "=" + OutputFormat)) { response = IshSession.PublicationOutput25.Create(new PublicationOutput25ServiceReference. CreateRequest( _folderId, LogicalId, Version, OutputFormat, LanguageCombination, metadata.ToXml())); } IshFields requestedMetadata = IshSession.IshTypeFieldSetup.ToIshRequestedMetadataFields(IshSession.DefaultRequestedMetadata, ISHType, metadata, Enumerations.ActionMode.Read); var response2 = IshSession.PublicationOutput25.GetMetadata(new PublicationOutput25ServiceReference. GetMetadataRequest( response.logicalId, response.version, OutputFormat, LanguageCombination, requestedMetadata.ToXml())); string xmlIshObjects = response2.xmlObjectList; IshObjects retrievedObjects = new IshObjects(ISHType, xmlIshObjects); returnedObjects.AddRange(retrievedObjects.Objects); } // Write objects to the pipeline WriteVerbose("returned object count[" + returnedObjects.Count + "]"); WriteObject(IshSession, ISHType, returnedObjects.ConvertAll(x => (IshBaseObject)x), true); } catch (TrisoftAutomationException trisoftAutomationException) { ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null)); } catch (Exception exception) { ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null)); } } } }
// Zlib.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2009-November-07 05:26:55> // // ------------------------------------------------------------------ // // This module defines classes for ZLIB compression and // decompression. This code is derived from the jzlib implementation of // zlib, but significantly modified. The object model is not the same, // and many of the behaviors are new or different. Nonetheless, in // keeping with the license for jzlib, the copyright to that code is // included below. // // ------------------------------------------------------------------ // // Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,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. // // 3. The names of the authors may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, // INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. // // ----------------------------------------------------------------------- // // This program is based on zlib-1.1.3; credit to authors // Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) // and contributors of zlib. // // ----------------------------------------------------------------------- using System; using System.IO; namespace SharpCompress.Compressors.Deflate { /// <summary> /// The compression level to be used when using a DeflateStream or ZlibStream with CompressionMode.Compress. /// </summary> public enum CompressionLevel { /// <summary> /// None means that the data will be simply stored, with no change at all. /// If you are producing ZIPs for use on Mac OSX, be aware that archives produced with CompressionLevel.None /// cannot be opened with the default zip reader. Use a different CompressionLevel. /// </summary> None = 0, /// <summary> /// Same as None. /// </summary> Level0 = 0, /// <summary> /// The fastest but least effective compression. /// </summary> BestSpeed = 1, /// <summary> /// A synonym for BestSpeed. /// </summary> Level1 = 1, /// <summary> /// A little slower, but better, than level 1. /// </summary> Level2 = 2, /// <summary> /// A little slower, but better, than level 2. /// </summary> Level3 = 3, /// <summary> /// A little slower, but better, than level 3. /// </summary> Level4 = 4, /// <summary> /// A little slower than level 4, but with better compression. /// </summary> Level5 = 5, /// <summary> /// The default compression level, with a good balance of speed and compression efficiency. /// </summary> Default = 6, /// <summary> /// A synonym for Default. /// </summary> Level6 = 6, /// <summary> /// Pretty good compression! /// </summary> Level7 = 7, /// <summary> /// Better compression than Level7! /// </summary> Level8 = 8, /// <summary> /// The "best" compression, where best means greatest reduction in size of the input data stream. /// This is also the slowest compression. /// </summary> BestCompression = 9, /// <summary> /// A synonym for BestCompression. /// </summary> Level9 = 9 } /// <summary> /// Describes options for how the compression algorithm is executed. Different strategies /// work better on different sorts of data. The strategy parameter can affect the compression /// ratio and the speed of compression but not the correctness of the compresssion. /// </summary> public enum CompressionStrategy { /// <summary> /// The default strategy is probably the best for normal data. /// </summary> Default = 0, /// <summary> /// The <c>Filtered</c> strategy is intended to be used most effectively with data produced by a /// filter or predictor. By this definition, filtered data consists mostly of small /// values with a somewhat random distribution. In this case, the compression algorithm /// is tuned to compress them better. The effect of <c>Filtered</c> is to force more Huffman /// coding and less string matching; it is a half-step between <c>Default</c> and <c>HuffmanOnly</c>. /// </summary> Filtered = 1, /// <summary> /// Using <c>HuffmanOnly</c> will force the compressor to do Huffman encoding only, with no /// string matching. /// </summary> HuffmanOnly = 2 } /// <summary> /// A general purpose exception class for exceptions in the Zlib library. /// </summary> public class ZlibException : Exception { /// <summary> /// The ZlibException class captures exception information generated /// by the Zlib library. /// </summary> public ZlibException() { } /// <summary> /// This ctor collects a message attached to the exception. /// </summary> /// <param name="s"></param> public ZlibException(String s) : base(s) { } } internal class SharedUtils { /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static int URShift(int number, int bits) { return (int)((uint)number >> bits); } #if NOT /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static long URShift(long number, int bits) { return (long) ((UInt64)number >> bits); } #endif /// <summary> /// Reads a number of characters from the current source TextReader and writes /// the data to the target array at the specified index. /// </summary> /// /// <param name="sourceTextReader">The source TextReader to read from</param> /// <param name="target">Contains the array of characteres read from the source TextReader.</param> /// <param name="start">The starting index of the target array.</param> /// <param name="count">The maximum number of characters to read from the source TextReader.</param> /// /// <returns> /// The number of characters read. The number will be less than or equal to /// count depending on the data available in the source TextReader. Returns -1 /// if the end of the stream is reached. /// </returns> public static Int32 ReadInput(TextReader sourceTextReader, byte[] target, int start, int count) { // Returns 0 bytes if not enough space in target if (target.Length == 0) { return 0; } char[] charArray = new char[target.Length]; int bytesRead = sourceTextReader.Read(charArray, start, count); // Returns -1 if EOF if (bytesRead == 0) { return -1; } for (int index = start; index < start + bytesRead; index++) { target[index] = (byte)charArray[index]; } return bytesRead; } } internal static class InternalConstants { internal static readonly int MAX_BITS = 15; internal static readonly int BL_CODES = 19; internal static readonly int D_CODES = 30; internal static readonly int LITERALS = 256; internal static readonly int LENGTH_CODES = 29; internal static readonly int L_CODES = (LITERALS + 1 + LENGTH_CODES); // Bit length codes must not exceed MAX_BL_BITS bits internal static readonly int MAX_BL_BITS = 7; // repeat previous bit length 3-6 times (2 bits of repeat count) internal static readonly int REP_3_6 = 16; // repeat a zero length 3-10 times (3 bits of repeat count) internal static readonly int REPZ_3_10 = 17; // repeat a zero length 11-138 times (7 bits of repeat count) internal static readonly int REPZ_11_138 = 18; } internal sealed class StaticTree { internal static readonly short[] lengthAndLiteralsTreeCodes = { 12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8, 28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8, 2, 8, 130, 8, 66, 8, 194, 8, 34, 8, 162, 8 , 98, 8, 226, 8, 18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8, 10, 8, 138, 8, 74, 8, 202, 8, 42, 8, 170, 8, 106, 8, 234, 8, 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8, 6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8 , 102, 8, 230, 8, 22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8, 14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8, 30, 8, 158, 8, 94, 8, 222, 8, 62, 8, 190, 8, 126, 8, 254, 8, 1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8 , 97, 8, 225, 8, 17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113, 8, 241, 8, 9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8 , 105, 8, 233, 8, 25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8, 5, 8, 133, 8, 69, 8, 197, 8, 37, 8, 165, 8 , 101, 8, 229, 8, 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8, 13, 8, 141, 8, 77, 8, 205, 8, 45, 8, 173, 8, 109, 8, 237, 8, 29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8, 19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9, 51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371 , 9, 243, 9, 499, 9, 11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9, 43, 9, 299, 9, 171, 9, 427, 9, 107, 9, 363 , 9, 235, 9, 491, 9, 27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9, 59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379 , 9, 251, 9, 507, 9, 7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9, 39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359 , 9, 231, 9, 487, 9, 23, 9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9, 55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375 , 9, 247, 9, 503, 9, 15, 9, 271, 9, 143, 9, 399, 9, 79, 9, 335, 9, 207, 9, 463, 9, 47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367 , 9, 239, 9, 495, 9, 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9, 223, 9, 479, 9, 63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383 , 9, 255, 9, 511, 9, 0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7, 8, 7, 72, 7, 40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7, 4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7, 3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8 , 99, 8, 227, 8 }; internal static readonly short[] distTreeCodes = { 0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5, 2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5, 1, 5, 17, 5, 9, 5, 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 }; // extra bits for each bit length code internal static readonly int[] extra_blbits = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7 }; internal static readonly StaticTree Literals; internal static readonly StaticTree Distances; internal static readonly StaticTree BitLengths; internal short[]? treeCodes; // static tree or null internal int[]? extraBits; // extra bits for each code or null internal int extraBase; // base index for extra_bits internal int elems; // max number of elements in the tree internal int maxLength; // max bit length for the codes private StaticTree(short[]? treeCodes, int[]? extraBits, int extraBase, int elems, int maxLength) { this.treeCodes = treeCodes; this.extraBits = extraBits; this.extraBase = extraBase; this.elems = elems; this.maxLength = maxLength; } static StaticTree() { Literals = new StaticTree(lengthAndLiteralsTreeCodes, DeflateManager.ExtraLengthBits, InternalConstants.LITERALS + 1, InternalConstants.L_CODES, InternalConstants.MAX_BITS); Distances = new StaticTree(distTreeCodes, DeflateManager.ExtraDistanceBits, 0, InternalConstants.D_CODES, InternalConstants.MAX_BITS); BitLengths = new StaticTree(null, extra_blbits, 0, InternalConstants.BL_CODES, InternalConstants.MAX_BL_BITS); } } }
using System; using System.Linq; using System.Text.RegularExpressions; using GitVersion.Helpers; namespace GitVersion { public class SemanticVersionPreReleaseTag : IFormattable, IComparable<SemanticVersionPreReleaseTag>, IEquatable<SemanticVersionPreReleaseTag> { private static readonly LambdaEqualityHelper<SemanticVersionPreReleaseTag> EqualityHelper = new LambdaEqualityHelper<SemanticVersionPreReleaseTag>(x => x.Name, x => x.Number); public SemanticVersionPreReleaseTag() { } public SemanticVersionPreReleaseTag(string name, int? number) { Name = name; Number = number; } public SemanticVersionPreReleaseTag(SemanticVersionPreReleaseTag preReleaseTag) { Name = preReleaseTag.Name; Number = preReleaseTag.Number; PromotedFromCommits = preReleaseTag.PromotedFromCommits; } public string Name { get; set; } public int? Number { get; set; } public bool PromotedFromCommits { get; set; } public override bool Equals(object obj) { return Equals(obj as SemanticVersionPreReleaseTag); } public bool Equals(SemanticVersionPreReleaseTag other) { return EqualityHelper.Equals(this, other); } public override int GetHashCode() { return EqualityHelper.GetHashCode(this); } public static bool operator ==(SemanticVersionPreReleaseTag left, SemanticVersionPreReleaseTag right) { return Equals(left, right); } public static bool operator !=(SemanticVersionPreReleaseTag left, SemanticVersionPreReleaseTag right) { return !Equals(left, right); } public static bool operator >(SemanticVersionPreReleaseTag left, SemanticVersionPreReleaseTag right) { return left.CompareTo(right) > 0; } public static bool operator <(SemanticVersionPreReleaseTag left, SemanticVersionPreReleaseTag right) { return left.CompareTo(right) < 0; } public static bool operator >=(SemanticVersionPreReleaseTag left, SemanticVersionPreReleaseTag right) { return left.CompareTo(right) >= 0; } public static bool operator <=(SemanticVersionPreReleaseTag left, SemanticVersionPreReleaseTag right) { return StringComparerUtils.IgnoreCaseComparer.Compare(left.Name, right.Name) != 1; } public static implicit operator string(SemanticVersionPreReleaseTag preReleaseTag) { return preReleaseTag.ToString(); } public static implicit operator SemanticVersionPreReleaseTag(string preReleaseTag) { return Parse(preReleaseTag); } public static SemanticVersionPreReleaseTag Parse(string preReleaseTag) { if (string.IsNullOrEmpty(preReleaseTag)) { return new SemanticVersionPreReleaseTag(); } var match = Regex.Match(preReleaseTag, @"(?<name>.*?)\.?(?<number>\d+)?$"); if (!match.Success) { // TODO check how to log this Console.WriteLine($"Unable to successfully parse semver tag {preReleaseTag}"); return new SemanticVersionPreReleaseTag(); } var value = match.Groups["name"].Value; var number = match.Groups["number"].Success ? int.Parse(match.Groups["number"].Value) : (int?)null; if (value.EndsWith("-")) return new SemanticVersionPreReleaseTag(preReleaseTag, null); return new SemanticVersionPreReleaseTag(value, number); } public int CompareTo(SemanticVersionPreReleaseTag other) { if (!HasTag() && other.HasTag()) { return 1; } if (HasTag() && !other.HasTag()) { return -1; } var nameComparison = StringComparerUtils.IgnoreCaseComparer.Compare(Name, other.Name); if (nameComparison != 0) return nameComparison; return Nullable.Compare(Number, other.Number); } public override string ToString() { return ToString(null); } /// <summary> /// Default formats: /// <para>t - SemVer 2.0 formatted tag [beta.1]</para> /// <para>l - Legacy SemVer tag with the tag number padded. [beta1]</para> /// <para>lp - Legacy SemVer tag with the tag number padded. [beta0001]. Can specify an integer to control padding (i.e., lp5)</para> /// </summary> public string ToString(string format, IFormatProvider formatProvider = null) { if (formatProvider != null) { if (formatProvider.GetFormat(GetType()) is ICustomFormatter formatter) return formatter.Format(format, this, formatProvider); } if (string.IsNullOrEmpty(format)) format = "t"; format = format.ToLower(); if (format.StartsWith("lp", StringComparison.Ordinal)) { // Handle format var padding = 4; if (format.Length > 2) { // try to parse if (int.TryParse(format.Substring(2), out var p)) { padding = p; } } return Number.HasValue ? FormatLegacy(GetLegacyName(), Number.Value.ToString("D" + padding)) : FormatLegacy(GetLegacyName()); } return format switch { "t" => (Number.HasValue ? string.IsNullOrEmpty(Name) ? $"{Number}" : $"{Name}.{Number}" : Name), "l" => (Number.HasValue ? FormatLegacy(GetLegacyName(), Number.Value.ToString()) : FormatLegacy(GetLegacyName())), _ => throw new ArgumentException("Unknown format", nameof(format)) }; } private string FormatLegacy(string tag, string number = "") { var tagEndsWithANumber = char.IsNumber(tag.LastOrDefault()); if (tagEndsWithANumber && number.Length > 0) number = "-" + number; if (tag.Length + number.Length > 20) return $"{tag.Substring(0, 20 - number.Length)}{number}"; return $"{tag}{number}"; } private string GetLegacyName() { if (string.IsNullOrEmpty(Name)) { return string.Empty; } var firstPart = Name.Split('_')[0]; return firstPart.Replace(".", string.Empty); } public bool HasTag() { return !string.IsNullOrEmpty(Name) || (Number.HasValue && !PromotedFromCommits); } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// SMS Reply Recipients Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SP_RECIPDataSet : EduHubDataSet<SP_RECIP> { /// <inheritdoc /> public override string Name { get { return "SP_RECIP"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal SP_RECIPDataSet(EduHubContext Context) : base(Context) { Index_CODE = new Lazy<Dictionary<string, IReadOnlyList<SP_RECIP>>>(() => this.ToGroupedDictionary(i => i.CODE)); Index_CODE_SFKEY = new Lazy<Dictionary<Tuple<string, string>, SP_RECIP>>(() => this.ToDictionary(i => Tuple.Create(i.CODE, i.SFKEY))); Index_SFKEY = new Lazy<NullDictionary<string, IReadOnlyList<SP_RECIP>>>(() => this.ToGroupedNullDictionary(i => i.SFKEY)); Index_TID = new Lazy<Dictionary<int, SP_RECIP>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="SP_RECIP" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="SP_RECIP" /> fields for each CSV column header</returns> internal override Action<SP_RECIP, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<SP_RECIP, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "CODE": mapper[i] = (e, v) => e.CODE = v; break; case "SFKEY": mapper[i] = (e, v) => e.SFKEY = v; break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="SP_RECIP" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="SP_RECIP" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="SP_RECIP" /> entities</param> /// <returns>A merged <see cref="IEnumerable{SP_RECIP}"/> of entities</returns> internal override IEnumerable<SP_RECIP> ApplyDeltaEntities(IEnumerable<SP_RECIP> Entities, List<SP_RECIP> DeltaEntities) { HashSet<Tuple<string, string>> Index_CODE_SFKEY = new HashSet<Tuple<string, string>>(DeltaEntities.Select(i => Tuple.Create(i.CODE, i.SFKEY))); HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.CODE; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = false; overwritten = overwritten || Index_CODE_SFKEY.Remove(Tuple.Create(entity.CODE, entity.SFKEY)); overwritten = overwritten || Index_TID.Remove(entity.TID); if (entity.CODE.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, IReadOnlyList<SP_RECIP>>> Index_CODE; private Lazy<Dictionary<Tuple<string, string>, SP_RECIP>> Index_CODE_SFKEY; private Lazy<NullDictionary<string, IReadOnlyList<SP_RECIP>>> Index_SFKEY; private Lazy<Dictionary<int, SP_RECIP>> Index_TID; #endregion #region Index Methods /// <summary> /// Find SP_RECIP by CODE field /// </summary> /// <param name="CODE">CODE value used to find SP_RECIP</param> /// <returns>List of related SP_RECIP entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SP_RECIP> FindByCODE(string CODE) { return Index_CODE.Value[CODE]; } /// <summary> /// Attempt to find SP_RECIP by CODE field /// </summary> /// <param name="CODE">CODE value used to find SP_RECIP</param> /// <param name="Value">List of related SP_RECIP entities</param> /// <returns>True if the list of related SP_RECIP entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByCODE(string CODE, out IReadOnlyList<SP_RECIP> Value) { return Index_CODE.Value.TryGetValue(CODE, out Value); } /// <summary> /// Attempt to find SP_RECIP by CODE field /// </summary> /// <param name="CODE">CODE value used to find SP_RECIP</param> /// <returns>List of related SP_RECIP entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SP_RECIP> TryFindByCODE(string CODE) { IReadOnlyList<SP_RECIP> value; if (Index_CODE.Value.TryGetValue(CODE, out value)) { return value; } else { return null; } } /// <summary> /// Find SP_RECIP by CODE and SFKEY fields /// </summary> /// <param name="CODE">CODE value used to find SP_RECIP</param> /// <param name="SFKEY">SFKEY value used to find SP_RECIP</param> /// <returns>Related SP_RECIP entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SP_RECIP FindByCODE_SFKEY(string CODE, string SFKEY) { return Index_CODE_SFKEY.Value[Tuple.Create(CODE, SFKEY)]; } /// <summary> /// Attempt to find SP_RECIP by CODE and SFKEY fields /// </summary> /// <param name="CODE">CODE value used to find SP_RECIP</param> /// <param name="SFKEY">SFKEY value used to find SP_RECIP</param> /// <param name="Value">Related SP_RECIP entity</param> /// <returns>True if the related SP_RECIP entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByCODE_SFKEY(string CODE, string SFKEY, out SP_RECIP Value) { return Index_CODE_SFKEY.Value.TryGetValue(Tuple.Create(CODE, SFKEY), out Value); } /// <summary> /// Attempt to find SP_RECIP by CODE and SFKEY fields /// </summary> /// <param name="CODE">CODE value used to find SP_RECIP</param> /// <param name="SFKEY">SFKEY value used to find SP_RECIP</param> /// <returns>Related SP_RECIP entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SP_RECIP TryFindByCODE_SFKEY(string CODE, string SFKEY) { SP_RECIP value; if (Index_CODE_SFKEY.Value.TryGetValue(Tuple.Create(CODE, SFKEY), out value)) { return value; } else { return null; } } /// <summary> /// Find SP_RECIP by SFKEY field /// </summary> /// <param name="SFKEY">SFKEY value used to find SP_RECIP</param> /// <returns>List of related SP_RECIP entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SP_RECIP> FindBySFKEY(string SFKEY) { return Index_SFKEY.Value[SFKEY]; } /// <summary> /// Attempt to find SP_RECIP by SFKEY field /// </summary> /// <param name="SFKEY">SFKEY value used to find SP_RECIP</param> /// <param name="Value">List of related SP_RECIP entities</param> /// <returns>True if the list of related SP_RECIP entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySFKEY(string SFKEY, out IReadOnlyList<SP_RECIP> Value) { return Index_SFKEY.Value.TryGetValue(SFKEY, out Value); } /// <summary> /// Attempt to find SP_RECIP by SFKEY field /// </summary> /// <param name="SFKEY">SFKEY value used to find SP_RECIP</param> /// <returns>List of related SP_RECIP entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SP_RECIP> TryFindBySFKEY(string SFKEY) { IReadOnlyList<SP_RECIP> value; if (Index_SFKEY.Value.TryGetValue(SFKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find SP_RECIP by TID field /// </summary> /// <param name="TID">TID value used to find SP_RECIP</param> /// <returns>Related SP_RECIP entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SP_RECIP FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find SP_RECIP by TID field /// </summary> /// <param name="TID">TID value used to find SP_RECIP</param> /// <param name="Value">Related SP_RECIP entity</param> /// <returns>True if the related SP_RECIP entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out SP_RECIP Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find SP_RECIP by TID field /// </summary> /// <param name="TID">TID value used to find SP_RECIP</param> /// <returns>Related SP_RECIP entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SP_RECIP TryFindByTID(int TID) { SP_RECIP value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a SP_RECIP table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SP_RECIP]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[SP_RECIP]( [TID] int IDENTITY NOT NULL, [CODE] varchar(15) NOT NULL, [SFKEY] varchar(4) NULL, [LW_TIME] smallint NULL, [LW_DATE] datetime NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [SP_RECIP_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE CLUSTERED INDEX [SP_RECIP_Index_CODE] ON [dbo].[SP_RECIP] ( [CODE] ASC ); CREATE NONCLUSTERED INDEX [SP_RECIP_Index_CODE_SFKEY] ON [dbo].[SP_RECIP] ( [CODE] ASC, [SFKEY] ASC ); CREATE NONCLUSTERED INDEX [SP_RECIP_Index_SFKEY] ON [dbo].[SP_RECIP] ( [SFKEY] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SP_RECIP]') AND name = N'SP_RECIP_Index_CODE_SFKEY') ALTER INDEX [SP_RECIP_Index_CODE_SFKEY] ON [dbo].[SP_RECIP] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SP_RECIP]') AND name = N'SP_RECIP_Index_SFKEY') ALTER INDEX [SP_RECIP_Index_SFKEY] ON [dbo].[SP_RECIP] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SP_RECIP]') AND name = N'SP_RECIP_Index_TID') ALTER INDEX [SP_RECIP_Index_TID] ON [dbo].[SP_RECIP] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SP_RECIP]') AND name = N'SP_RECIP_Index_CODE_SFKEY') ALTER INDEX [SP_RECIP_Index_CODE_SFKEY] ON [dbo].[SP_RECIP] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SP_RECIP]') AND name = N'SP_RECIP_Index_SFKEY') ALTER INDEX [SP_RECIP_Index_SFKEY] ON [dbo].[SP_RECIP] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SP_RECIP]') AND name = N'SP_RECIP_Index_TID') ALTER INDEX [SP_RECIP_Index_TID] ON [dbo].[SP_RECIP] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SP_RECIP"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="SP_RECIP"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SP_RECIP> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<Tuple<string, string>> Index_CODE_SFKEY = new List<Tuple<string, string>>(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_CODE_SFKEY.Add(Tuple.Create(entity.CODE, entity.SFKEY)); Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[SP_RECIP] WHERE"); // Index_CODE_SFKEY builder.Append("("); for (int index = 0; index < Index_CODE_SFKEY.Count; index++) { if (index != 0) builder.Append(" OR "); // CODE var parameterCODE = $"@p{parameterIndex++}"; builder.Append("([CODE]=").Append(parameterCODE); command.Parameters.Add(parameterCODE, SqlDbType.VarChar, 15).Value = Index_CODE_SFKEY[index].Item1; // SFKEY if (Index_CODE_SFKEY[index].Item2 == null) { builder.Append(" AND [SFKEY] IS NULL)"); } else { var parameterSFKEY = $"@p{parameterIndex++}"; builder.Append(" AND [SFKEY]=").Append(parameterSFKEY).Append(")"); command.Parameters.Add(parameterSFKEY, SqlDbType.VarChar, 4).Value = Index_CODE_SFKEY[index].Item2; } } builder.AppendLine(") OR"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the SP_RECIP data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SP_RECIP data set</returns> public override EduHubDataSetDataReader<SP_RECIP> GetDataSetDataReader() { return new SP_RECIPDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the SP_RECIP data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SP_RECIP data set</returns> public override EduHubDataSetDataReader<SP_RECIP> GetDataSetDataReader(List<SP_RECIP> Entities) { return new SP_RECIPDataReader(new EduHubDataSetLoadedReader<SP_RECIP>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class SP_RECIPDataReader : EduHubDataSetDataReader<SP_RECIP> { public SP_RECIPDataReader(IEduHubDataSetReader<SP_RECIP> Reader) : base (Reader) { } public override int FieldCount { get { return 6; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // CODE return Current.CODE; case 2: // SFKEY return Current.SFKEY; case 3: // LW_TIME return Current.LW_TIME; case 4: // LW_DATE return Current.LW_DATE; case 5: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // SFKEY return Current.SFKEY == null; case 3: // LW_TIME return Current.LW_TIME == null; case 4: // LW_DATE return Current.LW_DATE == null; case 5: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // CODE return "CODE"; case 2: // SFKEY return "SFKEY"; case 3: // LW_TIME return "LW_TIME"; case 4: // LW_DATE return "LW_DATE"; case 5: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "CODE": return 1; case "SFKEY": return 2; case "LW_TIME": return 3; case "LW_DATE": return 4; case "LW_USER": return 5; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute; using EditorBrowsableState = System.ComponentModel.EditorBrowsableState; using System.Diagnostics; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System { [DebuggerDisplay("{DebuggerDisplay,nq}")] [DebuggerTypeProxy(typeof(MemoryDebugView<>))] public struct Memory<T> { // NOTE: With the current implementation, Memory<T> and ReadOnlyMemory<T> must have the same layout, // as code uses Unsafe.As to cast between them. // The highest order bit of _index is used to discern whether _arrayOrOwnedMemory is an array or an owned memory // if (_index >> 31) == 1, object _arrayOrOwnedMemory is an OwnedMemory<T> // else, object _arrayOrOwnedMemory is a T[] private readonly object _arrayOrOwnedMemory; private readonly int _index; private readonly int _length; private const int RemoveOwnedFlagBitMask = 0x7FFFFFFF; /// <summary> /// Creates a new memory over the entirety of the target array. /// </summary> /// <param name="array">The target array.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[] array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); _arrayOrOwnedMemory = array; _index = 0; _length = array.Length; } /// <summary> /// Creates a new memory over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the memory.</param> /// <param name="length">The number of items in the memory.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[] array, int start, int length) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); _arrayOrOwnedMemory = array; _index = start; _length = length; } // Constructor for internal use only. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(OwnedMemory<T> owner, int index, int length) { if (owner == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.ownedMemory); if (index < 0 || length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(); _arrayOrOwnedMemory = owner; _index = index | (1 << 31); // Before using _index, check if _index < 0, then 'and' it with RemoveOwnedFlagBitMask _length = length; } /// <summary> /// Defines an implicit conversion of an array to a <see cref="Memory{T}"/> /// </summary> public static implicit operator Memory<T>(T[] array) => new Memory<T>(array); /// <summary> /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/> /// </summary> public static implicit operator Memory<T>(ArraySegment<T> arraySegment) => new Memory<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count); /// <summary> /// Defines an implicit conversion of a <see cref="Memory{T}"/> to a <see cref="ReadOnlyMemory{T}"/> /// </summary> public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) => Unsafe.As<Memory<T>, ReadOnlyMemory<T>>(ref memory); //Debugger Display = {T[length]} private string DebuggerDisplay => string.Format("{{{0}[{1}]}}", typeof(T).Name, _length); /// <summary> /// Returns an empty <see cref="Memory{T}"/> /// </summary> public static Memory<T> Empty { get; } = Array.Empty<T>(); /// <summary> /// The number of items in the memory. /// </summary> public int Length => _length; /// <summary> /// Returns true if Length is 0. /// </summary> public bool IsEmpty => _length == 0; /// <summary> /// Forms a slice out of the given memory, beginning at 'start'. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start) { if ((uint)start > (uint)_length) ThrowHelper.ThrowArgumentOutOfRangeException(); if (_index < 0) return new Memory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, _length - start); return new Memory<T>((T[])_arrayOrOwnedMemory, _index + start, _length - start); } /// <summary> /// Forms a slice out of the given memory, beginning at 'start', of given length /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); if (_index < 0) return new Memory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, length); return new Memory<T>((T[])_arrayOrOwnedMemory, _index + start, length); } /// <summary> /// Returns a span from the memory. /// </summary> public Span<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (_index < 0) return ((OwnedMemory<T>)_arrayOrOwnedMemory).Span.Slice(_index & RemoveOwnedFlagBitMask, _length); return new Span<T>((T[])_arrayOrOwnedMemory, _index, _length); } } public unsafe MemoryHandle Retain(bool pin = false) { MemoryHandle memoryHandle; if (pin) { if (_index < 0) { memoryHandle = ((OwnedMemory<T>)_arrayOrOwnedMemory).Pin(); memoryHandle.AddOffset((_index & RemoveOwnedFlagBitMask) * Unsafe.SizeOf<T>()); } else { var array = (T[])_arrayOrOwnedMemory; var handle = GCHandle.Alloc(array, GCHandleType.Pinned); void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref array.GetRawSzArrayData()), _index); memoryHandle = new MemoryHandle(null, pointer, handle); } } else { if (_index < 0) { ((OwnedMemory<T>)_arrayOrOwnedMemory).Retain(); memoryHandle = new MemoryHandle((OwnedMemory<T>)_arrayOrOwnedMemory); } else { memoryHandle = new MemoryHandle(null); } } return memoryHandle; } /// <summary> /// Get an array segment from the underlying memory. /// If unable to get the array segment, return false with a default array segment. /// </summary> public bool TryGetArray(out ArraySegment<T> arraySegment) { if (_index < 0) { if (((OwnedMemory<T>)_arrayOrOwnedMemory).TryGetArray(out var segment)) { arraySegment = new ArraySegment<T>(segment.Array, segment.Offset + (_index & RemoveOwnedFlagBitMask), _length); return true; } } else { arraySegment = new ArraySegment<T>((T[])_arrayOrOwnedMemory, _index, _length); return true; } arraySegment = default(ArraySegment<T>); return false; } /// <summary> /// Copies the contents from the memory into a new array. This heap /// allocates, so should generally be avoided, however it is sometimes /// necessary to bridge the gap with APIs written in terms of arrays. /// </summary> public T[] ToArray() => Span.ToArray(); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { if (obj is ReadOnlyMemory<T>) { return ((ReadOnlyMemory<T>)obj).Equals(this); } else if (obj is Memory<T> memory) { return Equals(memory); } else { return false; } } /// <summary> /// Returns true if the memory points to the same array and has the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public bool Equals(Memory<T> other) { return _arrayOrOwnedMemory == other._arrayOrOwnedMemory && _index == other._index && _length == other._length; } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return CombineHashCodes(_arrayOrOwnedMemory.GetHashCode(), (_index & RemoveOwnedFlagBitMask).GetHashCode(), _length.GetHashCode()); } private static int CombineHashCodes(int left, int right) { return ((left << 5) + left) ^ right; } private static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } } }
// *********************************************************************** // Copyright (c) 2008-2015 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.Compatibility; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Builders; namespace NUnit.Framework { /// <summary> /// TestCaseSourceAttribute indicates the source to be used to /// provide test cases for a test method. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)] public class TestCaseSourceAttribute : NUnitAttribute, ITestBuilder, IImplyFixture { private NUnitTestCaseBuilder _builder = new NUnitTestCaseBuilder(); #region Constructors /// <summary> /// Construct with the name of the method, property or field that will provide data /// </summary> /// <param name="sourceName">The name of a static method, property or field that will provide data.</param> public TestCaseSourceAttribute(string sourceName) { this.SourceName = sourceName; } /// <summary> /// Construct with a Type and name /// </summary> /// <param name="sourceType">The Type that will provide data</param> /// <param name="sourceName">The name of a static method, property or field that will provide data.</param> public TestCaseSourceAttribute(Type sourceType, string sourceName) { this.SourceType = sourceType; this.SourceName = sourceName; } /// <summary> /// Construct with a Type /// </summary> /// <param name="sourceType">The type that will provide data</param> public TestCaseSourceAttribute(Type sourceType) { this.SourceType = sourceType; } #endregion #region Properties /// <summary> /// The name of a the method, property or fiend to be used as a source /// </summary> public string SourceName { get; private set; } /// <summary> /// A Type to be used as a source /// </summary> public Type SourceType { get; private set; } /// <summary> /// Gets or sets the category associated with every fixture created from /// this attribute. May be a single category or a comma-separated list. /// </summary> public string Category { get; set; } #endregion #region ITestBuilder Members /// <summary> /// Construct one or more TestMethods from a given MethodInfo, /// using available parameter data. /// </summary> /// <param name="method">The IMethod for which tests are to be constructed.</param> /// <param name="suite">The suite to which the tests will be added.</param> /// <returns>One or more TestMethods</returns> public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test suite) { foreach (TestCaseParameters parms in GetTestCasesFor(method)) yield return _builder.BuildTestMethod(method, suite, parms); } #endregion #region Helper Methods /// <summary> /// Returns a set of ITestCaseDataItems for use as arguments /// to a parameterized test method. /// </summary> /// <param name="method">The method for which data is needed.</param> /// <returns></returns> private IEnumerable<ITestCaseData> GetTestCasesFor(IMethodInfo method) { List<ITestCaseData> data = new List<ITestCaseData>(); try { IEnumerable source = GetTestCaseSource(method); if (source != null) { #if NETCF int numParameters = method.IsGenericMethodDefinition ? 0 : method.GetParameters().Length; #else int numParameters = method.GetParameters().Length; #endif foreach (object item in source) { var parms = item as ITestCaseData; if (parms == null) { object[] args = item as object[]; if (args != null) { #if NETCF if (method.IsGenericMethodDefinition) { var mi = method.MakeGenericMethodEx(args); numParameters = mi == null ? 0 : mi.GetParameters().Length; } #endif if (args.Length != numParameters)//parameters.Length) args = new object[] { item }; } else if (item is Array) { Array array = item as Array; #if NETCF if (array.Rank == 1 && (method.IsGenericMethodDefinition || array.Length == numParameters))//parameters.Length)) #else if (array.Rank == 1 && array.Length == numParameters)//parameters.Length) #endif { args = new object[array.Length]; for (int i = 0; i < array.Length; i++) args[i] = array.GetValue(i); #if NETCF if (method.IsGenericMethodDefinition) { var mi = method.MakeGenericMethodEx(args); if (mi == null || array.Length != mi.GetParameters().Length) args = new object[] {item}; } #endif } else { args = new object[] { item }; } } else { args = new object[] { item }; } parms = new TestCaseParameters(args); } if (this.Category != null) foreach (string cat in this.Category.Split(new char[] { ',' })) parms.Properties.Add(PropertyNames.Category, cat); data.Add(parms); } } } catch (Exception ex) { data.Clear(); data.Add(new TestCaseParameters(ex)); } return data; } private IEnumerable GetTestCaseSource(IMethodInfo method) { Type sourceType = SourceType ?? method.TypeInfo.Type; // Handle Type implementing IEnumerable separately if (SourceName == null) return Reflect.Construct(sourceType) as IEnumerable; MemberInfo[] members = sourceType.GetMember(SourceName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); if (members.Length == 1) { MemberInfo member = members[0]; var field = member as FieldInfo; if (field != null) return field.IsStatic ? (IEnumerable)field.GetValue(null) : SourceMustBeStaticError(); var property = member as PropertyInfo; if (property != null) return property.GetGetMethod(true).IsStatic ? (IEnumerable)property.GetValue(null, null) : SourceMustBeStaticError(); var m = member as MethodInfo; if (m != null) return m.IsStatic ? (IEnumerable)m.Invoke(null, null) : SourceMustBeStaticError(); } return null; } private static IEnumerable SourceMustBeStaticError() { var parms = new TestCaseParameters(); parms.RunState = RunState.NotRunnable; parms.Properties.Set(PropertyNames.SkipReason, "The sourceName specified on a TestCaseSourceAttribute must refer to a static field, property or method."); return new TestCaseParameters[] { parms }; } #endregion } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Xml.Serialization; using System.Text; using Amazon.Runtime; using Amazon.S3.Util; using Amazon.Util; using System.Globalization; using Amazon.S3.Model.Internal.MarshallTransformations; namespace Amazon.S3.Model { /// <summary> /// Returns information about the GetObject response and response metadata. /// </summary> public partial class GetObjectResponse : StreamResponse { private string deleteMarker; private string acceptRanges; private Expiration expiration; private DateTime? restoreExpiration; private bool restoreInProgress; private DateTime? lastModified; private string eTag; private int? missingMeta; private string versionId; private DateTime? expires; private string websiteRedirectLocation; private ServerSideEncryptionMethod serverSideEncryption; private ServerSideEncryptionCustomerMethod serverSideEncryptionCustomerMethod; private string serverSideEncryptionKeyManagementServiceKeyId; private HeadersCollection headersCollection = new HeadersCollection(); private MetadataCollection metadataCollection = new MetadataCollection(); private ReplicationStatus replicationStatus; private S3StorageClass storageClass; private string bucketName; private string key; /// <summary> /// Flag which returns true if the Expires property has been unmarshalled /// from the raw value or set by user code. /// </summary> private bool isExpiresUnmarshalled; internal string RawExpires { get; set; } /// <summary> /// Gets and sets the BucketName property. /// </summary> public string BucketName { get { return this.bucketName; } set { this.bucketName = value; } } /// <summary> /// Gets and sets the Key property. /// </summary> public string Key { get { return this.key; } set { this.key = value; } } /// <summary> /// Specifies whether the object retrieved was (true) or was not (false) a Delete Marker. If false, this response header does not appear in the /// response. /// /// </summary> public string DeleteMarker { get { return this.deleteMarker; } set { this.deleteMarker = value; } } // Check to see if DeleteMarker property is set internal bool IsSetDeleteMarker() { return this.deleteMarker != null; } /// <summary> /// The collection of headers for the request. /// </summary> public HeadersCollection Headers { get { if (this.headersCollection == null) this.headersCollection = new HeadersCollection(); return this.headersCollection; } } /// <summary> /// The collection of meta data for the request. /// </summary> public MetadataCollection Metadata { get { if (this.metadataCollection == null) this.metadataCollection = new MetadataCollection(); return this.metadataCollection; } } /// <summary> /// Gets and sets the AcceptRanges. /// </summary> public string AcceptRanges { get { return this.acceptRanges; } set { this.acceptRanges = value; } } // Check to see if AcceptRanges property is set internal bool IsSetAcceptRanges() { return this.acceptRanges != null; } /// <summary> /// Gets and sets the Expiration property. /// Specifies the expiration date for the object and the /// rule governing the expiration. /// Is null if expiration is not applicable. /// </summary> public Expiration Expiration { get { return this.expiration; } set { this.expiration = value; } } // Check to see if Expiration property is set internal bool IsSetExpiration() { return this.expiration != null; } /// <summary> /// Gets and sets the RestoreExpiration property. /// RestoreExpiration will be set for objects that have been restored from Amazon Glacier. /// It indiciates for those objects how long the restored object will exist. /// </summary> public DateTime? RestoreExpiration { get { return this.restoreExpiration; } set { this.restoreExpiration = value; } } /// <summary> /// Gets and sets the RestoreInProgress /// Will be true when the object is in the process of being restored from Amazon Glacier. /// </summary> public bool RestoreInProgress { get { return this.restoreInProgress; } set { this.restoreInProgress = value; } } /// <summary> /// Last modified date of the object /// /// </summary> public DateTime LastModified { get { return this.lastModified ?? default(DateTime); } set { this.lastModified = value; } } // Check to see if LastModified property is set internal bool IsSetLastModified() { return this.lastModified.HasValue; } /// <summary> /// An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL /// /// </summary> public string ETag { get { return this.eTag; } set { this.eTag = value; } } // Check to see if ETag property is set internal bool IsSetETag() { return this.eTag != null; } /// <summary> /// This is set to the number of metadata entries not returned in x-amz-meta headers. This can happen if you create metadata using an API like /// SOAP that supports more flexible metadata than the REST API. For example, using SOAP, you can create metadata whose values are not legal /// HTTP headers. /// /// </summary> public int MissingMeta { get { return this.missingMeta ?? default(int); } set { this.missingMeta = value; } } // Check to see if MissingMeta property is set internal bool IsSetMissingMeta() { return this.missingMeta.HasValue; } /// <summary> /// Version of the object. /// /// </summary> public string VersionId { get { return this.versionId; } set { this.versionId = value; } } // Check to see if VersionId property is set internal bool IsSetVersionId() { return this.versionId != null; } /// <summary> /// The date and time at which the object is no longer cacheable. /// /// </summary> public DateTime Expires { get { if (this.isExpiresUnmarshalled) { return this.expires.Value; } else { this.expires = AmazonS3Util.ParseExpiresHeader(this.RawExpires, this.ResponseMetadata.RequestId); this.isExpiresUnmarshalled = true; return this.expires.Value; } } set { this.expires = value; this.isExpiresUnmarshalled = true; } } // Check to see if Expires property is set internal bool IsSetExpires() { return this.expires.HasValue; } /// <summary> /// If the bucket is configured as a website, redirects requests for this object to another object in the same bucket or to an external URL. /// Amazon S3 stores the value of this header in the object metadata. /// /// </summary> public string WebsiteRedirectLocation { get { return this.websiteRedirectLocation; } set { this.websiteRedirectLocation = value; } } // Check to see if WebsiteRedirectLocation property is set internal bool IsSetWebsiteRedirectLocation() { return this.websiteRedirectLocation != null; } /// <summary> /// The Server-side encryption algorithm used when storing this object in S3. /// /// </summary> public ServerSideEncryptionMethod ServerSideEncryptionMethod { get { return this.serverSideEncryption; } set { this.serverSideEncryption = value; } } // Check to see if ServerSideEncryptionMethod property is set internal bool IsSetServerSideEncryptionMethod() { return this.serverSideEncryption != null; } /// <summary> /// The class of storage used to store the object. /// /// </summary> public S3StorageClass StorageClass { get { return this.storageClass; } set { this.storageClass = value; } } // Check to see if StorageClass property is set internal bool IsSetStorageClass() { return this.storageClass != null; } /// <summary> /// The id of the AWS Key Management Service key that Amazon S3 uses to encrypt and decrypt the object. /// </summary> public string ServerSideEncryptionKeyManagementServiceKeyId { get { return this.serverSideEncryptionKeyManagementServiceKeyId; } set { this.serverSideEncryptionKeyManagementServiceKeyId = value; } } /// <summary> /// Checks if ServerSideEncryptionKeyManagementServiceKeyId property is set. /// </summary> /// <returns>true if ServerSideEncryptionKeyManagementServiceKeyId property is set.</returns> internal bool IsSetServerSideEncryptionKeyManagementServiceKeyId() { return !System.String.IsNullOrEmpty(this.serverSideEncryptionKeyManagementServiceKeyId); } /// <summary> /// The status of the replication job associated with this source object. /// </summary> public ReplicationStatus ReplicationStatus { get { return this.replicationStatus; } set { this.replicationStatus = value; } } /// <summary> /// Checks if ReplicationStatus property is set. /// </summary> /// <returns>true if ReplicationStatus property is set.</returns> internal bool IsSetReplicationStatus() { return ReplicationStatus != null; } #if BCL /// <summary> /// Writes the content of the ResponseStream a file indicated by the filePath argument. /// </summary> /// <param name="filePath">The location where to write the ResponseStream</param> public void WriteResponseStreamToFile(string filePath) { WriteResponseStreamToFile(filePath, false); } /// <summary> /// Writes the content of the ResponseStream a file indicated by the filePath argument. /// </summary> /// <param name="filePath">The location where to write the ResponseStream</param> /// <param name="append">Whether or not to append to the file if it exists</param> public void WriteResponseStreamToFile(string filePath, bool append) { CreateDirectory(filePath); Stream downloadStream = CreateDownloadStream(filePath, append); using (downloadStream) { long current = 0; byte[] buffer = new byte[S3Constants.DefaultBufferSize]; int bytesRead = 0; long totalIncrementTransferred = 0; while ((bytesRead = this.ResponseStream.Read(buffer, 0, buffer.Length)) > 0) { downloadStream.Write(buffer, 0, bytesRead); current += bytesRead; totalIncrementTransferred += bytesRead; if (totalIncrementTransferred >= AWSSDKUtils.DefaultProgressUpdateInterval || current == this.ContentLength) { this.OnRaiseProgressEvent(filePath, totalIncrementTransferred, current, this.ContentLength); totalIncrementTransferred = 0; } } ValidateWrittenStreamSize(current); } } private static Stream CreateDownloadStream(string filePath, bool append) { Stream downloadStream; if (append && File.Exists(filePath)) downloadStream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Read, S3Constants.DefaultBufferSize); else downloadStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, S3Constants.DefaultBufferSize); return downloadStream; } private static void CreateDirectory(string filePath) { // Make sure the directory exists to write too. FileInfo fi = new FileInfo(filePath); Directory.CreateDirectory(fi.DirectoryName); } #endif #region Progress Event /// <summary> /// The event for Write Object progress notifications. All /// subscribers will be notified when a new progress /// event is raised. /// </summary> /// <remarks> /// Subscribe to this event if you want to receive /// put object progress notifications. Here is how:<br /> /// 1. Define a method with a signature similar to this one: /// <code> /// private void displayProgress(object sender, WriteObjectProgressArgs args) /// { /// Console.WriteLine(args); /// } /// </code> /// 2. Add this method to the Put Object Progress Event delegate's invocation list /// <code> /// GetObjectResponse response = s3Client.GetObject(request); /// response.WriteObjectProgressEvent += displayProgress; /// </code> /// </remarks> public event EventHandler<WriteObjectProgressArgs> WriteObjectProgressEvent; #endregion /// <summary> /// This method is called by a producer of write object progress /// notifications. When called, all the subscribers in the /// invocation list will be called sequentially. /// </summary> /// <param name="file">The file being written.</param> /// <param name="incrementTransferred">The number of bytes transferred since last event</param> /// <param name="transferred">The number of bytes transferred</param> /// <param name="total">The total number of bytes to be transferred</param> internal void OnRaiseProgressEvent(string file, long incrementTransferred, long transferred, long total) { AWSSDKUtils.InvokeInBackground(WriteObjectProgressEvent, new WriteObjectProgressArgs(this.BucketName, this.Key, file, this.VersionId, incrementTransferred, transferred, total), this); } /// <summary> /// The Server-side encryption algorithm to be used with the customer provided key. /// /// </summary> public ServerSideEncryptionCustomerMethod ServerSideEncryptionCustomerMethod { get { if (this.serverSideEncryptionCustomerMethod == null) return ServerSideEncryptionCustomerMethod.None; return this.serverSideEncryptionCustomerMethod; } set { this.serverSideEncryptionCustomerMethod = value; } } private void ValidateWrittenStreamSize(long bytesWritten) { #if !PCL // Check if response stream or it's base stream is a AESDecryptionStream var stream = Runtime.Internal.Util.WrapperStream.SearchWrappedStream(this.ResponseStream, (s => s is Runtime.Internal.Util.DecryptStream)); // Don't validate length if response is an encrypted object. if (stream!=null) return; #endif if (bytesWritten != this.ContentLength) { string amzId2; this.ResponseMetadata.Metadata.TryGetValue(HeaderKeys.XAmzId2Header, out amzId2); amzId2 = amzId2 ?? string.Empty; var message = string.Format(CultureInfo.InvariantCulture, "The total bytes read {0} from response stream is not equal to the Content-Length {1} for the object {2} in bucket {3}."+ " Request ID = {4} , AmzId2 = {5}.", bytesWritten, this.ContentLength, this.Key, this.BucketName, this.ResponseMetadata.RequestId, amzId2); throw new StreamSizeMismatchException(message, this.ContentLength, bytesWritten, this.ResponseMetadata.RequestId, amzId2); } } } /// <summary> /// Encapsulates the information needed to provide /// download progress for the Write Object Event. /// </summary> public class WriteObjectProgressArgs : TransferProgressArgs { /// <summary> /// The constructor takes the number of /// currently transferred bytes and the /// total number of bytes to be transferred /// </summary> /// <param name="bucketName">The bucket name for the S3 object being written.</param> /// <param name="key">The object key for the S3 object being written.</param> /// <param name="versionId">The version-id of the S3 object.</param> /// <param name="incrementTransferred">The number of bytes transferred since last event</param> /// <param name="transferred">The number of bytes transferred</param> /// <param name="total">The total number of bytes to be transferred</param> internal WriteObjectProgressArgs(string bucketName, string key, string versionId, long incrementTransferred, long transferred, long total) : base(incrementTransferred, transferred, total) { this.BucketName = bucketName; this.Key = key; this.VersionId = versionId; } /// <summary> /// The constructor takes the number of /// currently transferred bytes and the /// total number of bytes to be transferred /// </summary> /// <param name="bucketName">The bucket name for the S3 object being written.</param> /// <param name="key">The object key for the S3 object being written.</param> /// <param name="filePath">The file for the S3 object being written.</param> /// <param name="versionId">The version-id of the S3 object.</param> /// <param name="incrementTransferred">The number of bytes transferred since last event</param> /// <param name="transferred">The number of bytes transferred</param> /// <param name="total">The total number of bytes to be transferred</param> internal WriteObjectProgressArgs(string bucketName, string key, string filePath, string versionId, long incrementTransferred, long transferred, long total) : base(incrementTransferred, transferred, total) { this.BucketName = bucketName; this.Key = key; this.VersionId = versionId; this.FilePath = filePath; } /// <summary> /// Gets the bucket name for the S3 object being written. /// </summary> public string BucketName { get; private set; } /// <summary> /// Gets the object key for the S3 object being written. /// </summary> public string Key { get; private set; } /// <summary> /// Gets the version-id of the S3 object. /// </summary> public string VersionId { get; private set; } /// <summary> /// The file for the S3 object being written. /// </summary> public string FilePath { get; private set; } } }
//----------------------------------------------------------------------- // <copyright file="FanOutShape.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; namespace Akka.Streams { /// <summary> /// TBD /// </summary> /// <typeparam name="TIn">TBD</typeparam> public abstract class FanOutShape<TIn> : Shape { #region internal classes /// <summary> /// TBD /// </summary> public interface IInit { /// <summary> /// TBD /// </summary> Inlet<TIn> Inlet { get; } /// <summary> /// TBD /// </summary> IEnumerable<Outlet> Outlets { get; } /// <summary> /// TBD /// </summary> string Name { get; } } /// <summary> /// TBD /// </summary> [Serializable] public sealed class InitName : IInit { /// <summary> /// TBD /// </summary> /// <param name="name">TBD</param> /// <exception cref="ArgumentNullException">TBD</exception> public InitName(string name) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); Name = name; Inlet = new Inlet<TIn>(name + ".in"); Outlets = Enumerable.Empty<Outlet>(); } /// <summary> /// TBD /// </summary> public Inlet<TIn> Inlet { get; } /// <summary> /// TBD /// </summary> public IEnumerable<Outlet> Outlets { get; } /// <summary> /// TBD /// </summary> public string Name { get; } } /// <summary> /// TBD /// </summary> [Serializable] public sealed class InitPorts : IInit { /// <summary> /// TBD /// </summary> /// <param name="inlet">TBD</param> /// <param name="outlets">TBD</param> /// <exception cref="ArgumentNullException">TBD</exception> public InitPorts(Inlet<TIn> inlet, IEnumerable<Outlet> outlets) { if (outlets == null) throw new ArgumentNullException(nameof(outlets)); if (inlet == null) throw new ArgumentNullException(nameof(inlet)); Inlet = inlet; Outlets = outlets; Name = "FanOut"; } /// <summary> /// TBD /// </summary> public Inlet<TIn> Inlet { get; } /// <summary> /// TBD /// </summary> public IEnumerable<Outlet> Outlets { get; } /// <summary> /// TBD /// </summary> public string Name { get; } } #endregion private readonly string _name; private ImmutableArray<Outlet> _outlets; private readonly IEnumerator<Outlet> _registered; /// <summary> /// TBD /// </summary> /// <param name="inlet">TBD</param> /// <param name="registered">TBD</param> /// <param name="name">TBD</param> protected FanOutShape(Inlet<TIn> inlet, IEnumerable<Outlet> registered, string name) { In = inlet; Inlets = ImmutableArray.Create<Inlet>(inlet); _outlets = ImmutableArray<Outlet>.Empty; _name = name; _registered = registered.GetEnumerator(); } /// <summary> /// TBD /// </summary> /// <param name="init">TBD</param> protected FanOutShape(IInit init) : this(init.Inlet, init.Outlets, init.Name) { } /// <summary> /// TBD /// </summary> public Inlet<TIn> In { get; } /// <summary> /// TBD /// </summary> public override ImmutableArray<Outlet> Outlets => _outlets; /// <summary> /// TBD /// </summary> public override ImmutableArray<Inlet> Inlets { get; } /// <summary> /// TBD /// </summary> /// <param name="init">TBD</param> /// <returns>TBD</returns> protected abstract FanOutShape<TIn> Construct(IInit init); /// <summary> /// TBD /// </summary> /// <param name="name">TBD</param> /// <returns>TBD</returns> protected Outlet<T> NewOutlet<T>(string name) { var p = _registered.MoveNext() ? (Outlet<T>)_registered.Current : new Outlet<T>($"{_name}.{name}"); _outlets = _outlets.Add(p); return p; } /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override Shape DeepCopy() => Construct(new InitPorts((Inlet<TIn>) In.CarbonCopy(), _outlets.Select(o => o.CarbonCopy()))); /// <summary> /// TBD /// </summary> /// <param name="inlets">TBD</param> /// <param name="outlets">TBD</param> /// <exception cref="ArgumentException">TBD</exception> /// <returns>TBD</returns> public sealed override Shape CopyFromPorts(ImmutableArray<Inlet> inlets, ImmutableArray<Outlet> outlets) { if (inlets.Length != 1) throw new ArgumentException( $"Proposed inlets [{string.Join(", ", inlets)}] do not fit FanOutShape"); if (outlets.Length != _outlets.Length) throw new ArgumentException( $"Proposed outlets [{string.Join(", ", outlets)}] do not fit FanOutShape"); return Construct(new InitPorts((Inlet<TIn>)inlets[0], outlets)); } } /// <summary> /// TBD /// </summary> /// <typeparam name="TIn">TBD</typeparam> /// <typeparam name="TOut">TBD</typeparam> public class UniformFanOutShape<TIn, TOut> : FanOutShape<TIn> { private readonly int _n; /// <summary> /// TBD /// </summary> /// <param name="n">TBD</param> /// <param name="init">TBD</param> public UniformFanOutShape(int n, IInit init) : base(init) { _n = n; Outs = Enumerable.Range(0, n).Select(i => NewOutlet<TOut>($"out{i}")).ToImmutableList(); } /// <summary> /// TBD /// </summary> /// <param name="n">TBD</param> public UniformFanOutShape(int n) : this(n, new InitName("UniformFanOut")) { } /// <summary> /// TBD /// </summary> /// <param name="n">TBD</param> /// <param name="name">TBD</param> public UniformFanOutShape(int n, string name) : this(n, new InitName(name)) { } /// <summary> /// TBD /// </summary> /// <param name="inlet">TBD</param> /// <param name="outlets">TBD</param> public UniformFanOutShape(Inlet<TIn> inlet, params Outlet<TOut>[] outlets) : this(outlets.Length, new InitPorts(inlet, outlets)) { } /// <summary> /// TBD /// </summary> public IImmutableList<Outlet<TOut>> Outs { get; } /// <summary> /// TBD /// </summary> /// <param name="n">TBD</param> /// <returns>TBD</returns> public Outlet<TOut> Out(int n) => Outs[n]; /// <summary> /// TBD /// </summary> /// <param name="init">TBD</param> /// <returns>TBD</returns> protected override FanOutShape<TIn> Construct(IInit init) => new UniformFanOutShape<TIn, TOut>(_n, init); } }
// -- FILE ------------------------------------------------------------------ // name : TimePeriodIntersectorTest.cs // project : Itenso Time Period // created : Jani Giannoudis - 2011.03.29 // language : C# 4.0 // environment: .NET 2.0 // copyright : (c) 2011-2012 by Itenso GmbH, Switzerland // -------------------------------------------------------------------------- using System; using Itenso.TimePeriod; using Xunit; namespace Itenso.TimePeriodTests { // ------------------------------------------------------------------------ public sealed class TimePeriodIntersectorTest : TestUnitBase { // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodIntersector")] [Fact] public void NoPeriodsTest() { TimePeriodIntersector<TimeRange> periodIntersector = new TimePeriodIntersector<TimeRange>(); ITimePeriodCollection periods = periodIntersector.IntersectPeriods( new TimePeriodCollection() ); Assert.Equal(0, periods.Count); } // NoPeriodsTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodIntersector")] [Fact] public void SinglePeriodAnytimeTest() { TimePeriodIntersector<TimeRange> periodIntersector = new TimePeriodIntersector<TimeRange>(); ITimePeriodCollection periods = periodIntersector.IntersectPeriods( new TimePeriodCollection { TimeRange.Anytime } ); Assert.Equal(0, periods.Count); } // SinglePeriodAnytimeTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodIntersector")] [Fact] public void MomentTest() { TimeRange period1 = new TimeRange( new DateTime( 2011, 3, 1 ), new DateTime( 2011, 3, 10 ) ); TimeRange period2 = new TimeRange( new DateTime( 2011, 3, 5 ), new DateTime( 2011, 3, 05 ) ); TimePeriodIntersector<TimeRange> periodIntersector = new TimePeriodIntersector<TimeRange>(); ITimePeriodCollection periods = periodIntersector.IntersectPeriods( new TimePeriodCollection { period1, period2 } ); Assert.Equal(0, periods.Count); } // MomentTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodIntersector")] [Fact] public void TouchingPeriodsTest() { TimeRange period1 = new TimeRange( new DateTime( 2011, 3, 01 ), new DateTime( 2011, 3, 05 ) ); TimeRange period2 = new TimeRange( new DateTime( 2011, 3, 05 ), new DateTime( 2011, 3, 10 ) ); TimeRange period3 = new TimeRange( new DateTime( 2011, 3, 10 ), new DateTime( 2011, 3, 14 ) ); TimePeriodIntersector<TimeRange> periodIntersector = new TimePeriodIntersector<TimeRange>(); ITimePeriodCollection periods = periodIntersector.IntersectPeriods( new TimePeriodCollection { period1, period2, period3 } ); Assert.Equal(0, periods.Count); } // TouchingPeriodsTest // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodIntersector")] [Fact] public void SingleIntersection1Test() { TimeRange period1 = new TimeRange( new DateTime( 2011, 3, 1 ), new DateTime( 2011, 3, 10 ) ); TimeRange period2 = new TimeRange( new DateTime( 2011, 3, 1 ), new DateTime( 2011, 3, 20 ) ); TimePeriodIntersector<TimeRange> periodIntersector = new TimePeriodIntersector<TimeRange>(); ITimePeriodCollection periods = periodIntersector.IntersectPeriods( new TimePeriodCollection { period1, period2 } ); Assert.Equal(1, periods.Count); Assert.True( periods[ 0 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 1 ), new DateTime( 2011, 3, 10 ) ) ) ); } // SingleIntersection1Test // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodIntersector")] [Fact] public void SingleIntersection2Test() { TimeRange period1 = new TimeRange( new DateTime( 2011, 3, 01 ), new DateTime( 2011, 3, 15 ) ); TimeRange period2 = new TimeRange( new DateTime( 2011, 3, 10 ), new DateTime( 2011, 3, 20 ) ); TimePeriodIntersector<TimeRange> periodIntersector = new TimePeriodIntersector<TimeRange>(); ITimePeriodCollection periods = periodIntersector.IntersectPeriods( new TimePeriodCollection { period1, period2 } ); Assert.Equal(1, periods.Count); Assert.True( periods[ 0 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 10 ), new DateTime( 2011, 3, 15 ) ) ) ); } // SingleIntersection2Test // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodIntersector")] [Fact] public void SingleIntersection3Test() { TimeRange period1 = new TimeRange( new DateTime( 2011, 3, 01 ), new DateTime( 2011, 3, 20 ) ); TimeRange period2 = new TimeRange( new DateTime( 2011, 3, 10 ), new DateTime( 2011, 3, 20 ) ); TimePeriodIntersector<TimeRange> periodIntersector = new TimePeriodIntersector<TimeRange>(); ITimePeriodCollection periods = periodIntersector.IntersectPeriods( new TimePeriodCollection { period1, period2 } ); Assert.Equal(1, periods.Count); Assert.True( periods[ 0 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 10 ), new DateTime( 2011, 3, 20 ) ) ) ); } // SingleIntersection3Test // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodIntersector")] [Fact] public void TouchingPeriodsWithIntersection1Test() { TimeRange period1 = new TimeRange( new DateTime( 2011, 3, 1 ), new DateTime( 2011, 3, 05 ) ); TimeRange period2 = new TimeRange( new DateTime( 2011, 3, 5 ), new DateTime( 2011, 3, 10 ) ); TimeRange period3 = new TimeRange( new DateTime( 2011, 3, 1 ), new DateTime( 2011, 3, 10 ) ); TimePeriodIntersector<TimeRange> periodIntersector = new TimePeriodIntersector<TimeRange>(); ITimePeriodCollection periods = periodIntersector.IntersectPeriods( new TimePeriodCollection { period1, period2, period3 } ); Assert.Equal(1, periods.Count); Assert.True( periods[ 0 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 1 ), new DateTime( 2011, 3, 10 ) ) ) ); } // TouchingPeriodsWithIntersection1Test // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodIntersector")] [Fact] public void TouchingPeriodsWithIntersection2Test() { TimeRange period1 = new TimeRange( new DateTime( 2011, 3, 01 ), new DateTime( 2011, 3, 20 ) ); TimeRange period2 = new TimeRange( new DateTime( 2011, 3, 01 ), new DateTime( 2011, 3, 05 ) ); TimeRange period3 = new TimeRange( new DateTime( 2011, 3, 15 ), new DateTime( 2011, 3, 20 ) ); TimePeriodIntersector<TimeRange> periodIntersector = new TimePeriodIntersector<TimeRange>(); ITimePeriodCollection periods = periodIntersector.IntersectPeriods( new TimePeriodCollection { period1, period2, period3 } ); Assert.Equal(2, periods.Count); Assert.True( periods[ 0 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 01 ), new DateTime( 2011, 3, 05 ) ) ) ); Assert.True( periods[ 1 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 15 ), new DateTime( 2011, 3, 20 ) ) ) ); } // TouchingPeriodsWithIntersection2Test // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodIntersector")] [Fact] public void MultipeTouchingIntersection1Test() { TimeRange period1 = new TimeRange( new DateTime( 2011, 3, 01 ), new DateTime( 2011, 3, 10 ) ); TimeRange period2 = new TimeRange( new DateTime( 2011, 3, 05 ), new DateTime( 2011, 3, 20 ) ); TimeRange period3 = new TimeRange( new DateTime( 2011, 3, 15 ), new DateTime( 2011, 3, 25 ) ); TimePeriodIntersector<TimeRange> periodIntersector = new TimePeriodIntersector<TimeRange>(); ITimePeriodCollection periods = periodIntersector.IntersectPeriods( new TimePeriodCollection { period1, period2, period3 } ); Assert.Equal(2, periods.Count); Assert.True( periods[ 0 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 05 ), new DateTime( 2011, 3, 10 ) ) ) ); Assert.True( periods[ 1 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 15 ), new DateTime( 2011, 3, 20 ) ) ) ); } // MultipeTouchingIntersection1Test // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodIntersector")] [Fact] public void MultipeTouchingIntersection2Test() { TimeRange period1 = new TimeRange( new DateTime( 2011, 3, 01 ), new DateTime( 2011, 3, 10 ) ); TimeRange period2 = new TimeRange( new DateTime( 2011, 3, 04 ), new DateTime( 2011, 3, 10 ) ); TimeRange period3 = new TimeRange( new DateTime( 2011, 3, 06 ), new DateTime( 2011, 3, 10 ) ); TimeRange period4 = new TimeRange( new DateTime( 2011, 3, 10 ), new DateTime( 2011, 3, 14 ) ); TimeRange period5 = new TimeRange( new DateTime( 2011, 3, 10 ), new DateTime( 2011, 3, 16 ) ); TimeRange period6 = new TimeRange( new DateTime( 2011, 3, 10 ), new DateTime( 2011, 3, 20 ) ); TimePeriodIntersector<TimeRange> periodIntersector = new TimePeriodIntersector<TimeRange>(); ITimePeriodCollection periods = periodIntersector.IntersectPeriods( new TimePeriodCollection { period1, period2, period3, period4, period5, period6 } ); Assert.Equal(1, periods.Count); Assert.True( periods[ 0 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 04 ), new DateTime( 2011, 3, 16 ) ) ) ); } // MultipeTouchingIntersection2Test // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodIntersector")] [Fact] public void MultipeTouchingIntersection3Test() { TimeRange period1 = new TimeRange( new DateTime( 2011, 3, 01 ), new DateTime( 2011, 3, 10 ) ); TimeRange period2 = new TimeRange( new DateTime( 2011, 3, 05 ), new DateTime( 2011, 3, 15 ) ); TimeRange period3 = new TimeRange( new DateTime( 2011, 3, 12 ), new DateTime( 2011, 3, 18 ) ); TimeRange period4 = new TimeRange( new DateTime( 2011, 3, 20 ), new DateTime( 2011, 3, 24 ) ); TimeRange period5 = new TimeRange( new DateTime( 2011, 3, 22 ), new DateTime( 2011, 3, 28 ) ); TimeRange period6 = new TimeRange( new DateTime( 2011, 3, 24 ), new DateTime( 2011, 3, 26 ) ); TimePeriodIntersector<TimeRange> periodIntersector = new TimePeriodIntersector<TimeRange>(); ITimePeriodCollection periods = periodIntersector.IntersectPeriods( new TimePeriodCollection { period1, period2, period3, period4, period5, period6 } ); Assert.Equal(3, periods.Count); Assert.True( periods[ 0 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 05 ), new DateTime( 2011, 3, 10 ) ) ) ); Assert.True( periods[ 1 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 12 ), new DateTime( 2011, 3, 15 ) ) ) ); Assert.True( periods[ 2 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 22 ), new DateTime( 2011, 3, 26 ) ) ) ); } // MultipeTouchingIntersection3Test // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodIntersector")] [Fact] public void NotCombinedIntersection1Test() { TimeRange period1 = new TimeRange( new DateTime( 2011, 3, 01 ), new DateTime( 2011, 3, 10 ) ); TimeRange period2 = new TimeRange( new DateTime( 2011, 3, 01 ), new DateTime( 2011, 3, 05 ) ); TimeRange period3 = new TimeRange( new DateTime( 2011, 3, 05 ), new DateTime( 2011, 3, 10 ) ); TimePeriodIntersector<TimeRange> periodIntersector = new TimePeriodIntersector<TimeRange>(); ITimePeriodCollection periods = periodIntersector.IntersectPeriods( new TimePeriodCollection { period1, period2, period3 }, false ); Assert.Equal(2, periods.Count); Assert.True( periods[ 0 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 01 ), new DateTime( 2011, 3, 05 ) ) ) ); Assert.True( periods[ 1 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 05 ), new DateTime( 2011, 3, 10 ) ) ) ); } // NotCombinedIntersection1Test // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodIntersector")] [Fact] public void NotCombinedIntersection2Test() { TimeRange period1 = new TimeRange( new DateTime( 2011, 3, 01 ), new DateTime( 2011, 3, 10 ) ); TimeRange period2 = new TimeRange( new DateTime( 2011, 3, 02 ), new DateTime( 2011, 3, 06 ) ); TimeRange period3 = new TimeRange( new DateTime( 2011, 3, 03 ), new DateTime( 2011, 3, 08 ) ); TimePeriodIntersector<TimeRange> periodIntersector = new TimePeriodIntersector<TimeRange>(); ITimePeriodCollection periods = periodIntersector.IntersectPeriods( new TimePeriodCollection { period1, period2, period3 }, false ); Assert.Equal(3, periods.Count); Assert.True( periods[ 0 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 02 ), new DateTime( 2011, 3, 03 ) ) ) ); Assert.True( periods[ 1 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 03 ), new DateTime( 2011, 3, 06 ) ) ) ); Assert.True( periods[ 2 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 06 ), new DateTime( 2011, 3, 08 ) ) ) ); } // NotCombinedIntersection2Test // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodIntersector")] [Fact] public void NotCombinedIntersection3Test() { TimeRange period1 = new TimeRange( new DateTime( 2011, 3, 01 ), new DateTime( 2011, 3, 10 ) ); TimeRange period2 = new TimeRange( new DateTime( 2011, 3, 02 ), new DateTime( 2011, 3, 08 ) ); TimeRange period3 = new TimeRange( new DateTime( 2011, 3, 04 ), new DateTime( 2011, 3, 06 ) ); TimePeriodIntersector<TimeRange> periodIntersector = new TimePeriodIntersector<TimeRange>(); ITimePeriodCollection periods = periodIntersector.IntersectPeriods( new TimePeriodCollection { period1, period2, period3 }, false ); Assert.Equal(3, periods.Count); Assert.True( periods[ 0 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 02 ), new DateTime( 2011, 3, 04 ) ) ) ); Assert.True( periods[ 1 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 04 ), new DateTime( 2011, 3, 06 ) ) ) ); Assert.True( periods[ 2 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 06 ), new DateTime( 2011, 3, 08 ) ) ) ); } // NotCombinedIntersection3Test // ---------------------------------------------------------------------- [Trait("Category", "TimePeriodIntersector")] [Fact] public void NotCombinedIntersection4Test() { TimeRange period1 = new TimeRange( new DateTime( 2011, 3, 01 ), new DateTime( 2011, 3, 10 ) ); TimeRange period2 = new TimeRange( new DateTime( 2011, 3, 01 ), new DateTime( 2011, 3, 05 ) ); TimeRange period3 = new TimeRange( new DateTime( 2011, 3, 04 ), new DateTime( 2011, 3, 06 ) ); TimeRange period4 = new TimeRange( new DateTime( 2011, 3, 05 ), new DateTime( 2011, 3, 10 ) ); TimePeriodIntersector<TimeRange> periodIntersector = new TimePeriodIntersector<TimeRange>(); ITimePeriodCollection periods = periodIntersector.IntersectPeriods( new TimePeriodCollection { period1, period2, period3, period4 }, false ); Assert.Equal(4, periods.Count); Assert.True( periods[ 0 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 01 ), new DateTime( 2011, 3, 04 ) ) ) ); Assert.True( periods[ 1 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 04 ), new DateTime( 2011, 3, 05 ) ) ) ); Assert.True( periods[ 2 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 05 ), new DateTime( 2011, 3, 06 ) ) ) ); Assert.True( periods[ 3 ].IsSamePeriod( new TimeRange( new DateTime( 2011, 3, 06 ), new DateTime( 2011, 3, 10 ) ) ) ); } // NotCombinedIntersection4Test } // class TimePeriodIntersectorTest } // namespace Itenso.TimePeriodTests // -- EOF -------------------------------------------------------------------
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace TekConf.Web.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System.Collections.Generic; using MLAPI.Serialization.Pooled; using MLAPI.Transports; namespace MLAPI.Messaging { /// <summary> /// QueueHistoryFrame /// Used by the RpcQueueContainer to hold queued RPCs /// All queued Rpcs end up in a PooledNetworkBuffer within a QueueHistoryFrame instance. /// </summary> public class RpcQueueHistoryFrame { public enum QueueFrameType { Inbound, Outbound, } public bool IsDirty; //Used to determine if this queue history frame has been reset (cleaned) yet public bool HasLoopbackData; //Used to determine if a dirt frame is dirty because rpcs are being looped back betwen HostClient and HostServer public uint TotalSize; public List<uint> QueueItemOffsets; public PooledNetworkBuffer QueueBuffer; public PooledNetworkWriter QueueWriter; public RpcQueueHistoryFrame LoopbackHistoryFrame; //Temporary fix for Host mode loopback work around. public PooledNetworkReader QueueReader; private int m_QueueItemOffsetIndex; private RpcFrameQueueItem m_CurrentQueueItem; private readonly QueueFrameType m_QueueFrameType; private int m_MaximumClients; private long m_CurrentStreamSizeMark; private NetworkUpdateStage m_StreamUpdateStage; //Update stage specific to RPCs (typically inbound has most potential for variation) private const int k_MaxStreamBounds = 131072; private const int k_MinStreamBounds = 0; /// <summary> /// GetQueueFrameType /// Returns whether this is an inbound or outbound frame /// </summary> /// <returns></returns> public QueueFrameType GetQueueFrameType() { return m_QueueFrameType; } /// <summary> /// MarkCurrentStreamSize /// Marks the current size of the stream (used primarily for sanity checks) /// </summary> public void MarkCurrentStreamPosition() { if (QueueBuffer != null) { m_CurrentStreamSizeMark = QueueBuffer.Position; } else { m_CurrentStreamSizeMark = 0; } } /// <summary> /// Returns the current position that was marked (to track size of RPC msg) /// </summary> /// <returns>m_CurrentStreamSizeMark</returns> public long GetCurrentMarkedPosition() { return m_CurrentStreamSizeMark; } /// <summary> /// GetCurrentQueueItem /// Internal method to get the current Queue Item from the stream at its current position /// </summary> /// <returns>FrameQueueItem</returns> private RpcFrameQueueItem GetCurrentQueueItem() { //Write the packed version of the queueItem to our current queue history buffer m_CurrentQueueItem.QueueItemType = (RpcQueueContainer.QueueItemType)QueueReader.ReadUInt16(); m_CurrentQueueItem.Timestamp = QueueReader.ReadSingle(); m_CurrentQueueItem.NetworkId = QueueReader.ReadUInt64(); //Clear out any current value for the client ids m_CurrentQueueItem.ClientNetworkIds = new ulong[0]; //If outbound, determine if any client ids needs to be added if (m_QueueFrameType == QueueFrameType.Outbound) { //Outbound we care about both channel and clients m_CurrentQueueItem.NetworkChannel = (NetworkChannel)QueueReader.ReadByteDirect(); int NumClients = QueueReader.ReadInt32(); if (NumClients > 0 && NumClients < m_MaximumClients) { ulong[] clientIdArray = new ulong[NumClients]; for (int i = 0; i < NumClients; i++) { clientIdArray[i] = QueueReader.ReadUInt64(); } if (m_CurrentQueueItem.ClientNetworkIds == null) { m_CurrentQueueItem.ClientNetworkIds = clientIdArray; } else { m_CurrentQueueItem.ClientNetworkIds = clientIdArray; } } } m_CurrentQueueItem.UpdateStage = m_StreamUpdateStage; //Get the stream size m_CurrentQueueItem.StreamSize = QueueReader.ReadInt64(); //Sanity checking for boundaries if (m_CurrentQueueItem.StreamSize < k_MaxStreamBounds && m_CurrentQueueItem.StreamSize > k_MinStreamBounds) { //Inbound and Outbound message streams are handled differently if (m_QueueFrameType == QueueFrameType.Inbound) { //Get our offset long Position = QueueReader.ReadInt64(); //Always make sure we are positioned at the start of the stream before we write m_CurrentQueueItem.NetworkBuffer.Position = 0; //Write the entire message to the m_CurrentQueueItem stream (1 stream is re-used for all incoming RPCs) m_CurrentQueueItem.NetworkWriter.ReadAndWrite(QueueReader, m_CurrentQueueItem.StreamSize); //Reset the position back to the offset so std rpc API can process the message properly //(i.e. minus the already processed header) m_CurrentQueueItem.NetworkBuffer.Position = Position; } else { //Create a byte array segment for outbound sending m_CurrentQueueItem.MessageData = QueueReader.CreateArraySegment((int)m_CurrentQueueItem.StreamSize, (int)QueueBuffer.Position); } } else { UnityEngine.Debug.LogWarning($"{nameof(m_CurrentQueueItem)}.{nameof(RpcFrameQueueItem.StreamSize)} exceeds allowed size ({k_MaxStreamBounds} vs {m_CurrentQueueItem.StreamSize})! Exiting from the current RpcQueue enumeration loop!"); m_CurrentQueueItem.QueueItemType = RpcQueueContainer.QueueItemType.None; } return m_CurrentQueueItem; } /// <summary> /// GetNextQueueItem /// Handles getting the next queue item from this frame /// If none are remaining, then it returns a queue item type of NONE /// </summary> /// <returns>FrameQueueItem</returns> internal RpcFrameQueueItem GetNextQueueItem() { QueueBuffer.Position = QueueItemOffsets[m_QueueItemOffsetIndex]; m_QueueItemOffsetIndex++; if (m_QueueItemOffsetIndex >= QueueItemOffsets.Count) { m_CurrentQueueItem.QueueItemType = RpcQueueContainer.QueueItemType.None; return m_CurrentQueueItem; } return GetCurrentQueueItem(); } /// <summary> /// GetFirstQueueItem /// Should be called the first time a queue item is pulled from a queue history frame. /// This will reset the frame's stream indices and add a new stream and stream writer to the m_CurrentQueueItem instance. /// </summary> /// <returns>FrameQueueItem</returns> internal RpcFrameQueueItem GetFirstQueueItem() { if (QueueBuffer.Position > 0) { m_QueueItemOffsetIndex = 0; QueueBuffer.Position = 0; if (m_QueueFrameType == QueueFrameType.Inbound) { if (m_CurrentQueueItem.NetworkBuffer == null) { m_CurrentQueueItem.NetworkBuffer = PooledNetworkBuffer.Get(); } if (m_CurrentQueueItem.NetworkWriter == null) { m_CurrentQueueItem.NetworkWriter = PooledNetworkWriter.Get(m_CurrentQueueItem.NetworkBuffer); } if (m_CurrentQueueItem.NetworkReader == null) { m_CurrentQueueItem.NetworkReader = PooledNetworkReader.Get(m_CurrentQueueItem.NetworkBuffer); } } return GetCurrentQueueItem(); } m_CurrentQueueItem.QueueItemType = RpcQueueContainer.QueueItemType.None; return m_CurrentQueueItem; } /// <summary> /// CloseQueue /// Should be called once all processing of the current frame is complete. /// This only closes the m_CurrentQueueItem's stream which is used as a "middle-man" (currently) /// for delivering the RPC message to the method requesting a queue item from a frame. /// </summary> public void CloseQueue() { if (m_CurrentQueueItem.NetworkWriter != null) { m_CurrentQueueItem.NetworkWriter.Dispose(); m_CurrentQueueItem.NetworkWriter = null; } if (m_CurrentQueueItem.NetworkReader != null) { m_CurrentQueueItem.NetworkReader.Dispose(); m_CurrentQueueItem.NetworkReader = null; } if (m_CurrentQueueItem.NetworkBuffer != null) { m_CurrentQueueItem.NetworkBuffer.Dispose(); m_CurrentQueueItem.NetworkBuffer = null; } } /// <summary> /// QueueHistoryFrame Constructor /// </summary> /// <param name="queueType">type of queue history frame (Inbound/Outbound)</param> public RpcQueueHistoryFrame(QueueFrameType queueType, NetworkUpdateStage updateStage, int maxClients = 512) { m_MaximumClients = maxClients; m_QueueFrameType = queueType; m_CurrentQueueItem = new RpcFrameQueueItem(); m_StreamUpdateStage = updateStage; } } }
// ByteFX.Data data access components for .Net // Copyright (C) 2002-2003 ByteFX, Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using System.Collections; using System.ComponentModel; #if WINDOWS using System.Drawing; using System.Windows.Forms; #endif namespace ByteFX.Data.MySqlClient.Designers { #if WINDOWS /// <summary> /// Summary description for EditConnectionString. /// </summary> public class EditConnectionString : System.Windows.Forms.Form { private System.Windows.Forms.Button buttonOK; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textServer; private System.Windows.Forms.TextBox textUser; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox textPassword; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox comboDatabase; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox textPort; private System.Windows.Forms.CheckBox useCompression; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public EditConnectionString() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } public string ConnectionString; /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.buttonOK = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.textServer = new System.Windows.Forms.TextBox(); this.textUser = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.textPassword = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.comboDatabase = new System.Windows.Forms.ComboBox(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.textPort = new System.Windows.Forms.TextBox(); this.useCompression = new System.Windows.Forms.CheckBox(); this.SuspendLayout(); // // buttonOK // this.buttonOK.Location = new System.Drawing.Point(67, 200); this.buttonOK.Name = "buttonOK"; this.buttonOK.TabIndex = 0; this.buttonOK.Text = "&OK"; this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click); // // buttonCancel // this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Location = new System.Drawing.Point(187, 200); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.TabIndex = 0; this.buttonCancel.Text = "&Cancel"; // // label1 // this.label1.Location = new System.Drawing.Point(12, 24); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(104, 16); this.label1.TabIndex = 1; this.label1.Text = "Mysql server name:"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // textServer // this.textServer.Location = new System.Drawing.Point(112, 20); this.textServer.Name = "textServer"; this.textServer.Size = new System.Drawing.Size(168, 20); this.textServer.TabIndex = 2; this.textServer.Text = ""; // // textUser // this.textUser.Location = new System.Drawing.Point(112, 76); this.textUser.Name = "textUser"; this.textUser.Size = new System.Drawing.Size(168, 20); this.textUser.TabIndex = 2; this.textUser.Text = ""; // // label2 // this.label2.Location = new System.Drawing.Point(68, 76); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(40, 16); this.label2.TabIndex = 1; this.label2.Text = "User:"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // textPassword // this.textPassword.Location = new System.Drawing.Point(112, 108); this.textPassword.Name = "textPassword"; this.textPassword.PasswordChar = '*'; this.textPassword.Size = new System.Drawing.Size(168, 20); this.textPassword.TabIndex = 2; this.textPassword.Text = ""; // // label3 // this.label3.Location = new System.Drawing.Point(44, 108); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(64, 16); this.label3.TabIndex = 1; this.label3.Text = "Password:"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // comboDatabase // this.comboDatabase.Location = new System.Drawing.Point(112, 160); this.comboDatabase.Name = "comboDatabase"; this.comboDatabase.Size = new System.Drawing.Size(168, 21); this.comboDatabase.TabIndex = 3; this.comboDatabase.DropDown += new System.EventHandler(this.comboDatabase_DropDown); // // label4 // this.label4.Location = new System.Drawing.Point(4, 164); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(104, 16); this.label4.TabIndex = 1; this.label4.Text = "Select a database:"; this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label5 // this.label5.Location = new System.Drawing.Point(72, 52); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(36, 16); this.label5.TabIndex = 1; this.label5.Text = "Port:"; this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // textPort // this.textPort.Location = new System.Drawing.Point(112, 48); this.textPort.Name = "textPort"; this.textPort.Size = new System.Drawing.Size(168, 20); this.textPort.TabIndex = 2; this.textPort.Text = ""; // // useCompression // this.useCompression.Location = new System.Drawing.Point(10, 132); this.useCompression.Name = "useCompression"; this.useCompression.RightToLeft = System.Windows.Forms.RightToLeft.Yes; this.useCompression.Size = new System.Drawing.Size(116, 24); this.useCompression.TabIndex = 4; this.useCompression.Text = "Use compression"; this.useCompression.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // EditConnectionString // this.AcceptButton = this.buttonOK; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.buttonCancel; this.ClientSize = new System.Drawing.Size(298, 239); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.useCompression, this.comboDatabase, this.textServer, this.label1, this.buttonOK, this.buttonCancel, this.textUser, this.label2, this.textPassword, this.label3, this.label4, this.label5, this.textPort}); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "EditConnectionString"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Edit Connection String"; this.Load += new System.EventHandler(this.EditConnectionString_Load); this.ResumeLayout(false); } #endregion MySqlConnection conn; private void EditConnectionString_Load(object sender, System.EventArgs e) { conn = new MySqlConnection(ConnectionString); textServer.Text = conn.DataSource; textUser.Text = conn.User; textPassword.Text = conn.Password; textPort.Text = conn.Port.ToString(); conn = null; } string GetString() { System.Text.StringBuilder s; s = new System.Text.StringBuilder(); s.Append("server=" + textServer.Text); s.Append(";port=" + textPort.Text); s.Append(";uid=" + textUser.Text); s.Append(";pwd=" + textPassword.Text); if (useCompression.Checked) { s.Append(";Use compression=true"); } if (comboDatabase.SelectedIndex != -1) s.Append(";Initial Catalog=" + comboDatabase.SelectedItem.ToString()); else s.Append(";Initial Catalog=" + comboDatabase.Text); return s.ToString(); } private void comboDatabase_DropDown(object sender, System.EventArgs e) { comboDatabase.Items.Clear(); comboDatabase.SelectedIndex = -1; try { conn = new MySqlConnection(GetString()); conn.Open(); MySqlCommand comm = new MySqlCommand("show databases",conn); MySqlDataReader r = (MySqlDataReader)comm.ExecuteReader(); while(r.Read()) { comboDatabase.Items.Add(r[0]); } r.Close(); conn.Close(); } catch(MySqlException) { } } private void buttonOK_Click(object sender, System.EventArgs e) { ConnectionString = GetString(); DialogResult = DialogResult.OK; Close(); } } #endif }
// Copyright (c) 2010, Armin Ronacher // Licensed under the BSD license, see LICENSE for more information using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; namespace BlockPuzzle { public class GamePane { private GameSession session; private Random rnd; private GameBlock[] regularBlocks; private GameBlock[] hardBlocks; private Texture cursorTexture; private float jitter; private GameBlockState[,] grid; private Vector2 position; private HashSet<GameBlockAnimation> activeAnimations; private int cursorColumn; private int cursorRow; private float scrollY; private float scrollSpeed; private bool fastScrollMode; private bool gameOver; private class ClearInfo { public enum ClearDirection { Row, Column }; public int Column; public int Row; public int Count; public ClearDirection Direction; public ClearInfo(int column, int row, int count, ClearDirection direction) { Column = column; Row = row; Count = count; Direction = direction; } } public GamePane(GameSession session, GameBlock[] regularBlocks, GameBlock[] hardBlocks, float posX, float posY) { this.session = session; this.regularBlocks = regularBlocks; this.hardBlocks = hardBlocks; this.rnd = new Random(session.Game.Random.Next()); grid = new GameBlockState[Columns, Rows]; position = new Vector2(posX, posY); jitter = 0.0f; scrollY = 0.0f; scrollSpeed = DefaultScrollSpeed; cursorColumn = 0; cursorRow = 1; cursorTexture = regularBlocks[0].Texture; activeAnimations = new HashSet<GameBlockAnimation>(); for (int column = 0; column < Columns; column++) for (int row = 0; row < Rows; row++) grid[column, row] = new GameBlockState(this, column, row, (float)rnd.NextDouble()); PopulateWithRandomBlocks(7); } /// <summary> /// Returns a random game block from the available soft /// game blocks. /// </summary> public GameBlock GetRandomBlock() { return regularBlocks[rnd.Next() % regularBlocks.Length]; } /// <summary> /// Populates the game to a given height with random blocks. These /// blocks are placed in a way that they cannot be cleared automatically. /// </summary> public void PopulateWithRandomBlocks(int height) { for (int row = 0; row < height; row++) InsertNewRow(true); } /// <summary> /// Inserts a new row at the bottom. This also moves all rows up. /// The row placed is always safe row wise which means that they will not /// clear itself partially once placed. Optionally the same can be enabled /// for rows which is used to fill the initial space. /// </summary> public void InsertNewRow(bool safeColumns) { Color4 lastColor; int consecutiveBlocks = 0; MoveRowsUp(); for (int column = 0; column < Columns; column++) { GameBlock newBlock = GetRandomBlock(); while ((newBlock.Color == lastColor && consecutiveBlocks >= 1) || (safeColumns && !this[column, 1].Empty && newBlock.Color == this[column, 1].Block.Color)) newBlock = GetRandomBlock(); if (newBlock.Color == lastColor) { consecutiveBlocks++; } else { lastColor = newBlock.Color; consecutiveBlocks = 0; } this[column, 0].Block = newBlock; } // no point in clearing if safe columns are in use. We never generate a // pattern in rows that could be cleared anyways, and if safe columns are // enabled we also won't create patterns that can be cleared the other // way round. if (!safeColumns) TryClear(); } /// <summary> /// Drops a new hard line onto the game field and applies gravity. /// </summary> public void DropHardLine() { int topRow = Rows - 1; GameBlock hardBlock = hardBlocks[rnd.Next() % hardBlocks.Length]; for (int column = 0; column < Columns; column++) this[column, topRow].Block = hardBlock; TryClear(); } /// <summary> /// Moves all rows up. Used internally by InsertNewRow(). /// </summary> protected void MoveRowsUp() { for (int row = Rows - 2; row >= 0; row--) for (int column = 0; column < Columns; column++) this[column, row].MoveUp(); foreach (GameBlockAnimation blockAnimation in activeAnimations) blockAnimation.MoveUp(); } /// <summary> /// Tests for line clearing. This also applies gravity as necessary. Usually /// not necessary to call this externally as it happens automatically when /// lines are dropped, inserted from the bottom and after each exchange. /// This also checks if the game is over. /// </summary> public void TryClear() { bool tryClear = true; int clearCount = 0; int lineCount = 0; while (tryClear) { List<ClearInfo> toClear = new List<ClearInfo>(); TryClearRows(toClear); TryClearColumns(toClear); lineCount += toClear.Count; foreach (ClearInfo info in toClear) { switch (info.Direction) { case ClearInfo.ClearDirection.Row: for (var column = info.Column; column < info.Column + info.Count; column++) { this[column, info.Row].Clear(); TryBreakHardBlock(column, info.Row + 1); } break; case ClearInfo.ClearDirection.Column: for (var row = info.Row; row < info.Row + info.Count; row++) this[info.Column, row].Clear(); TryBreakHardBlock(info.Column, info.Row + info.Count); break; } clearCount += info.Count; } tryClear = ApplyGravity(); } if (clearCount > 0) OnBlocksCleared(clearCount, lineCount); CheckForGameOver(); } /// <summary> /// Implements the logic to break hard rows into soft blocks. Hard blocks are /// broken up into soft ones when something next to them is cleared. /// </summary> private void TryBreakHardBlock(int column, int row) { if (row >= Rows) return; GameBlockState blockState = this[column, row]; if (!blockState.Hard) return; for (int probeColumn = 0; probeColumn < Columns; probeColumn++) this[probeColumn, row].MakeSoftBlock(); } /// <summary> /// Helper for TryClear() that clears row wise. /// </summary> private void TryClearRows(List<ClearInfo> toClear) { for (int row = 1; row < Rows; row++) { for (int column = 0; column < Columns - 1; ) { int columnStart = column; GameBlockState thisState = this[column++, row]; if (thisState.Empty || thisState.Hard) continue; Color4 color = thisState.Block.Color; int inTheRow = 1; for (; column < Columns; column++, inTheRow++) { GameBlockState otherState = this[column, row]; if (otherState.Empty || color != otherState.Block.Color) break; } if (inTheRow >= 3) toClear.Add(new ClearInfo(columnStart, row, inTheRow, ClearInfo.ClearDirection.Row)); } } } /// <summary> /// Helper for TryClear() that clears column wise. /// </summary> private void TryClearColumns(List<ClearInfo> toClear) { for (int column = 0; column < Columns; column++) { for (int row = 1; row < Rows - 1; ) { int rowStart = row; GameBlockState thisState = this[column, row++]; if (thisState.Empty || thisState.Hard) continue; Color4 color = thisState.Block.Color; int inTheColumn = 1; for (; row < Rows; row++, inTheColumn++) { GameBlockState otherState = this[column, row]; if (otherState.Empty || color != otherState.Block.Color) break; } if (inTheColumn >= 3) toClear.Add(new ClearInfo(column, rowStart, inTheColumn, ClearInfo.ClearDirection.Column)); } } } /// <summary> /// Applies gravity. This is automatically called with TryClear(). /// </summary> private bool ApplyGravity() { bool tryClearAgain = false; for (int row = 1; row < Rows; row++) { for (int column = 0; column < Columns; column++) { GameBlockState thisState = this[column, row]; if (thisState.Empty) { continue; } else if (thisState.Hard) { ApplyGravityOnHardRow(row); continue; } GameBlockState lowestState = null; for (int lowerRow = row - 1; lowerRow > 0; lowerRow--) { GameBlockState otherState = this[column, lowerRow]; if (!otherState.Empty) break; lowestState = otherState; } if (lowestState != null) { thisState.MoveDown(lowestState); tryClearAgain = true; } } } return tryClearAgain; } /// <summary> /// Applies gravity on hard rows. Hard blocks always have to be rows /// so when the first hard block is found this is called instead of /// the regular gravity logic for the whole row. /// </summary> private void ApplyGravityOnHardRow(int row) { int column; int rowToFallDownTo = -1; for (int probeRow = row - 1; probeRow > 1; probeRow--) { for (column = 0; column < Columns; column++) { if (!this[column, probeRow].Empty) break; } if (column != Columns) break; rowToFallDownTo = probeRow; } if (rowToFallDownTo >= 0) for (column = 0; column < Columns; column++) this[column, row].MoveDown(this[column, rowToFallDownTo]); } /// <summary> /// Helper function that checks if the game over condition was triggered. /// Sets the gameOver flag, explodes blocks and calls into OnGameOver(). /// </summary> private void CheckForGameOver() { for (int column = 0; column < Columns; column++) { if (!this[column, Rows - 1].Empty) { gameOver = true; ExplodeAllBlocks(); OnGameOver(); } } } /// <summary> /// Replaces all blocks with animations of exploding blocks. /// </summary> private void ExplodeAllBlocks() { for (int row = 0; row < Rows; row++) for (int column = 0; column < Columns; column++) this[column, row].Explode(); } /// <summary> /// Callback for cleared blocks that notifies the session. /// </summary> public void OnBlocksCleared(int blockCount, int lineCount) { if (Session.Running) Session.OnBlocksCleared(this, blockCount, lineCount); } /// <summary> /// Callback for game over situation that notifies the session. /// </summary> public void OnGameOver() { if (Session.Running) Session.OnGameOver(this); } public void Update(FrameEventArgs args) { jitter = (jitter + (float)args.Time * 7.0f) % 360.0f; if (!gameOver) { scrollY += (float)args.Time * (fastScrollMode ? 150.0f : scrollSpeed); if (scrollY >= BlockSize) { scrollY -= BlockSize; InsertNewRow(false); MoveCursorUp(); } } if (Math.Sin(jitter * 50) > 0.5f) cursorTexture = regularBlocks[rnd.Next() % regularBlocks.Length].Texture; HashSet<GameBlockAnimation> toDelete = new HashSet<GameBlockAnimation>(); foreach (GameBlockAnimation blockAnimation in activeAnimations) if (!blockAnimation.Update(args)) toDelete.Add(blockAnimation); foreach (GameBlockAnimation blockAnimation in toDelete) activeAnimations.Remove(blockAnimation); for (int column = 0; column < Columns; column++) for (int row = 0; row < Rows; row++) this[column, row].UpdateAnimation(args); } public void Draw(DrawContext ctx) { List<GameBlockState> deferredBlocks = new List<GameBlockState>(); float scale = 1.0f + (float)Math.Sin(jitter * 0.5f) * 0.003f; float angle = (float)Math.Sin(jitter * 0.5) * 0.15f; ctx.Push(); ctx.Translate(position.X, position.Y); ctx.ScaleAroundPoint(scale, scale, Columns * BlockSize / 2, Rows * BlockSize / 2); ctx.RotateAroundPoint(angle, Columns * BlockSize / 3, Rows * BlockSize / 3); // cursor if (!gameOver) { ctx.Push(); ctx.Translate(GetBlockX(cursorColumn) - 4, GetBlockY(cursorRow) - 4); ctx.BindTexture(cursorTexture); ctx.SetColor(new Color4(100, 100, 100, 255)); ctx.DrawTexturedRectangle(BlockSize * 2.0f + 8, BlockSize + 8, cursorTexture); ctx.Pop(); // game over logo } else { ctx.Push(); ctx.Translate(40.0f, 240.0f); ctx.BindTexture(session.GameOverTexture); ctx.DrawTexturedRectangle(240.0f, 45.0f, session.GameOverTexture); ctx.Pop(); } // regular blocks for (int column = 0; column < Columns; column++) { for (int row = 0; row < Rows; row++) { GameBlockState blockState = this[column, row]; if (blockState.Empty) continue; if (blockState.DrawDeferred) deferredBlocks.Add(blockState); else blockState.Draw(ctx); } } // block independent block animations foreach (GameBlockAnimation animation in activeAnimations) animation.Draw(ctx); // top and bottom bars that hide partial rows if (!gameOver) { ctx.Push(); ctx.BindTexture(session.BarTexture); ctx.SetColor(new Color4(40, 40, 40, 255)); ctx.Translate(-BlockSize / 2, -35.0f); ctx.DrawTexturedRectangle(BlockSize * (Columns + 1), 40.0f, session.BarTexture); ctx.Translate(0.0f, BlockSize * Rows - BlockSize / 2); ctx.DrawTexturedRectangle(BlockSize * (Columns + 1), 50.0f, session.BarTexture); ctx.Pop(); } // selected blocks and other things we want to have on top foreach (GameBlockState blockState in deferredBlocks) blockState.Draw(ctx); ctx.Pop(); } public void MoveCursorUp() { if (cursorRow < Rows - 1) cursorRow++; } public void MoveCursorDown() { if (cursorRow > 1) cursorRow--; } public void MoveCursorLeft() { if (cursorColumn > 0) cursorColumn--; } public void MoveCursorRight() { if (cursorColumn < Columns - 2) cursorColumn++; } /// <summary> /// Exchanges the two blocks under the cursor. /// </summary> public void PerformExchange() { GameBlockState blockState = this[cursorColumn, cursorRow]; if (blockState.Hard) return; blockState.ExchangeWith(this[cursorColumn + 1, cursorRow]); TryClear(); } /// <summary> /// Registers a new block animation for this pane. /// </summary> public void AddAnimation(GameBlockAnimation animation) { activeAnimations.Add(animation); } public void IncreaseSpeed() { float newSpeed = scrollSpeed + SpeedChangeValue; scrollSpeed = Math.Min(MaximumScrollSpeed, newSpeed); } public void DecreaseSpeed() { float newSpeed = scrollSpeed - SpeedChangeValue; scrollSpeed = Math.Max(MinimumScrollSpeed, newSpeed); } public float GetBlockX(int column) { return column * BlockSize; } public float GetBlockY(int row) { return (Rows - row - 1) * BlockSize - ScrollY; } public GameSession Session { get { return session; } } public GameBlockState this[int column, int row] { get { return grid[column, row]; } set { grid[column, row] = value; } } public float Jitter { get { return jitter; } } public Vector2 Position { get { return position; } } public int CursorColumn { get { return cursorColumn; } } public int CursorRow { get { return cursorRow; } } public float BlockSize { get { return 32.0f; } } public int Columns { get { return 10; } } public int Rows { get { return 18; } } public float ScrollSpeed { get { return scrollSpeed; } set { scrollSpeed = value; } } public float DefaultScrollSpeed { get { return 6.0f; } } public float MinimumScrollSpeed { get { return 4.0f; } } public float MaximumScrollSpeed { get { return 20.0f; } } public float SpeedChangeValue { get { return 4.0f; } } public bool FastScrollMode { get { return fastScrollMode; } set { fastScrollMode = value; } } public float ScrollY { get { return scrollY; } } public bool GameOver { get { return gameOver; } } } }
using System; using System.Drawing; using System.Drawing.Imaging; using Hydra.Framework.ImageProcessing.Analysis; namespace Hydra.Framework.ImageProcessing.Analysis.Filters { // //********************************************************************** /// <summary> /// ReplaceChannel class /// </summary> //********************************************************************** // public class ReplaceChannel : IFilter { #region Private Member Variables // //********************************************************************** /// <summary> /// RBG Channel /// </summary> //********************************************************************** // private short channel_m = RGB.R; // //********************************************************************** /// <summary> /// Change Image bitmap /// </summary> //********************************************************************** // private Bitmap channelImage_m; #endregion #region Properties // //********************************************************************** /// <summary> /// Gets or sets the channel property. /// </summary> /// <value>The channel.</value> //********************************************************************** // public short Channel { get { return channel_m; } set { channel_m = value; } } // //********************************************************************** /// <summary> /// Gets or sets the channel image property. /// </summary> /// <value>The channel image.</value> //********************************************************************** // public Bitmap ChannelImage { get { return channelImage_m; } set { // // check for not null // if (value == null) throw new NullReferenceException(); // // check for valid format // if (value.PixelFormat != PixelFormat.Format8bppIndexed) throw new ArgumentException(); channelImage_m = value; } } #endregion #region Constructors // //********************************************************************** /// <summary> /// Initialises a new instance of the <see cref="T:ReplaceChannel"/> class. /// </summary> //********************************************************************** // public ReplaceChannel() { } // //********************************************************************** /// <summary> /// Initialises a new instance of the <see cref="T:ReplaceChannel"/> class. /// </summary> /// <param name="channelImage">The channel image.</param> //********************************************************************** // public ReplaceChannel(Bitmap channelImage) { if (channelImage.PixelFormat != PixelFormat.Format8bppIndexed) throw new ArgumentException(); this.channelImage_m = channelImage; } // //********************************************************************** /// <summary> /// Initialises a new instance of the <see cref="T:ReplaceChannel"/> class. /// </summary> /// <param name="channel">The channel.</param> //********************************************************************** // public ReplaceChannel(short channel) { this.channel_m = channel; } // //********************************************************************** /// <summary> /// Initialises a new instance of the <see cref="T:ReplaceChannel"/> class. /// </summary> /// <param name="channelImage">The channel image.</param> /// <param name="channel">The channel.</param> //********************************************************************** // public ReplaceChannel(Bitmap channelImage, short channel) : this(channelImage) { this.channel_m = channel; } #endregion #region Public Methods // //********************************************************************** /// <summary> /// Apply filter /// Output image will have the same dimension as source image /// </summary> /// <param name="srcImg">The SRC img.</param> /// <returns></returns> //********************************************************************** // public Bitmap Apply(Bitmap srcImg) { // // get source image size // int width = srcImg.Width; int height = srcImg.Height; // // overlay dimension // int ovrW = channelImage_m.Width; int ovrH = channelImage_m.Height; // // 1. source image and overlay must have the same width and height // 2. source image must be RGB // if ((srcImg.PixelFormat != PixelFormat.Format24bppRgb) || (width != ovrW) || (height != ovrH)) throw new ArgumentException(); // // lock source bitmap data // BitmapData srcData = srcImg.LockBits( new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); // // create new image // Bitmap dstImg = new Bitmap(width, height, PixelFormat.Format24bppRgb); // // lock destination bitmap data // BitmapData dstData = dstImg.LockBits( new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); // // lock overlay image // BitmapData ovrData = channelImage_m.LockBits( new Rectangle(0, 0, ovrW, ovrH), ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed); int offset = srcData.Stride - width * 3; int offsetOvr = ovrData.Stride - width; // // do the job (Warning Unsafe Code) // unsafe { byte * src = (byte *) srcData.Scan0.ToPointer(); byte * dst = (byte *) dstData.Scan0.ToPointer(); byte * ovr = (byte *) ovrData.Scan0.ToPointer(); // // for each line // for (int y = 0; y < height; y++) { // // for each pixel // for (int x = 0; x < width; x++, src += 3, dst += 3, ovr ++) { dst[RGB.R] = src[RGB.R]; dst[RGB.G] = src[RGB.G]; dst[RGB.B] = src[RGB.B]; dst[channel_m] = *ovr; } src += offset; dst += offset; ovr += offsetOvr; } } // // unlock all images // dstImg.UnlockBits(dstData); srcImg.UnlockBits(srcData); channelImage_m.UnlockBits(ovrData); return dstImg; } #endregion } }